An example of sending an eMail with the MailKit library

The MailKit library https://github.com/jstedfast/MailKit for .NET is very usefull in sending SMTP mail messages. Here is an example of a service that sends messages with that library.

To use the library search MimeKit and MailKit in nuget


public interface IMailService
{
	Task SendSomeMessage(string email, string text);
}

public class MailService: IMailService
{
	private readonly ILogger<MailService> _logger;
	private readonly IConfiguration _configuration;

	private string _smtpHost { get; set; }
	private int _smtpPort { get; set; }
	private string _smtpUser { get; set; }
	private string _smtpPassword { get; set; }

	public MailService(
		ILogger<MailService> logger,
		IConfiguration configuration
		)
	{

		_logger = logger;
		_configuration = configuration;

		_smtpHost = _configuration["Mail:SmtpHost"];
		_smtpPort = int.TryParse(_configuration["Mail:SmtpPort"], out int smtpPort) ? smtpPort: 25;
		_smtpUser = _configuration["Mail:SmtpUser"];
		_smtpPassword = _configuration["Mail:SmtpPassword"];
	}

	public async Task SendSomeMessage(string email, string text)
	{
		_logger.LogDebug($"Sending some message: {text}");

		using SmtpClient smtpClient = new ();

		try
		{

			var message = new MimeMessage();
			message.From.Add(new MailboxAddress("Me", _configuration["Mail:From"]));
			message.To.Add(new MailboxAddress(email, email));
			message.Subject = "Some Subject";

			message.Body = new TextPart(MimeKit.Text.TextFormat.Html)
			{
				Text = $@"Please click the link: <br/><a href=''>Some Link</a>"
			};

			await smtpClient.ConnectAsync(_smtpHost, _smtpPort, false);

			if (!string.IsNullOrWhiteSpace(_smtpUser) && !string.IsNullOrWhiteSpace(_smtpPassword))
				await smtpClient.AuthenticateAsync(_smtpUser, _smtpPassword);

			await smtpClient.SendAsync(message);
		}
		catch (Exception e)
		{
			_logger.LogError($"{e}");
		}
		finally
		{
			if (smtpClient.IsConnected)
				await smtpClient.DisconnectAsync(true);
		}
	}
}

Post a Comment

Previous Post Next Post