summaryrefslogtreecommitdiffstats
path: root/SendGrid/SendGridMail/Transport/Web.cs
blob: 4d2f484a274499f383c39980a99425b1fbe6d7e7 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Reflection;
using System.Threading.Tasks;
using System.Xml;
using Exceptions;
using SendGrid.SmtpApi;

// ReSharper disable MemberCanBePrivate.Global
namespace SendGrid
{
	public class Web : ITransport
	{
		#region Properties

		//TODO: Make this configurable
		public const String Endpoint = "https://api.sendgrid.com/api/mail.send.xml";
	    
		private readonly NetworkCredential _credentials;
	    private readonly HttpClient _client;

		#endregion

		/// <summary>
		///     Creates a new Web interface for sending mail
		/// </summary>
		/// <param name="credentials">SendGridMessage user parameters</param>
        public Web(NetworkCredential credentials)
            : this(credentials, TimeSpan.FromSeconds(100)) { }

        /// <summary>
        ///     Creates a new Web interface for sending mail.
        /// </summary>
        /// <param name="credentials">SendGridMessage user parameters</param>
        /// <param name="httpTimeout">HTTP request timeout</param>
	    public Web(NetworkCredential credentials, TimeSpan httpTimeout)
	    {
        	_credentials = credentials;
            _client = new HttpClient();
            
            var version = Assembly.GetExecutingAssembly().GetName().Version.ToString();
            _client.DefaultRequestHeaders.TryAddWithoutValidation("User-Agent", "sendgrid/" + version + ";csharp");
            _client.Timeout = httpTimeout;
	    }

		/// <summary>
		///     Asynchronously delivers a message over SendGrid's Web interface
		/// </summary>
		/// <param name="message"></param>
		public async Task DeliverAsync(ISendGrid message)
		{
			var content = new MultipartFormDataContent();
			AttachFormParams(message, content);
			AttachFiles(message, content);
			var response = await _client.PostAsync(Endpoint, content);
			await CheckForErrorsAsync(response);
		}

	    #region Support Methods

		private void AttachFormParams(ISendGrid message, MultipartFormDataContent content)
		{
			var formParams = FetchFormParams(message);
			foreach (var keyValuePair in formParams)
			{
				content.Add(new StringContent(keyValuePair.Value), keyValuePair.Key);
			}
		}

		private void AttachFiles(ISendGrid message, MultipartFormDataContent content)
		{
			var files = FetchFileBodies(message);
			foreach (var file in files)
			{
				var fs = new FileStream(file.Key, FileMode.Open, FileAccess.Read);
				var fileContent = new StreamContent(fs);

				fileContent.Headers.ContentDisposition = new ContentDispositionHeaderValue("form-data")
				{
					Name = "files[" + Path.GetFileName(file.Key) + "]",
					FileName = Path.GetFileName(file.Key)
				};

				fileContent.Headers.ContentType = MediaTypeHeaderValue.Parse("application/octet-stream");
				content.Add(fileContent);
			}

			var streamingFiles = FetchStreamingFileBodies(message);
			foreach (var file in streamingFiles)
			{
				var stream = file.Value;
				var fileContent = new StreamContent(stream);

				fileContent.Headers.ContentDisposition = new ContentDispositionHeaderValue("form-data")
				{
					Name = "files[" + Path.GetFileName(file.Key) + "]",
					FileName = Path.GetFileName(file.Key)
				};

				fileContent.Headers.ContentType = MediaTypeHeaderValue.Parse("application/octet-stream");
				content.Add(fileContent);
			}
		}

		private static void FindErrorsInResponse(Stream content)
		{
			using (var reader = XmlReader.Create(content))
			{
				while (reader.Read())
				{
					if (!reader.IsStartElement()) continue;
					switch (reader.Name)
					{
						case "result":
							break;
						case "message": // success
							if (reader.ReadToNextSibling("errors"))
								throw new ProtocolViolationException();
							return;
						case "error": // failure
							throw new ProtocolViolationException();
						default:
							throw new ArgumentException("Unknown element: " + reader.Name);
					}
				}
			}
		}

		private static string[] GetErrorsInResponse(Stream content)
		{
			var xmlDoc = new XmlDocument();
			xmlDoc.Load(content);
			return (from XmlNode errorNode in xmlDoc.SelectNodes("//error") select errorNode.InnerText).ToArray();
		}

		private static async Task CheckForErrorsAsync(HttpResponseMessage response)
		{
			var content = await response.Content.ReadAsStreamAsync();

		    var errors = GetErrorsInResponse(content);

            // API error
            if (errors.Any())
                throw new InvalidApiRequestException(response.StatusCode, errors, response.ReasonPhrase);

            // Other error
            if (response.StatusCode != HttpStatusCode.OK)
                FindErrorsInResponse(content);
		}

		internal List<KeyValuePair<String, String>> FetchFormParams(ISendGrid message)
		{
			var result = new List<KeyValuePair<string, string>>
			{
				new KeyValuePair<String, String>("api_user", _credentials.UserName),
				new KeyValuePair<String, String>("api_key", _credentials.Password),
				new KeyValuePair<String, String>("headers",
					message.Headers.Count == 0 ? null : Utils.SerializeDictionary(message.Headers)),
				new KeyValuePair<String, String>("replyto",
					message.ReplyTo.Length == 0 ? null : message.ReplyTo.ToList().First().Address),
				new KeyValuePair<String, String>("from", message.From.Address),
				new KeyValuePair<String, String>("fromname", message.From.DisplayName),
				new KeyValuePair<String, String>("subject", message.Subject),
				new KeyValuePair<String, String>("text", message.Text),
				new KeyValuePair<String, String>("html", message.Html),
				new KeyValuePair<String, String>("x-smtpapi", message.Header.JsonString() ?? "")
			};
			if (message.To != null)
			{
				result = result.Concat(message.To.ToList().Select(a => new KeyValuePair<String, String>("to[]", a.Address)))
					.Concat(message.To.ToList().Select(a => new KeyValuePair<String, String>("toname[]", a.DisplayName)))
					.ToList();
			}

		    if (message.Cc != null)
		    {
		        result.AddRange(message.Cc.Select(c => new KeyValuePair<string, string>("cc[]", c.Address)));
		    }

		    if (message.Bcc != null)
		    {
		        result.AddRange(message.Bcc.Select(c => new KeyValuePair<string, string>("bcc[]", c.Address)));
		    }
            
			if (message.GetEmbeddedImages().Count > 0) {
				result = result.Concat(message.GetEmbeddedImages().ToList().Select(x => new KeyValuePair<String, String>(string.Format("content[{0}]", x.Key), x.Value)))
					.ToList();
			}
			return result.Where(r => !String.IsNullOrEmpty(r.Value)).ToList();
		}

		internal IEnumerable<KeyValuePair<string, MemoryStream>> FetchStreamingFileBodies(ISendGrid message)
		{
			return message.StreamedAttachments.Select(kvp => kvp).ToList();
		}

		internal List<KeyValuePair<String, FileInfo>> FetchFileBodies(ISendGrid message)
		{
			return message.Attachments == null
				? new List<KeyValuePair<string, FileInfo>>()
				: message.Attachments.Select(name => new KeyValuePair<String, FileInfo>(name, new FileInfo(name))).ToList();
		}

		#endregion
	}
}