< Summary

Information
Class: MyNet.Mail.Smtp.MailSmtpService
Assembly: MyNet.Mail
File(s): https://raw.githubusercontent.com/sandre58/MyNet/5aaaab311aa14541478b9e402357d98b657a23e4/src/MyNet.Mail/Smtp/MailSmtpService.cs
Tag: 342_31701152804
Line coverage
89%
Covered lines: 76
Uncovered lines: 9
Coverable lines: 85
Total lines: 193
Line coverage: 89.4%
Branch coverage
79%
Covered branches: 27
Total branches: 34
Branch coverage: 79.4%
Method coverage

Feature is only available for sponsors

Upgrade to PRO version

Metrics

MethodBranch coverage Crap Score Cyclomatic complexity Line coverage
.ctor(...)100%11100%
CreateSmtpClient(...)50%4491.66%
CreateMailMessage(...)90%202095.55%
Send(...)100%11100%
SendAsync()70%121072.72%
CanConnect()100%11100%
CanConnectAsync()100%11100%
Dispose()100%11100%

File(s)

https://raw.githubusercontent.com/sandre58/MyNet/5aaaab311aa14541478b9e402357d98b657a23e4/src/MyNet.Mail/Smtp/MailSmtpService.cs

#LineLine coverage
 1// -----------------------------------------------------------------------
 2// <copyright file="MailSmtpService.cs" company="Stéphane ANDRE">
 3// Copyright (c) Stéphane ANDRE. All rights reserved.
 4// </copyright>
 5// -----------------------------------------------------------------------
 6
 7using System;
 8using System.ComponentModel;
 9using System.Diagnostics.CodeAnalysis;
 10using System.Net;
 11using System.Net.Mail;
 12using System.Net.Mime;
 13using System.Text;
 14using System.Threading;
 15using System.Threading.Tasks;
 16using MyNet.Mail.Models;
 17using Attachment = System.Net.Mail.Attachment;
 18
 19namespace MyNet.Mail.Smtp;
 20
 21public 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)
 625        : this(CreateSmtpClient(options))
 26    {
 627    }
 28
 29    private static SmtpClient CreateSmtpClient(SmtpClientOptions options)
 30    {
 631        var client = new SmtpClient(options.Server, options.Port)
 632        {
 633            EnableSsl = options.UseSsl,
 634            PickupDirectoryLocation = options.MailPickupDirectory,
 635            DeliveryMethod = options.UsePickupDirectory
 636                ? SmtpDeliveryMethod.SpecifiedPickupDirectory
 637                : SmtpDeliveryMethod.Network,
 638            UseDefaultCredentials = !options.RequiresAuthentication
 639        };
 40
 641        if (options.RequiresAuthentication)
 42        {
 043            client.Credentials = new NetworkCredential(options.User, options.Password);
 44        }
 45
 646        return client;
 47    }
 48
 49    public static MailMessage CreateMailMessage(IEmail email)
 50    {
 1551        var data = email.Data;
 52        MailMessage? message;
 53
 54        // Smtp seems to require the HTML version as the alternative.
 1555        if (!string.IsNullOrEmpty(data.PlaintextAlternativeBody))
 56        {
 357            message = new MailMessage
 358            {
 359                Subject = data.Subject,
 360                Body = data.PlaintextAlternativeBody,
 361                IsBodyHtml = false,
 362                BodyEncoding = Encoding.UTF8,
 363                SubjectEncoding = Encoding.UTF8,
 364                From = new MailAddress(data.From.Address, data.From.Name)
 365            };
 66
 367            var mimeType = new ContentType("text/html; charset=UTF-8");
 368            var alternate = AlternateView.CreateAlternateViewFromString(data.Body, mimeType);
 369            message.AlternateViews.Add(alternate);
 70        }
 71        else
 72        {
 1273            message = new MailMessage
 1274            {
 1275                Subject = data.Subject,
 1276                Body = data.Body,
 1277                IsBodyHtml = data.IsHtml,
 1278                BodyEncoding = Encoding.UTF8,
 1279                SubjectEncoding = Encoding.UTF8,
 1280                From = new MailAddress(data.From.Address, data.From.Name)
 1281            };
 82        }
 83
 3684        foreach (var header in data.Headers)
 85        {
 386            message.Headers.Add(header.Key, header.Value);
 87        }
 88
 6089        foreach (var address in data.To)
 90        {
 1591            message.To.Add(new MailAddress(address.Address, address.Name));
 92        }
 93
 3694        foreach (var address in data.Cc)
 95        {
 396            message.CC.Add(new MailAddress(address.Address, address.Name));
 97        }
 98
 3699        foreach (var address in data.Bcc)
 100        {
 3101            message.Bcc.Add(new MailAddress(address.Address, address.Name));
 102        }
 103
 36104        foreach (var address in data.ReplyTo)
 105        {
 3106            message.ReplyToList.Add(new MailAddress(address.Address, address.Name));
 107        }
 108
 15109        message.Priority = data.Priority switch
 15110        {
 3111            Priority.Low => MailPriority.Low,
 0112            Priority.Normal => MailPriority.Normal,
 12113            Priority.High => MailPriority.High,
 0114            _ => message.Priority
 15115        };
 116
 42117        foreach (var attachment in data.Attachments)
 118        {
 6119            if (attachment.Data == null)
 120            {
 121                continue;
 122            }
 123
 3124            var a = new Attachment(attachment.Data, attachment.Filename, attachment.ContentType) { ContentId = attachmen
 3125            message.Attachments.Add(a);
 126        }
 127
 15128        return message;
 129    }
 130
 131    public SendResponse Send(IEmail email, CancellationToken? token = null) =>
 3132        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    {
 9137        var response = new SendResponse();
 138
 9139        if (token?.IsCancellationRequested ?? false)
 140        {
 6141            response.ErrorMessages.Add("Send canceled.");
 6142            return response;
 143        }
 144
 145        try
 146        {
 3147            token?.ThrowIfCancellationRequested();
 148
 3149            using var message = CreateMailMessage(email);
 3150            var tcs = new TaskCompletionSource<bool>(TaskCreationOptions.RunContinuationsAsynchronously);
 151
 3152            smtpClient.SendCompleted += handler;
 153            try
 154            {
 3155                smtpClient.SendAsync(message, tcs);
 3156                await using var registration = token?.Register(static state => ((SmtpClient)state!).SendAsyncCancel(), s
 3157                _ = await tcs.Task.ConfigureAwait(false);
 3158            }
 159            finally
 160            {
 3161                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            }
 3174        }
 0175        catch (OperationCanceledException)
 176        {
 0177            response.ErrorMessages.Add("Send canceled.");
 0178        }
 0179        catch (Exception ex)
 180        {
 0181            response.ErrorMessages.Add(ex.Message);
 0182        }
 183
 3184        return response;
 9185    }
 186
 6187    public bool CanConnect() => SmtpHelper.TestSmtpConnection(smtpClient.Host, smtpClient.Port);
 188
 3189    public Task<bool> CanConnectAsync() => Task.FromResult(CanConnect());
 190
 18191    public void Dispose() => smtpClient.Dispose();
 192}
 193