-
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathMailKitEmailSender.cs
88 lines (73 loc) · 2.45 KB
/
MailKitEmailSender.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
using System;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using IOKode.OpinionatedFramework.Emailing;
using MailKit.Net.Smtp;
using MimeKit;
namespace IOKode.OpinionatedFramework.ContractImplementations.MailKit;
public class MailKitEmailSender : IEmailSender, IDisposable
{
private readonly MailKitOptions _options;
private readonly SmtpClient _client;
public MailKitEmailSender(MailKitOptions options)
{
_options = options;
_client = new SmtpClient();
}
public async Task SendAsync(Email email, CancellationToken cancellationToken)
{
try
{
await _connectAsync(cancellationToken);
if (_options.Authenticate)
{
await _client.AuthenticateAsync(_options.Username, _options.Password, cancellationToken);
}
var message = new MimeMessage();
var bodyBuilder = new BodyBuilder();
message.Subject = email.Subject;
message.MessageId = email.MessageId.ToString();
message.From.Add(MailboxAddress.Parse(email.From.ToString()));
message.To.AddRange(email.To.Select(to => MailboxAddress.Parse(to.ToString())));
if (email.ReplyTo != null)
{
message.ReplyTo.Add(MailboxAddress.Parse(email.ReplyTo.ToString()));
}
if (email.TextContent != null)
{
bodyBuilder.TextBody = email.TextContent;
}
if (email.HtmlContent != null)
{
bodyBuilder.HtmlBody = email.HtmlContent;
}
foreach (var attachment in email.Attachments)
{
await bodyBuilder.Attachments.AddAsync(attachment.FileName, attachment.Content, cancellationToken);
}
message.Body = bodyBuilder.ToMessageBody();
await _client.SendAsync(message, cancellationToken);
}
catch (Exception ex)
{
throw new EmailException(ex);
}
finally
{
await _client.DisconnectAsync(true, cancellationToken);
}
}
public void Dispose()
{
_client.Dispose();
}
private async Task _connectAsync(CancellationToken cancellationToken)
{
if (_client.IsConnected)
{
return;
}
await _client.ConnectAsync(_options.Host, _options.Port, _options.Secure, cancellationToken);
}
}