-
Notifications
You must be signed in to change notification settings - Fork 143
Expand file tree
/
Copy pathMailKitEmailHelper.cs
More file actions
228 lines (188 loc) · 8.33 KB
/
Copy pathMailKitEmailHelper.cs
File metadata and controls
228 lines (188 loc) · 8.33 KB
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
using System;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Mail;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using MailKit.Net.Smtp;
using MailKit.Security;
using MimeKit;
using MimeKit.Utils;
using Shesha.Configuration;
namespace Shesha.Email
{
internal static class MailKitEmailHelper
{
public static MimeMessage ConvertToMimeMessage(MailMessage mail)
{
if (mail == null)
throw new ArgumentNullException(nameof(mail));
var message = new MimeMessage();
if (mail.From != null)
message.From.Add(CreateMailboxAddress(mail.From));
foreach (var address in mail.To.Cast<MailAddress>())
{
message.To.Add(CreateMailboxAddress(address));
}
foreach (var address in mail.CC.Cast<MailAddress>())
{
message.Cc.Add(CreateMailboxAddress(address));
}
foreach (var address in mail.Bcc.Cast<MailAddress>())
{
message.Bcc.Add(CreateMailboxAddress(address));
}
message.Subject = mail.Subject ?? string.Empty;
foreach (var headerKey in mail.Headers.AllKeys)
{
var value = mail.Headers[headerKey];
if (!string.IsNullOrEmpty(headerKey) && !string.IsNullOrEmpty(value))
{
message.Headers.Replace(headerKey, value);
}
}
var builder = new BodyBuilder();
var htmlView = mail.AlternateViews
.Cast<AlternateView>()
.FirstOrDefault(v => string.Equals(v.ContentType.MediaType, "text", StringComparison.OrdinalIgnoreCase)
&& string.Equals(v.ContentType.MediaSubtype, "html", StringComparison.OrdinalIgnoreCase));
if (htmlView != null)
{
builder.HtmlBody = ReadAlternateView(htmlView);
AddLinkedResources(builder, htmlView);
}
else if (mail.IsBodyHtml)
{
builder.HtmlBody = mail.Body;
}
else
{
builder.TextBody = mail.Body;
}
foreach (var alternateView in mail.AlternateViews.Cast<AlternateView>())
{
if (alternateView == htmlView)
continue;
if (string.Equals(alternateView.ContentType.MediaType, "text", StringComparison.OrdinalIgnoreCase)
&& string.Equals(alternateView.ContentType.MediaSubtype, "plain", StringComparison.OrdinalIgnoreCase))
{
builder.TextBody = ReadAlternateView(alternateView);
}
}
foreach (var attachment in mail.Attachments.Cast<Attachment>())
{
builder.Attachments.Add(CreateAttachmentPart(attachment));
}
message.Body = builder.ToMessageBody();
return message;
}
public static async Task SendAsync(MimeMessage message, SmtpSettings settings, CancellationToken cancellationToken = default)
{
if (settings == null)
throw new ArgumentNullException(nameof(settings));
using var smtpClient = new SmtpClient();
await smtpClient.ConnectAsync(settings.Host, settings.Port, GetSecureSocketOption(settings), cancellationToken).ConfigureAwait(false);
var credential = CreateCredential(settings);
if (credential != null)
{
await smtpClient.AuthenticateAsync(credential, cancellationToken).ConfigureAwait(false);
}
await smtpClient.SendAsync(message, cancellationToken).ConfigureAwait(false);
await smtpClient.DisconnectAsync(true, cancellationToken).ConfigureAwait(false);
}
public static void Send(MimeMessage message, SmtpSettings settings, CancellationToken cancellationToken = default)
{
if (settings == null)
throw new ArgumentNullException(nameof(settings));
using var smtpClient = new SmtpClient();
smtpClient.Connect(settings.Host, settings.Port, GetSecureSocketOption(settings), cancellationToken);
var credential = CreateCredential(settings);
if (credential != null)
{
smtpClient.Authenticate(credential, cancellationToken);
}
smtpClient.Send(message, cancellationToken);
smtpClient.Disconnect(true, cancellationToken);
}
private static void AddLinkedResources(BodyBuilder builder, AlternateView view)
{
foreach (var resource in view.LinkedResources.Cast<LinkedResource>())
{
builder.LinkedResources.Add(CreateLinkedResource(resource));
}
}
private static MimeEntity CreateAttachmentPart(Attachment attachment)
{
var mediaType = attachment.ContentType.MediaType ?? "application";
var mediaSubType = attachment.ContentType.MediaSubtype ?? "octet-stream";
var mimePart = new MimePart(mediaType, mediaSubType)
{
Content = new MimeContent(CopyToMemoryStream(attachment.ContentStream)),
ContentDisposition = new ContentDisposition(ContentDisposition.Attachment),
ContentTransferEncoding = ContentEncoding.Base64,
FileName = attachment.Name
};
return mimePart;
}
private static MimeEntity CreateLinkedResource(LinkedResource resource)
{
var mediaType = resource.ContentType.MediaType ?? "application";
var mediaSubType = resource.ContentType.MediaSubtype ?? "octet-stream";
var mimePart = new MimePart(mediaType, mediaSubType)
{
Content = new MimeContent(CopyToMemoryStream(resource.ContentStream)),
ContentDisposition = new ContentDisposition(ContentDisposition.Inline),
ContentTransferEncoding = ContentEncoding.Base64,
ContentId = string.IsNullOrWhiteSpace(resource.ContentId) ? MimeUtils.GenerateMessageId() : resource.ContentId,
FileName = resource.ContentId
};
return mimePart;
}
private static MemoryStream CopyToMemoryStream(Stream stream)
{
var memoryStream = new MemoryStream();
if (stream.CanSeek)
stream.Position = 0;
stream.CopyTo(memoryStream);
memoryStream.Position = 0;
return memoryStream;
}
private static MailboxAddress CreateMailboxAddress(MailAddress address)
{
return string.IsNullOrEmpty(address.DisplayName)
? MailboxAddress.Parse(address.Address)
: new MailboxAddress(address.DisplayName, address.Address);
}
private static string ReadAlternateView(AlternateView view)
{
var encoding = !string.IsNullOrWhiteSpace(view.ContentType.CharSet)
? Encoding.GetEncoding(view.ContentType.CharSet)
: Encoding.UTF8;
if (view.ContentStream.CanSeek)
view.ContentStream.Position = 0;
using var reader = new StreamReader(view.ContentStream, encoding, detectEncodingFromByteOrderMarks: true, leaveOpen: true);
var content = reader.ReadToEnd();
if (view.ContentStream.CanSeek)
view.ContentStream.Position = 0;
return content;
}
private static NetworkCredential? CreateCredential(SmtpSettings settings)
{
if (string.IsNullOrWhiteSpace(settings.UserName))
return null;
return string.IsNullOrWhiteSpace(settings.Domain)
? new NetworkCredential(settings.UserName, settings.Password)
: new NetworkCredential(settings.UserName, settings.Password, settings.Domain);
}
private static SecureSocketOptions GetSecureSocketOption(SmtpSettings settings)
{
if (!settings.EnableSsl)
return SecureSocketOptions.None;
return settings.Port == 465
? SecureSocketOptions.SslOnConnect
: SecureSocketOptions.StartTls;
}
}
}