|
| 1 | +namespace FluentEmailer.MailKit; |
| 2 | + |
| 3 | +/// <summary> |
| 4 | +/// Send emails with the MailKit Library. |
| 5 | +/// </summary> |
| 6 | +public sealed class MailKitSender : ISender |
| 7 | +{ |
| 8 | + private readonly SmtpClientOptions _smtpClientOptions; |
| 9 | + |
| 10 | + /// <summary> |
| 11 | + /// Creates a sender that uses the given SmtpClientOptions when sending with MailKit. Since the client is internal this will dispose of the client. |
| 12 | + /// </summary> |
| 13 | + /// <param name="smtpClientOptions">The SmtpClientOptions to use to create the MailKit client</param> |
| 14 | + public MailKitSender(SmtpClientOptions smtpClientOptions) |
| 15 | + { |
| 16 | + _smtpClientOptions = smtpClientOptions; |
| 17 | + } |
| 18 | + |
| 19 | + /// <summary> |
| 20 | + /// Send the specified email. |
| 21 | + /// </summary> |
| 22 | + /// <returns>A response with any errors and a success boolean.</returns> |
| 23 | + /// <param name="email">Email.</param> |
| 24 | + /// <param name="token">Cancellation Token.</param> |
| 25 | + public SendResponse Send(IFluentEmailer email, CancellationToken token = default) |
| 26 | + { |
| 27 | + var response = new SendResponse(); |
| 28 | + var message = CreateMailMessage(email); |
| 29 | + |
| 30 | + if (token.IsCancellationRequested) |
| 31 | + { |
| 32 | + response.ErrorMessages.Add("Message was cancelled by cancellation token."); |
| 33 | + return response; |
| 34 | + } |
| 35 | + |
| 36 | + try |
| 37 | + { |
| 38 | + if (_smtpClientOptions.UsePickupDirectory) |
| 39 | + { |
| 40 | + SaveToPickupDirectory(message, _smtpClientOptions.MailPickupDirectory).Wait(token); |
| 41 | + return response; |
| 42 | + } |
| 43 | + |
| 44 | + using var client = new SmtpClient(); |
| 45 | + if (_smtpClientOptions.SocketOptions.HasValue) |
| 46 | + { |
| 47 | + client.Connect( |
| 48 | + _smtpClientOptions.Server, |
| 49 | + _smtpClientOptions.Port, |
| 50 | + _smtpClientOptions.SocketOptions.Value, |
| 51 | + token); |
| 52 | + } |
| 53 | + else |
| 54 | + { |
| 55 | + client.Connect( |
| 56 | + _smtpClientOptions.Server, |
| 57 | + _smtpClientOptions.Port, |
| 58 | + _smtpClientOptions.UseSsl, |
| 59 | + token); |
| 60 | + } |
| 61 | + |
| 62 | + // Note: only needed if the SMTP server requires authentication |
| 63 | + if (_smtpClientOptions.RequiresAuthentication) |
| 64 | + client.Authenticate(_smtpClientOptions.User, _smtpClientOptions.Password, token); |
| 65 | + |
| 66 | + client.Send(message, token); |
| 67 | + client.Disconnect(true, token); |
| 68 | + } |
| 69 | + catch (Exception ex) |
| 70 | + { |
| 71 | + response.ErrorMessages.Add(ex.Message); |
| 72 | + } |
| 73 | + |
| 74 | + return response; |
| 75 | + } |
| 76 | + |
| 77 | + /// <summary> |
| 78 | + /// Send the specified email. |
| 79 | + /// </summary> |
| 80 | + /// <returns>A response with any errors and a success boolean.</returns> |
| 81 | + /// <param name="email">Email.</param> |
| 82 | + /// <param name="token">Cancellation Token.</param> |
| 83 | + public async Task<SendResponse> SendAsync(IFluentEmailer email, CancellationToken token = default) |
| 84 | + { |
| 85 | + var response = new SendResponse(); |
| 86 | + var message = CreateMailMessage(email); |
| 87 | + |
| 88 | + if (token.IsCancellationRequested) |
| 89 | + { |
| 90 | + response.ErrorMessages.Add("Message was cancelled by cancellation token."); |
| 91 | + return response; |
| 92 | + } |
| 93 | + |
| 94 | + try |
| 95 | + { |
| 96 | + if (_smtpClientOptions.UsePickupDirectory) |
| 97 | + { |
| 98 | + await SaveToPickupDirectory(message, _smtpClientOptions.MailPickupDirectory); |
| 99 | + return response; |
| 100 | + } |
| 101 | + |
| 102 | + using var client = new SmtpClient(); |
| 103 | + if (_smtpClientOptions.SocketOptions.HasValue) |
| 104 | + { |
| 105 | + await client.ConnectAsync( |
| 106 | + _smtpClientOptions.Server, |
| 107 | + _smtpClientOptions.Port, |
| 108 | + _smtpClientOptions.SocketOptions.Value, |
| 109 | + token); |
| 110 | + } |
| 111 | + else |
| 112 | + { |
| 113 | + await client.ConnectAsync( |
| 114 | + _smtpClientOptions.Server, |
| 115 | + _smtpClientOptions.Port, |
| 116 | + _smtpClientOptions.UseSsl, |
| 117 | + token); |
| 118 | + } |
| 119 | + |
| 120 | + // Note: only needed if the SMTP server requires authentication |
| 121 | + if (_smtpClientOptions.RequiresAuthentication) |
| 122 | + await client.AuthenticateAsync(_smtpClientOptions.User, _smtpClientOptions.Password, token); |
| 123 | + |
| 124 | + await client.SendAsync(message, token); |
| 125 | + await client.DisconnectAsync(true, token); |
| 126 | + } |
| 127 | + catch (Exception ex) |
| 128 | + { |
| 129 | + response.ErrorMessages.Add(ex.Message); |
| 130 | + } |
| 131 | + |
| 132 | + return response; |
| 133 | + } |
| 134 | + |
| 135 | + /// <summary> |
| 136 | + /// Saves email to a pickup directory. |
| 137 | + /// </summary> |
| 138 | + /// <param name="message">Message to save for pickup.</param> |
| 139 | + /// <param name="pickupDirectory">Pickup directory.</param> |
| 140 | + private static async Task SaveToPickupDirectory(MimeMessage message, string pickupDirectory) |
| 141 | + { |
| 142 | + // Note: this will require that you know where the specified pickup directory is. |
| 143 | + var path = Path.Combine(pickupDirectory, Guid.NewGuid() + ".eml"); |
| 144 | + |
| 145 | + if (File.Exists(path)) |
| 146 | + return; |
| 147 | + |
| 148 | + try |
| 149 | + { |
| 150 | + await using var stream = new FileStream(path, FileMode.CreateNew); |
| 151 | + await message.WriteToAsync(stream); |
| 152 | + } |
| 153 | + catch (IOException) |
| 154 | + { |
| 155 | + // The file may have been created between our File.Exists() check and |
| 156 | + // our attempt to create the stream. |
| 157 | + throw; |
| 158 | + } |
| 159 | + } |
| 160 | + |
| 161 | + /// <summary> |
| 162 | + /// Create a MimMessage so MailKit can send it |
| 163 | + /// </summary> |
| 164 | + /// <returns>The mail message.</returns> |
| 165 | + /// <param name="email">Email data.</param> |
| 166 | + private static MimeMessage CreateMailMessage(IFluentEmailer email) |
| 167 | + { |
| 168 | + var data = email.Data; |
| 169 | + |
| 170 | + var message = new MimeMessage(); |
| 171 | + |
| 172 | + // if for any reason, subject header is not added, add it else update it. |
| 173 | + if (!message.Headers.Contains(HeaderId.Subject)) |
| 174 | + message.Headers.Add(HeaderId.Subject, Encoding.UTF8, data.Subject ?? string.Empty); |
| 175 | + else |
| 176 | + message.Headers[HeaderId.Subject] = data.Subject ?? string.Empty; |
| 177 | + |
| 178 | + message.Headers.Add(HeaderId.Encoding, Encoding.UTF8.EncodingName); |
| 179 | + |
| 180 | + message.From.Add(new MailboxAddress(data.FromAddress.Name, data.FromAddress.EmailAddress)); |
| 181 | + |
| 182 | + var builder = new BodyBuilder(); |
| 183 | + if (!string.IsNullOrEmpty(data.PlaintextAlternativeBody)) |
| 184 | + { |
| 185 | + builder.TextBody = data.PlaintextAlternativeBody; |
| 186 | + builder.HtmlBody = data.Body; |
| 187 | + } |
| 188 | + else if (!data.IsHtml) |
| 189 | + { |
| 190 | + builder.TextBody = data.Body; |
| 191 | + } |
| 192 | + else |
| 193 | + { |
| 194 | + builder.HtmlBody = data.Body; |
| 195 | + } |
| 196 | + |
| 197 | + data.Attachments.ForEach(x => |
| 198 | + { |
| 199 | + var attachment = builder.Attachments.Add(x.Filename, x.Data, ContentType.Parse(x.ContentType)); |
| 200 | + attachment.ContentId = x.ContentId; |
| 201 | + }); |
| 202 | + |
| 203 | + message.Body = builder.ToMessageBody(); |
| 204 | + |
| 205 | + foreach (var header in data.Headers) |
| 206 | + message.Headers.Add(header.Key, header.Value); |
| 207 | + |
| 208 | + data.ToAddresses.ForEach(x => message.To.Add(new MailboxAddress(x.Name, x.EmailAddress))); |
| 209 | + data.CcAddresses.ForEach(x => message.Cc.Add(new MailboxAddress(x.Name, x.EmailAddress))); |
| 210 | + data.BccAddresses.ForEach(x => message.Bcc.Add(new MailboxAddress(x.Name, x.EmailAddress))); |
| 211 | + data.ReplyToAddresses.ForEach(x => message.ReplyTo.Add(new MailboxAddress(x.Name, x.EmailAddress))); |
| 212 | + |
| 213 | + message.Priority = data.Priority switch |
| 214 | + { |
| 215 | + Priority.Low => MessagePriority.NonUrgent, |
| 216 | + Priority.Normal => MessagePriority.Normal, |
| 217 | + Priority.High => MessagePriority.Urgent, |
| 218 | + _ => message.Priority |
| 219 | + }; |
| 220 | + |
| 221 | + return message; |
| 222 | + } |
| 223 | +} |
0 commit comments