< Summary

Information
Class: MyNet.Mail.MailKit.MailKitService
Assembly: MyNet.Mail.MailKit
File(s): https://raw.githubusercontent.com/sandre58/MyNet/5aaaab311aa14541478b9e402357d98b657a23e4/src/MyNet.Mail.MailKit/MailKitService.cs
Tag: 342_31701152804
Line coverage
77%
Covered lines: 86
Uncovered lines: 25
Coverable lines: 111
Total lines: 275
Line coverage: 77.4%
Branch coverage
80%
Covered branches: 45
Total branches: 56
Branch coverage: 80.3%
Method coverage

Feature is only available for sponsors

Upgrade to PRO version

Metrics

MethodBranch coverage Crap Score Cyclomatic complexity Line coverage
.ctor(...)100%22100%
CreateMailMessage(...)92.3%262694.59%
Send(...)100%210%
SendAsync()75%9879.31%
CanConnect()100%210%
CanConnectAsync()50%6450%
Dispose()100%22100%
ApplyCharset(...)83.33%66100%
CheckMessage(...)100%22100%
AddCanceled(...)100%11100%
SaveToPickupDirectoryAsync()50%44100%
ConnectAndAuthenticateAsync()0%620%

File(s)

https://raw.githubusercontent.com/sandre58/MyNet/5aaaab311aa14541478b9e402357d98b657a23e4/src/MyNet.Mail.MailKit/MailKitService.cs

