| | | 1 | | // ----------------------------------------------------------------------- |
| | | 2 | | // <copyright file="MailSmtpService.cs" company="Stéphane ANDRE"> |
| | | 3 | | // Copyright (c) Stéphane ANDRE. All rights reserved. |
| | | 4 | | // </copyright> |
| | | 5 | | // ----------------------------------------------------------------------- |
| | | 6 | | |
| | | 7 | | using System; |
| | | 8 | | using System.ComponentModel; |
| | | 9 | | using System.Diagnostics.CodeAnalysis; |
| | | 10 | | using System.Net; |
| | | 11 | | using System.Net.Mail; |
| | | 12 | | using System.Net.Mime; |
| | | 13 | | using System.Text; |
| | | 14 | | using System.Threading; |
| | | 15 | | using System.Threading.Tasks; |
| | | 16 | | using MyNet.Mail.Models; |
| | | 17 | | using Attachment = System.Net.Mail.Attachment; |
| | | 18 | | |
| | | 19 | | namespace MyNet.Mail.Smtp; |
| | | 20 | | |
| | | 21 | | public sealed class MailSmtpService(SmtpClient smtpClient) : IMailService, IDisposable |
| | | 22 | | { |
| | | 23 | | [SuppressMessage("Reliability", "CA2000:Dispose objects before losing scope", Justification = "Dispose in class Disp |
| | | 24 | | public MailSmtpService(SmtpClientOptions options) |
| | 6 | 25 | | : this(CreateSmtpClient(options)) |
| | | 26 | | { |
| | 6 | 27 | | } |
| | | 28 | | |
| | | 29 | | private static SmtpClient CreateSmtpClient(SmtpClientOptions options) |
| | | 30 | | { |
| | 6 | 31 | | var client = new SmtpClient(options.Server, options.Port) |
| | 6 | 32 | | { |
| | 6 | 33 | | EnableSsl = options.UseSsl, |
| | 6 | 34 | | PickupDirectoryLocation = options.MailPickupDirectory, |
| | 6 | 35 | | DeliveryMethod = options.UsePickupDirectory |
| | 6 | 36 | | ? SmtpDeliveryMethod.SpecifiedPickupDirectory |
| | 6 | 37 | | : SmtpDeliveryMethod.Network, |
| | 6 | 38 | | UseDefaultCredentials = !options.RequiresAuthentication |
| | 6 | 39 | | }; |
| | | 40 | | |
| | 6 | 41 | | if (options.RequiresAuthentication) |
| | | 42 | | { |
| | 0 | 43 | | client.Credentials = new NetworkCredential(options.User, options.Password); |
| | | 44 | | } |
| | | 45 | | |
| | 6 | 46 | | return client; |
| | | 47 | | } |
| | | 48 | | |
| | | 49 | | public static MailMessage CreateMailMessage(IEmail email) |
| | | 50 | | { |
| | 15 | 51 | | var data = email.Data; |
| | | 52 | | MailMessage? message; |
| | | 53 | | |
| | | 54 | | // Smtp seems to require the HTML version as the alternative. |
| | 15 | 55 | | if (!string.IsNullOrEmpty(data.PlaintextAlternativeBody)) |
| | | 56 | | { |
| | 3 | 57 | | message = new MailMessage |
| | 3 | 58 | | { |
| | 3 | 59 | | Subject = data.Subject, |
| | 3 | 60 | | Body = data.PlaintextAlternativeBody, |
| | 3 | 61 | | IsBodyHtml = false, |
| | 3 | 62 | | BodyEncoding = Encoding.UTF8, |
| | 3 | 63 | | SubjectEncoding = Encoding.UTF8, |
| | 3 | 64 | | From = new MailAddress(data.From.Address, data.From.Name) |
| | 3 | 65 | | }; |
| | | 66 | | |
| | 3 | 67 | | var mimeType = new ContentType("text/html; charset=UTF-8"); |
| | 3 | 68 | | var alternate = AlternateView.CreateAlternateViewFromString(data.Body, mimeType); |
| | 3 | 69 | | message.AlternateViews.Add(alternate); |
| | | 70 | | } |
| | | 71 | | else |
| | | 72 | | { |
| | 12 | 73 | | message = new MailMessage |
| | 12 | 74 | | { |
| | 12 | 75 | | Subject = data.Subject, |
| | 12 | 76 | | Body = data.Body, |
| | 12 | 77 | | IsBodyHtml = data.IsHtml, |
| | 12 | 78 | | BodyEncoding = Encoding.UTF8, |
| | 12 | 79 | | SubjectEncoding = Encoding.UTF8, |
| | 12 | 80 | | From = new MailAddress(data.From.Address, data.From.Name) |
| | 12 | 81 | | }; |
| | | 82 | | } |
| | | 83 | | |
| | 36 | 84 | | foreach (var header in data.Headers) |
| | | 85 | | { |
| | 3 | 86 | | message.Headers.Add(header.Key, header.Value); |
| | | 87 | | } |
| | | 88 | | |
| | 60 | 89 | | foreach (var address in data.To) |
| | | 90 | | { |
| | 15 | 91 | | message.To.Add(new MailAddress(address.Address, address.Name)); |
| | | 92 | | } |
| | | 93 | | |
| | 36 | 94 | | foreach (var address in data.Cc) |
| | | 95 | | { |
| | 3 | 96 | | message.CC.Add(new MailAddress(address.Address, address.Name)); |
| | | 97 | | } |
| | | 98 | | |
| | 36 | 99 | | foreach (var address in data.Bcc) |
| | | 100 | | { |
| | 3 | 101 | | message.Bcc.Add(new MailAddress(address.Address, address.Name)); |
| | | 102 | | } |
| | | 103 | | |
| | 36 | 104 | | foreach (var address in data.ReplyTo) |
| | | 105 | | { |
| | 3 | 106 | | message.ReplyToList.Add(new MailAddress(address.Address, address.Name)); |
| | | 107 | | } |
| | | 108 | | |
| | 15 | 109 | | message.Priority = data.Priority switch |
| | 15 | 110 | | { |
| | 3 | 111 | | Priority.Low => MailPriority.Low, |
| | 0 | 112 | | Priority.Normal => MailPriority.Normal, |
| | 12 | 113 | | Priority.High => MailPriority.High, |
| | 0 | 114 | | _ => message.Priority |
| | 15 | 115 | | }; |
| | | 116 | | |
| | 42 | 117 | | foreach (var attachment in data.Attachments) |
| | | 118 | | { |
| | 6 | 119 | | if (attachment.Data == null) |
| | | 120 | | { |
| | | 121 | | continue; |
| | | 122 | | } |
| | | 123 | | |
| | 3 | 124 | | var a = new Attachment(attachment.Data, attachment.Filename, attachment.ContentType) { ContentId = attachmen |
| | 3 | 125 | | message.Attachments.Add(a); |
| | | 126 | | } |
| | | 127 | | |
| | 15 | 128 | | return message; |
| | | 129 | | } |
| | | 130 | | |
| | | 131 | | public SendResponse Send(IEmail email, CancellationToken? token = null) => |
| | 3 | 132 | | SendAsync(email, token).ConfigureAwait(false).GetAwaiter().GetResult(); |
| | | 133 | | |
| | | 134 | | [SuppressMessage("Reliability", "CA2007:Consider calling ConfigureAwait on the awaited task", Justification = "Inten |
| | | 135 | | public async Task<SendResponse> SendAsync(IEmail email, CancellationToken? token = null) |
| | | 136 | | { |
| | 9 | 137 | | var response = new SendResponse(); |
| | | 138 | | |
| | 9 | 139 | | if (token?.IsCancellationRequested ?? false) |
| | | 140 | | { |
| | 6 | 141 | | response.ErrorMessages.Add("Send canceled."); |
| | 6 | 142 | | return response; |
| | | 143 | | } |
| | | 144 | | |
| | | 145 | | try |
| | | 146 | | { |
| | 3 | 147 | | token?.ThrowIfCancellationRequested(); |
| | | 148 | | |
| | 3 | 149 | | using var message = CreateMailMessage(email); |
| | 3 | 150 | | var tcs = new TaskCompletionSource<bool>(TaskCreationOptions.RunContinuationsAsynchronously); |
| | | 151 | | |
| | 3 | 152 | | smtpClient.SendCompleted += handler; |
| | | 153 | | try |
| | | 154 | | { |
| | 3 | 155 | | smtpClient.SendAsync(message, tcs); |
| | 3 | 156 | | await using var registration = token?.Register(static state => ((SmtpClient)state!).SendAsyncCancel(), s |
| | 3 | 157 | | _ = await tcs.Task.ConfigureAwait(false); |
| | 3 | 158 | | } |
| | | 159 | | finally |
| | | 160 | | { |
| | 3 | 161 | | smtpClient.SendCompleted -= handler; |
| | | 162 | | } |
| | | 163 | | |
| | | 164 | | void handler(object? s, AsyncCompletedEventArgs e) |
| | | 165 | | { |
| | | 166 | | _ = e.UserState != tcs |
| | | 167 | | ? tcs.TrySetException(new InvalidOperationException("Unexpected UserState")) |
| | | 168 | | : e.Cancelled |
| | | 169 | | ? tcs.TrySetCanceled() |
| | | 170 | | : e.Error != null |
| | | 171 | | ? tcs.TrySetException(e.Error) |
| | | 172 | | : tcs.TrySetResult(true); |
| | | 173 | | } |
| | 3 | 174 | | } |
| | 0 | 175 | | catch (OperationCanceledException) |
| | | 176 | | { |
| | 0 | 177 | | response.ErrorMessages.Add("Send canceled."); |
| | 0 | 178 | | } |
| | 0 | 179 | | catch (Exception ex) |
| | | 180 | | { |
| | 0 | 181 | | response.ErrorMessages.Add(ex.Message); |
| | 0 | 182 | | } |
| | | 183 | | |
| | 3 | 184 | | return response; |
| | 9 | 185 | | } |
| | | 186 | | |
| | 6 | 187 | | public bool CanConnect() => SmtpHelper.TestSmtpConnection(smtpClient.Host, smtpClient.Port); |
| | | 188 | | |
| | 3 | 189 | | public Task<bool> CanConnectAsync() => Task.FromResult(CanConnect()); |
| | | 190 | | |
| | 18 | 191 | | public void Dispose() => smtpClient.Dispose(); |
| | | 192 | | } |
| | | 193 | | |