-
Notifications
You must be signed in to change notification settings - Fork 442
/
Copy pathSmtpSender.cs
219 lines (189 loc) · 7.13 KB
/
SmtpSender.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
using FluentEmail.Core;
using FluentEmail.Core.Interfaces;
using FluentEmail.Core.Models;
using System;
using System.Net.Mail;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
namespace FluentEmail.Smtp
{
public class SmtpSender : ISender
{
private readonly Func<SmtpClient> _clientFactory;
private readonly SmtpClient _smtpClient;
/// <summary>
/// Creates a sender using the default SMTP settings.
/// </summary>
public SmtpSender() : this(() => new SmtpClient())
{
}
/// <summary>
/// Creates a sender that uses the factory to create and dispose an SmtpClient with each email sent.
/// </summary>
/// <param name="clientFactory"></param>
public SmtpSender(Func<SmtpClient> clientFactory)
{
_clientFactory = clientFactory;
}
/// <summary>
/// Creates a sender that uses the given SmtpClient, but does not dispose it.
/// </summary>
/// <param name="smtpClient"></param>
public SmtpSender(SmtpClient smtpClient)
{
_smtpClient = smtpClient;
}
public SendResponse Send(IFluentEmail email, CancellationToken? token = null)
{
// Uses task.run to negate Synchronisation Context
// see: https://stackoverflow.com/questions/28333396/smtpclient-sendmailasync-causes-deadlock-when-throwing-a-specific-exception/28445791#28445791
return Task.Run(() => SendAsync(email, token)).Result;
}
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;
}
if (_smtpClient == null)
{
using (var client = _clientFactory())
{
await client.SendMailExAsync(message, token ?? default);
}
}
else
{
await _smtpClient.SendMailExAsync(message, token ?? default);
}
return response;
}
private MailMessage CreateMailMessage(IFluentEmail email)
{
var data = email.Data;
MailMessage message = null;
// Smtp seems to require the HTML version as the alternative.
if (!string.IsNullOrEmpty(data.PlaintextAlternativeBody))
{
message = new MailMessage
{
Subject = data.Subject,
Body = data.PlaintextAlternativeBody,
IsBodyHtml = false,
From = new MailAddress(data.FromAddress.EmailAddress, data.FromAddress.Name)
};
var mimeType = new System.Net.Mime.ContentType("text/html; charset=UTF-8");
AlternateView alternate = AlternateView.CreateAlternateViewFromString(data.Body, mimeType);
message.AlternateViews.Add(alternate);
}
else
{
message = new MailMessage
{
Subject = data.Subject,
Body = data.Body,
IsBodyHtml = data.IsHtml,
BodyEncoding = Encoding.UTF8,
SubjectEncoding = Encoding.UTF8,
From = new MailAddress(data.FromAddress.EmailAddress, data.FromAddress.Name)
};
}
foreach (var header in data.Headers)
{
message.Headers.Add(header.Key, header.Value);
}
data.ToAddresses.ForEach(x =>
{
message.To.Add(new MailAddress(x.EmailAddress, x.Name));
});
data.CcAddresses.ForEach(x =>
{
message.CC.Add(new MailAddress(x.EmailAddress, x.Name));
});
data.BccAddresses.ForEach(x =>
{
message.Bcc.Add(new MailAddress(x.EmailAddress, x.Name));
});
data.ReplyToAddresses.ForEach(x =>
{
message.ReplyToList.Add(new MailAddress(x.EmailAddress, x.Name));
});
switch (data.Priority)
{
case Priority.Low:
message.Priority = MailPriority.Low;
break;
case Priority.Normal:
message.Priority = MailPriority.Normal;
break;
case Priority.High:
message.Priority = MailPriority.High;
break;
}
data.Attachments.ForEach(x =>
{
System.Net.Mail.Attachment a = new System.Net.Mail.Attachment(x.Data, x.Filename, x.ContentType);
a.ContentId = x.ContentId;
message.Attachments.Add(a);
});
return message;
}
}
// Taken from https://stackoverflow.com/questions/28333396/smtpclient-sendmailasync-causes-deadlock-when-throwing-a-specific-exception/28445791#28445791
// SmtpClient causes deadlock when throwing exceptions. This fixes that.
public static class SendMailEx
{
public static Task SendMailExAsync(
this SmtpClient @this,
MailMessage message,
CancellationToken token = default(CancellationToken))
{
// use Task.Run to negate SynchronizationContext
return Task.Run(() => SendMailExImplAsync(@this, message, token));
}
private static async Task SendMailExImplAsync(
SmtpClient client,
MailMessage message,
CancellationToken token)
{
token.ThrowIfCancellationRequested();
var tcs = new TaskCompletionSource<bool>();
SendCompletedEventHandler handler = null;
Action unsubscribe = () => client.SendCompleted -= handler;
handler = async (_, e) =>
{
unsubscribe();
// a hack to complete the handler asynchronously
await Task.Yield();
if (e.UserState != tcs)
tcs.TrySetException(new InvalidOperationException("Unexpected UserState"));
else if (e.Cancelled)
tcs.TrySetCanceled();
else if (e.Error != null)
tcs.TrySetException(e.Error);
else
tcs.TrySetResult(true);
};
client.SendCompleted += handler;
try
{
client.SendAsync(message, tcs);
using (token.Register(() =>
{
client.SendAsyncCancel();
}, useSynchronizationContext: false))
{
await tcs.Task;
}
}
finally
{
unsubscribe();
}
}
}
}