#LineLine coverage
 1// -----------------------------------------------------------------------
 2// <copyright file="MailKitService.cs" company="Stéphane ANDRE">
 3// Copyright (c) Stéphane ANDRE. All rights reserved.
 4// </copyright>
 5// -----------------------------------------------------------------------
 6
 7using System;
 8using System.Diagnostics.CodeAnalysis;
 9using System.IO;
 10using System.Linq;
 11using System.Text;
 12using System.Threading;
 13using System.Threading.Tasks;
 14using MailKit.Net.Smtp;
 15using Microsoft.Extensions.Logging;
 16using MimeKit;
 17using MyNet.Mail.MailKit.Exceptions;
 18using MyNet.Mail.Models;
 19using MyNet.Mail.Smtp;
 20using MyNet.Utilities;
 21using MyNet.Utilities.Logging;
 22
 23namespace 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>
 31public sealed partial class MailKitService(SmtpClientOptions smtpClientOptions, ILogger? logger = null) : IMailService, 
 32{
 2433    private readonly ILogger _logger = logger ?? Log.Create<MailKitService>();
 2434    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    {
 3642        ArgumentNullException.ThrowIfNull(email);
 43
 3344        var data = email.Data;
 3345        var encoding = preferredEncoding ?? Encoding.UTF8;
 46
 3347        var message = new MimeMessage { Subject = data.Subject };
 48
 3349        message.From.Add(new MailboxAddress(data.From.Name, data.From.Address));
 50
 13251        foreach (var address in data.To)
 52        {
 3353            message.To.Add(new MailboxAddress(address.Name, address.Address));
 54        }
 55
 7256        foreach (var address in data.Cc)
 57        {
 358            message.Cc.Add(new MailboxAddress(address.Name, address.Address));
 59        }
 60
 7261        foreach (var address in data.Bcc)
 62        {
 363            message.Bcc.Add(new MailboxAddress(address.Name, address.Address));
 64        }
 65
 7266        foreach (var address in data.ReplyTo)
 67        {
 368            message.ReplyTo.Add(new MailboxAddress(address.Name, address.Address));
 69        }
 70
 3371        var builder = new BodyBuilder();
 3372        if (!string.IsNullOrEmpty(data.PlaintextAlternativeBody))
 73        {
 374            builder.TextBody = data.PlaintextAlternativeBody;
 375            builder.HtmlBody = data.Body;
 76        }
 3077        else if (!data.IsHtml)
 78        {
 2779            builder.TextBody = data.Body;
 80        }
 81        else
 82        {
 383            builder.HtmlBody = data.Body;
 84        }
 85
 7286        foreach (var attachment in data.Attachments)
 87        {
 388            if (attachment.Data is null)
 89            {
 90                continue;
 91            }
 92
 393            var mimeAttachment = builder.Attachments.Add(attachment.Filename, attachment.Data, ContentType.Parse(attachm
 394            if (!string.IsNullOrWhiteSpace(attachment.ContentId))
 95            {
 396                mimeAttachment.ContentId = attachment.ContentId;
 97            }
 98        }
 99
 33100        message.Body = builder.ToMessageBody();
 33101        ApplyCharset(message.Body, encoding);
 102
 72103        foreach (var header in data.Headers)
 104        {
 3105            message.Headers.Add(header.Key, header.Value);
 106        }
 107
 33108        message.Priority = data.Priority switch
 33109        {
 3110            Priority.Low => MessagePriority.NonUrgent,
 0111            Priority.Normal => MessagePriority.Normal,
 30112            Priority.High => MessagePriority.Urgent,
 0113            _ => message.Priority
 33114        };
 115
 33116        return message;
 117    }
 118
 119    /// <inheritdoc />
 120    [SuppressMessage("Reliability", "CA2007:Consider calling ConfigureAwait on the awaited task", Justification = "Synch
 0121    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    {
 12126        ObjectDisposedException.ThrowIf(_disposed, this);
 127
 9128        var response = new SendResponse();
 9129        var cancellationToken = token ?? CancellationToken.None;
 130
 9131        using (_logger.MeasureTime(nameof(SendAsync)))
 132        {
 9133            if (cancellationToken.IsCancellationRequested)
 134            {
 3135                AddCanceled(response);
 3136                return response;
 137            }
 138
 139            try
 140            {
 6141                cancellationToken.ThrowIfCancellationRequested();
 6142                MailKitSmtpOptionsValidator.Validate(smtpClientOptions);
 143
 6144                using var message = CreateMailMessage(email, MailEncodingResolver.Resolve(smtpClientOptions));
 6145                CheckMessage(message);
 146
 3147                if (smtpClientOptions.UsePickupDirectory)
 148                {
 3149                    await SaveToPickupDirectoryAsync(message, smtpClientOptions.MailPickupDirectory, cancellationToken).
 3150                    response.MessageId = message.MessageId ?? string.Empty;
 3151                    LogMailHasBeenSentSuccessfullyEmail(email);
 3152                    return response;
 153                }
 154
 0155                response.MessageId = await _connectionManager.SendAsync(message, cancellationToken).ConfigureAwait(false
 0156                LogMailHasBeenSentSuccessfullyEmail(email);
 0157            }
 0158            catch (OperationCanceledException)
 159            {
 0160                AddCanceled(response);
 0161            }
 3162            catch (Exception ex)
 163            {
 3164                _logger.LogException(ex);
 3165                response.ErrorMessages.Add(ex.Message);
 3166            }
 3167        }
 168
 3169        return response;
 9170    }
 171
 172    /// <inheritdoc />
 173    [SuppressMessage("Reliability", "CA2007:Consider calling ConfigureAwait on the awaited task", Justification = "Synch
 0174    public bool CanConnect() => CanConnectAsync().ConfigureAwait(false).GetAwaiter().GetResult();
 175
 176    /// <inheritdoc />
 177    public async Task<bool> CanConnectAsync()
 178    {
 6179        ObjectDisposedException.ThrowIf(_disposed, this);
 180
 6181        SmtpClient? client = null;
 182        try
 183        {
 6184            MailKitSmtpOptionsValidator.Validate(smtpClientOptions);
 6185            if (smtpClientOptions.UsePickupDirectory)
 186            {
 6187                return Directory.Exists(smtpClientOptions.MailPickupDirectory);
 188            }
 189
 0190            client = new SmtpClient();
 0191            await ConnectAndAuthenticateAsync(client, CancellationToken.None).ConfigureAwait(false);
 0192            await client.DisconnectAsync(true, CancellationToken.None).ConfigureAwait(false);
 0193            return true;
 194        }
 0195        catch (Exception ex)
 196        {
 0197            LogSmtpConnectivityCheckFailed(ex);
 0198            return false;
 199        }
 200        finally
 201        {
 6202            client?.Dispose();
 203        }
 6204    }
 205
 206    /// <inheritdoc />
 207    public void Dispose()
 208    {
 27209        if (_disposed)
 210        {
 3211            return;
 212        }
 213
 24214        _disposed = true;
 24215        _connectionManager.Dispose();
 24216    }
 217
 218    private static void ApplyCharset(MimeEntity entity, Encoding encoding)
 219    {
 220        switch (entity)
 221        {
 222            case TextPart textPart:
 39223                textPart.ContentType.Charset = encoding.WebName;
 39224                break;
 225            case Multipart multipart:
 36226                foreach (var part in multipart)
 227                {
 12228                    ApplyCharset(part, encoding);
 229                }
 230
 231                break;
 232        }
 6233    }
 234
 235    private static void CheckMessage(MimeMessage message)
 236    {
 6237        if (message.From.Mailboxes.All(x => string.IsNullOrEmpty(x.Address)))
 238        {
 3239            throw new EmptySenderAddressesException();
 240        }
 3241    }
 242
 3243    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    {
 3248        Directory.CreateDirectory(pickupDirectory ?? string.Empty);
 3249        var path = Path.Combine(pickupDirectory ?? string.Empty, Guid.NewGuid() + ".eml");
 250
 3251        await using var stream = new FileStream(path, FileMode.CreateNew);
 3252        await message.WriteToAsync(stream, cancellationToken).ConfigureAwait(false);
 3253    }
 254
 255    private async Task ConnectAndAuthenticateAsync(SmtpClient client, CancellationToken cancellationToken)
 256    {
 0257        await client.ConnectAsync(
 0258            smtpClientOptions.Server!,
 0259            smtpClientOptions.Port,
 0260            SmtpSecureSocketOptionsResolver.Resolve(smtpClientOptions),
 0261            cancellationToken).ConfigureAwait(false);
 262
 0263        if (smtpClientOptions.RequiresAuthentication)
 264        {
 0265            await client.AuthenticateAsync(smtpClientOptions.User!, smtpClientOptions.Password!, cancellationToken).Conf
 266        }
 0267    }
 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