forked from lukencode/FluentEmail
-
Notifications
You must be signed in to change notification settings - Fork 0
/
MailKitSender.cs
270 lines (235 loc) · 9.53 KB
/
MailKitSender.cs
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
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
using FluentEmail.Core;
using FluentEmail.Core.Interfaces;
using FluentEmail.Core.Models;
using MailKit.Net.Smtp;
using MimeKit;
using System;
using System.IO;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
namespace FluentEmail.MailKitSmtp
{
/// <summary>
/// Send emails with the MailKit Library.
/// </summary>
public class MailKitSender : ISender
{
private readonly SmtpClientOptions _smtpClientOptions;
/// <summary>
/// Creates a sender that uses the given SmtpClientOptions when sending with MailKit. Since the client is internal this will dispose of the client.
/// </summary>
/// <param name="smtpClientOptions">The SmtpClientOptions to use to create the MailKit client</param>
public MailKitSender(SmtpClientOptions smtpClientOptions)
{
_smtpClientOptions = smtpClientOptions;
}
/// <summary>
/// Send the specified email.
/// </summary>
/// <returns>A response with any errors and a success boolean.</returns>
/// <param name="email">Email.</param>
/// <param name="token">Cancellation Token.</param>
public SendResponse Send(IFluentEmail email, CancellationToken? token = null)
{
var response = new SendResponse();
var message = CreateMailMessage(email);
if (token?.IsCancellationRequested ?? false)
{
response.ErrorMessages.Add("Message was cancelled by cancellation token.");
return response;
}
try
{
if (_smtpClientOptions.UsePickupDirectory)
{
this.SaveToPickupDirectory(message, _smtpClientOptions.MailPickupDirectory).Wait();
return response;
}
using (var client = new SmtpClient())
{
if (_smtpClientOptions.SocketOptions.HasValue)
{
client.Connect(
_smtpClientOptions.Server,
_smtpClientOptions.Port,
_smtpClientOptions.SocketOptions.Value,
token.GetValueOrDefault());
}
else
{
client.Connect(
_smtpClientOptions.Server,
_smtpClientOptions.Port,
_smtpClientOptions.UseSsl,
token.GetValueOrDefault());
}
// Note: only needed if the SMTP server requires authentication
if (_smtpClientOptions.RequiresAuthentication)
{
client.Authenticate(_smtpClientOptions.User, _smtpClientOptions.Password, token.GetValueOrDefault());
}
client.Send(message, token.GetValueOrDefault());
client.Disconnect(true, token.GetValueOrDefault());
}
}
catch (Exception ex)
{
response.ErrorMessages.Add(ex.Message);
}
return response;
}
/// <summary>
/// Send the specified email.
/// </summary>
/// <returns>A response with any errors and a success boolean.</returns>
/// <param name="email">Email.</param>
/// <param name="token">Cancellation Token.</param>
public async Task<SendResponse> SendAsync(IFluentEmail email, CancellationToken? token = null)
{
var response = new SendResponse();
var message = CreateMailMessage(email);
if (token?.IsCancellationRequested ?? false)
{
response.ErrorMessages.Add("Message was cancelled by cancellation token.");
return response;
}
try
{
if (_smtpClientOptions.UsePickupDirectory)
{
await this.SaveToPickupDirectory(message, _smtpClientOptions.MailPickupDirectory);
return response;
}
using (var client = new SmtpClient())
{
if (_smtpClientOptions.SocketOptions.HasValue)
{
await client.ConnectAsync(
_smtpClientOptions.Server,
_smtpClientOptions.Port,
_smtpClientOptions.SocketOptions.Value,
token.GetValueOrDefault());
}
else
{
await client.ConnectAsync(
_smtpClientOptions.Server,
_smtpClientOptions.Port,
_smtpClientOptions.UseSsl,
token.GetValueOrDefault());
}
// Note: only needed if the SMTP server requires authentication
if (_smtpClientOptions.RequiresAuthentication)
{
await client.AuthenticateAsync(_smtpClientOptions.User, _smtpClientOptions.Password, token.GetValueOrDefault());
}
await client.SendAsync(message, token.GetValueOrDefault());
await client.DisconnectAsync(true, token.GetValueOrDefault());
}
}
catch (Exception ex)
{
response.ErrorMessages.Add(ex.Message);
}
return response;
}
/// <summary>
/// Saves email to a pickup directory.
/// </summary>
/// <param name="message">Message to save for pickup.</param>
/// <param name="pickupDirectory">Pickup directory.</param>
private async Task SaveToPickupDirectory(MimeMessage message, string pickupDirectory)
{
// Note: this will require that you know where the specified pickup directory is.
var path = Path.Combine(pickupDirectory, Guid.NewGuid().ToString() + ".eml");
if (File.Exists(path))
return;
try
{
using (var stream = new FileStream(path, FileMode.CreateNew))
{
await message.WriteToAsync(stream);
return;
}
}
catch (IOException)
{
// The file may have been created between our File.Exists() check and
// our attempt to create the stream.
throw;
}
}
/// <summary>
/// Create a MimMessage so MailKit can send it
/// </summary>
/// <returns>The mail message.</returns>
/// <param name="email">Email data.</param>
private MimeMessage CreateMailMessage(IFluentEmail email)
{
var data = email.Data;
var message = new MimeMessage();
// fixes https://github.com/lukencode/FluentEmail/issues/228
// if for any reason, subject header is not added, add it else update it.
if (!message.Headers.Contains(HeaderId.Subject))
message.Headers.Add(HeaderId.Subject, Encoding.UTF8, data.Subject ?? string.Empty);
else
message.Headers[HeaderId.Subject] = data.Subject ?? string.Empty;
message.Headers.Add(HeaderId.Encoding, Encoding.UTF8.EncodingName);
message.From.Add(new MailboxAddress(data.FromAddress.Name, data.FromAddress.EmailAddress));
var builder = new BodyBuilder();
if (!string.IsNullOrEmpty(data.PlaintextAlternativeBody))
{
builder.TextBody = data.PlaintextAlternativeBody;
builder.HtmlBody = data.Body;
}
else if (!data.IsHtml)
{
builder.TextBody = data.Body;
}
else
{
builder.HtmlBody = data.Body;
}
data.Attachments.ForEach(x =>
{
var attachment = builder.Attachments.Add(x.Filename, x.Data, ContentType.Parse(x.ContentType));
attachment.ContentId = x.ContentId;
});
message.Body = builder.ToMessageBody();
foreach (var header in data.Headers)
{
message.Headers.Add(header.Key, header.Value);
}
data.ToAddresses.ForEach(x =>
{
message.To.Add(new MailboxAddress(x.Name, x.EmailAddress));
});
data.CcAddresses.ForEach(x =>
{
message.Cc.Add(new MailboxAddress(x.Name, x.EmailAddress));
});
data.BccAddresses.ForEach(x =>
{
message.Bcc.Add(new MailboxAddress(x.Name, x.EmailAddress));
});
data.ReplyToAddresses.ForEach(x =>
{
message.ReplyTo.Add(new MailboxAddress(x.Name, x.EmailAddress));
});
switch (data.Priority)
{
case Priority.Low:
message.Priority = MessagePriority.NonUrgent;
break;
case Priority.Normal:
message.Priority = MessagePriority.Normal;
break;
case Priority.High:
message.Priority = MessagePriority.Urgent;
break;
}
return message;
}
}
}