| | | 1 | | // ----------------------------------------------------------------------- |
| | | 2 | | // <copyright file="MailKitService.cs" company="Stéphane ANDRE"> |
| | | 3 | | // Copyright (c) Stéphane ANDRE. All rights reserved. |
| | | 4 | | // </copyright> |
| | | 5 | | // ----------------------------------------------------------------------- |
| | | 6 | | |
| | | 7 | | using System; |
| | | 8 | | using System.Diagnostics.CodeAnalysis; |
| | | 9 | | using System.IO; |
| | | 10 | | using System.Linq; |
| | | 11 | | using System.Text; |
| | | 12 | | using System.Threading; |
| | | 13 | | using System.Threading.Tasks; |
| | | 14 | | using MailKit.Net.Smtp; |
| | | 15 | | using Microsoft.Extensions.Logging; |
| | | 16 | | using MimeKit; |
| | | 17 | | using MyNet.Mail.MailKit.Exceptions; |
| | | 18 | | using MyNet.Mail.Models; |
| | | 19 | | using MyNet.Mail.Smtp; |
| | | 20 | | using MyNet.Utilities; |
| | | 21 | | using MyNet.Utilities.Logging; |
| | | 22 | | |
| | | 23 | | namespace MyNet.Mail.MailKit; |
| | | 24 | | |
| | | 25 | | /// <summary> |
| | | 26 | | /// Sends email through MailKit using the supplied <see cref="SmtpClientOptions"/>. |
| | | 27 | | /// Reuses a single SMTP connection per service instance; call <see cref="Dispose"/> when done. |
| | | 28 | | /// </summary> |
| | | 29 | | /// <param name="smtpClientOptions">SMTP settings for this sender.</param> |
| | | 30 | | /// <param name="logger">Optional logger; defaults to <see cref="Log.Create{T}"/>.</param> |
| | | 31 | | public sealed partial class MailKitService(SmtpClientOptions smtpClientOptions, ILogger? logger = null) : IMailService, |
| | | 32 | | { |
| | 24 | 33 | | private readonly ILogger _logger = logger ?? Log.Create<MailKitService>(); |
| | 24 | 34 | | private readonly MailKitSmtpConnectionManager _connectionManager = new(smtpClientOptions); |
| | | 35 | | private bool _disposed; |
| | | 36 | | |
| | | 37 | | /// <summary> |
| | | 38 | | /// Builds a <see cref="MimeMessage"/> from <see cref="IEmail"/> data. |
| | | 39 | | /// </summary> |
| | | 40 | | public static MimeMessage CreateMailMessage(IEmail email, Encoding? preferredEncoding = null) |
| | | 41 | | { |
| | 36 | 42 | | ArgumentNullException.ThrowIfNull(email); |
| | | 43 | | |
| | 33 | 44 | | var data = email.Data; |
| | 33 | 45 | | var encoding = preferredEncoding ?? Encoding.UTF8; |
| | | 46 | | |
| | 33 | 47 | | var message = new MimeMessage { Subject = data.Subject }; |
| | | 48 | | |
| | 33 | 49 | | message.From.Add(new MailboxAddress(data.From.Name, data.From.Address)); |
| | | 50 | | |
| | 132 | 51 | | foreach (var address in data.To) |
| | | 52 | | { |
| | 33 | 53 | | message.To.Add(new MailboxAddress(address.Name, address.Address)); |
| | | 54 | | } |
| | | 55 | | |
| | 72 | 56 | | foreach (var address in data.Cc) |
| | | 57 | | { |
| | 3 | 58 | | message.Cc.Add(new MailboxAddress(address.Name, address.Address)); |
| | | 59 | | } |
| | | 60 | | |
| | 72 | 61 | | foreach (var address in data.Bcc) |
| | | 62 | | { |
| | 3 | 63 | | message.Bcc.Add(new MailboxAddress(address.Name, address.Address)); |
| | | 64 | | } |
| | | 65 | | |
| | 72 | 66 | | foreach (var address in data.ReplyTo) |
| | | 67 | | { |
| | 3 | 68 | | message.ReplyTo.Add(new MailboxAddress(address.Name, address.Address)); |
| | | 69 | | } |
| | | 70 | | |
| | 33 | 71 | | var builder = new BodyBuilder(); |
| | 33 | 72 | | if (!string.IsNullOrEmpty(data.PlaintextAlternativeBody)) |
| | | 73 | | { |
| | 3 | 74 | | builder.TextBody = data.PlaintextAlternativeBody; |
| | 3 | 75 | | builder.HtmlBody = data.Body; |
| | | 76 | | } |
| | 30 | 77 | | else if (!data.IsHtml) |
| | | 78 | | { |
| | 27 | 79 | | builder.TextBody = data.Body; |
| | | 80 | | } |
| | | 81 | | else |
| | | 82 | | { |
| | 3 | 83 | | builder.HtmlBody = data.Body; |
| | | 84 | | } |
| | | 85 | | |
| | 72 | 86 | | foreach (var attachment in data.Attachments) |
| | | 87 | | { |
| | 3 | 88 | | if (attachment.Data is null) |
| | | 89 | | { |
| | | 90 | | continue; |
| | | 91 | | } |
| | | 92 | | |
| | 3 | 93 | | var mimeAttachment = builder.Attachments.Add(attachment.Filename, attachment.Data, ContentType.Parse(attachm |
| | 3 | 94 | | if (!string.IsNullOrWhiteSpace(attachment.ContentId)) |
| | | 95 | | { |
| | 3 | 96 | | mimeAttachment.ContentId = attachment.ContentId; |
| | | 97 | | } |
| | | 98 | | } |
| | | 99 | | |
| | 33 | 100 | | message.Body = builder.ToMessageBody(); |
| | 33 | 101 | | ApplyCharset(message.Body, encoding); |
| | | 102 | | |
| | 72 | 103 | | foreach (var header in data.Headers) |
| | | 104 | | { |
| | 3 | 105 | | message.Headers.Add(header.Key, header.Value); |
| | | 106 | | } |
| | | 107 | | |
| | 33 | 108 | | message.Priority = data.Priority switch |
| | 33 | 109 | | { |
| | 3 | 110 | | Priority.Low => MessagePriority.NonUrgent, |
| | 0 | 111 | | Priority.Normal => MessagePriority.Normal, |
| | 30 | 112 | | Priority.High => MessagePriority.Urgent, |
| | 0 | 113 | | _ => message.Priority |
| | 33 | 114 | | }; |
| | | 115 | | |
| | 33 | 116 | | return message; |
| | | 117 | | } |
| | | 118 | | |
| | | 119 | | /// <inheritdoc /> |
| | | 120 | | [SuppressMessage("Reliability", "CA2007:Consider calling ConfigureAwait on the awaited task", Justification = "Synch |
| | 0 | 121 | | public SendResponse Send(IEmail email, CancellationToken? token = null) => SendAsync(email, token).ConfigureAwait(fa |
| | | 122 | | |
| | | 123 | | /// <inheritdoc /> |
| | | 124 | | public async Task<SendResponse> SendAsync(IEmail email, CancellationToken? token = null) |
| | | 125 | | { |
| | 12 | 126 | | ObjectDisposedException.ThrowIf(_disposed, this); |
| | | 127 | | |
| | 9 | 128 | | var response = new SendResponse(); |
| | 9 | 129 | | var cancellationToken = token ?? CancellationToken.None; |
| | | 130 | | |
| | 9 | 131 | | using (_logger.MeasureTime(nameof(SendAsync))) |
| | | 132 | | { |
| | 9 | 133 | | if (cancellationToken.IsCancellationRequested) |
| | | 134 | | { |
| | 3 | 135 | | AddCanceled(response); |
| | 3 | 136 | | return response; |
| | | 137 | | } |
| | | 138 | | |
| | | 139 | | try |
| | | 140 | | { |
| | 6 | 141 | | cancellationToken.ThrowIfCancellationRequested(); |
| | 6 | 142 | | MailKitSmtpOptionsValidator.Validate(smtpClientOptions); |
| | | 143 | | |
| | 6 | 144 | | using var message = CreateMailMessage(email, MailEncodingResolver.Resolve(smtpClientOptions)); |
| | 6 | 145 | | CheckMessage(message); |
| | | 146 | | |
| | 3 | 147 | | if (smtpClientOptions.UsePickupDirectory) |
| | | 148 | | { |
| | 3 | 149 | | await SaveToPickupDirectoryAsync(message, smtpClientOptions.MailPickupDirectory, cancellationToken). |
| | 3 | 150 | | response.MessageId = message.MessageId ?? string.Empty; |
| | 3 | 151 | | LogMailHasBeenSentSuccessfullyEmail(email); |
| | 3 | 152 | | return response; |
| | | 153 | | } |
| | | 154 | | |
| | 0 | 155 | | response.MessageId = await _connectionManager.SendAsync(message, cancellationToken).ConfigureAwait(false |
| | 0 | 156 | | LogMailHasBeenSentSuccessfullyEmail(email); |
| | 0 | 157 | | } |
| | 0 | 158 | | catch (OperationCanceledException) |
| | | 159 | | { |
| | 0 | 160 | | AddCanceled(response); |
| | 0 | 161 | | } |
| | 3 | 162 | | catch (Exception ex) |
| | | 163 | | { |
| | 3 | 164 | | _logger.LogException(ex); |
| | 3 | 165 | | response.ErrorMessages.Add(ex.Message); |
| | 3 | 166 | | } |
| | 3 | 167 | | } |
| | | 168 | | |
| | 3 | 169 | | return response; |
| | 9 | 170 | | } |
| | | 171 | | |
| | | 172 | | /// <inheritdoc /> |
| | | 173 | | [SuppressMessage("Reliability", "CA2007:Consider calling ConfigureAwait on the awaited task", Justification = "Synch |
| | 0 | 174 | | public bool CanConnect() => CanConnectAsync().ConfigureAwait(false).GetAwaiter().GetResult(); |
| | | 175 | | |
| | | 176 | | /// <inheritdoc /> |
| | | 177 | | public async Task<bool> CanConnectAsync() |
| | | 178 | | { |
| | 6 | 179 | | ObjectDisposedException.ThrowIf(_disposed, this); |
| | | 180 | | |
| | 6 | 181 | | SmtpClient? client = null; |
| | | 182 | | try |
| | | 183 | | { |
| | 6 | 184 | | MailKitSmtpOptionsValidator.Validate(smtpClientOptions); |
| | 6 | 185 | | if (smtpClientOptions.UsePickupDirectory) |
| | | 186 | | { |
| | 6 | 187 | | return Directory.Exists(smtpClientOptions.MailPickupDirectory); |
| | | 188 | | } |
| | | 189 | | |
| | 0 | 190 | | client = new SmtpClient(); |
| | 0 | 191 | | await ConnectAndAuthenticateAsync(client, CancellationToken.None).ConfigureAwait(false); |
| | 0 | 192 | | await client.DisconnectAsync(true, CancellationToken.None).ConfigureAwait(false); |
| | 0 | 193 | | return true; |
| | | 194 | | } |
| | 0 | 195 | | catch (Exception ex) |
| | | 196 | | { |
| | 0 | 197 | | LogSmtpConnectivityCheckFailed(ex); |
| | 0 | 198 | | return false; |
| | | 199 | | } |
| | | 200 | | finally |
| | | 201 | | { |
| | 6 | 202 | | client?.Dispose(); |
| | | 203 | | } |
| | 6 | 204 | | } |
| | | 205 | | |
| | | 206 | | /// <inheritdoc /> |
| | | 207 | | public void Dispose() |
| | | 208 | | { |
| | 27 | 209 | | if (_disposed) |
| | | 210 | | { |
| | 3 | 211 | | return; |
| | | 212 | | } |
| | | 213 | | |
| | 24 | 214 | | _disposed = true; |
| | 24 | 215 | | _connectionManager.Dispose(); |
| | 24 | 216 | | } |
| | | 217 | | |
| | | 218 | | private static void ApplyCharset(MimeEntity entity, Encoding encoding) |
| | | 219 | | { |
| | | 220 | | switch (entity) |
| | | 221 | | { |
| | | 222 | | case TextPart textPart: |
| | 39 | 223 | | textPart.ContentType.Charset = encoding.WebName; |
| | 39 | 224 | | break; |
| | | 225 | | case Multipart multipart: |
| | 36 | 226 | | foreach (var part in multipart) |
| | | 227 | | { |
| | 12 | 228 | | ApplyCharset(part, encoding); |
| | | 229 | | } |
| | | 230 | | |
| | | 231 | | break; |
| | | 232 | | } |
| | 6 | 233 | | } |
| | | 234 | | |
| | | 235 | | private static void CheckMessage(MimeMessage message) |
| | | 236 | | { |
| | 6 | 237 | | if (message.From.Mailboxes.All(x => string.IsNullOrEmpty(x.Address))) |
| | | 238 | | { |
| | 3 | 239 | | throw new EmptySenderAddressesException(); |
| | | 240 | | } |
| | 3 | 241 | | } |
| | | 242 | | |
| | 3 | 243 | | private static void AddCanceled(SendResponse response) => response.ErrorMessages.Add("Send canceled."); |
| | | 244 | | |
| | | 245 | | [SuppressMessage("Reliability", "CA2007:Consider calling ConfigureAwait on the awaited task", Justification = "await |
| | | 246 | | private static async Task SaveToPickupDirectoryAsync(MimeMessage message, string? pickupDirectory, CancellationToken |
| | | 247 | | { |
| | 3 | 248 | | Directory.CreateDirectory(pickupDirectory ?? string.Empty); |
| | 3 | 249 | | var path = Path.Combine(pickupDirectory ?? string.Empty, Guid.NewGuid() + ".eml"); |
| | | 250 | | |
| | 3 | 251 | | await using var stream = new FileStream(path, FileMode.CreateNew); |
| | 3 | 252 | | await message.WriteToAsync(stream, cancellationToken).ConfigureAwait(false); |
| | 3 | 253 | | } |
| | | 254 | | |
| | | 255 | | private async Task ConnectAndAuthenticateAsync(SmtpClient client, CancellationToken cancellationToken) |
| | | 256 | | { |
| | 0 | 257 | | await client.ConnectAsync( |
| | 0 | 258 | | smtpClientOptions.Server!, |
| | 0 | 259 | | smtpClientOptions.Port, |
| | 0 | 260 | | SmtpSecureSocketOptionsResolver.Resolve(smtpClientOptions), |
| | 0 | 261 | | cancellationToken).ConfigureAwait(false); |
| | | 262 | | |
| | 0 | 263 | | if (smtpClientOptions.RequiresAuthentication) |
| | | 264 | | { |
| | 0 | 265 | | await client.AuthenticateAsync(smtpClientOptions.User!, smtpClientOptions.Password!, cancellationToken).Conf |
| | | 266 | | } |
| | 0 | 267 | | } |
| | | 268 | | |
| | | 269 | | [LoggerMessage(LogLevel.Information, "SMTP connectivity check failed.")] |
| | | 270 | | partial void LogSmtpConnectivityCheckFailed(Exception exception); |
| | | 271 | | |
| | | 272 | | [LoggerMessage(LogLevel.Information, "Mail has been sent successfully: {Email}")] |
| | | 273 | | partial void LogMailHasBeenSentSuccessfullyEmail(IEmail email); |
| | | 274 | | } |
| | | 275 | | |