Skip to content
Daniel Collingwood edited this page Nov 25, 2022 · 9 revisions

MailKitSimplified.Sender Usage

Installation NuGet Downloads

Package Manager Console

Install-Package MailKitSimplified.Sender # -Version x.x.x

.NET CLI Console

dotnet add package MailKitSimplified.Sender # --version x.x.x

Setup

If you're not familiar with dependency injection then you can specify the SMTP host address like this:

using var smtpSender = SmtpSender.Create("smtp.example.com").SetPort(25);

An email sender must have a SMTP host address, and sometimes a port number, but leaving the port as the default value of 0 will normally choose the right port automatically (e.g. 25, 587). Most companies use LDAP or something similar for behind-the-scenes authentication, but if not you can specify a network credential too. Use SetProtocolLog("") to quickly debug with detailed logging to the console, or use something like SetProtocolLog("Logs/SmtpClient.txt") to output logs to a file.

Sending Mail

await smtpSender.WriteEmail
    .From("my.name@example.com")
    .To("YourName@example.com")
    .Subject("Hello World")
    .Attach(@"C:\Temp\EmailClientSmtp.log")
    .SendAsync();

Using the method above will pass exceptions up to the next layer, but if you just want to log exceptions then continue with a "false" output that can also be done using the "try" prefix:

bool isSent = await smtpSender.WriteEmail
    .From("me@example.com", "My Name")
    .To("you@example.com", "Your Name")
    .Cc("friend@example.com")
    .Bcc("admin@localhost")
    .Subject($"Hello at {DateTime.Now}!")
    .BodyText("Optional text/plain content.")
    .BodyHtml("Optional text/html content.<br/>")
    .TryAttach("C:/Temp/attachment1.txt", "C:/Temp/attachment2.pdf")
    .TrySendAsync();

_logger.LogInformation("Email {result}.", isSent ? "sent" : "failed to send");

Further examples (how to set up MailKit SMTP server logs etc.) can be found in the samples and tests folders on GitHub.

MailKitSimplified.Sender Dependency Injection

Dependency Injection is recommended over manual setup as the built-in garbage collector will handle lifetime and disposal.

using MailKitSimplified.Sender;

IHost host = Host.CreateDefaultBuilder(args)
    .ConfigureServices((context, services) =>
    {
        services.AddHostedService<ExampleNamespace.Worker>();
        services.AddMailKitSimplifiedEmailSender(context.Configuration);
    })
    .Build();

await host.RunAsync();

You'll also need the following in appsettings.json (check Properties -> Copy to Output Directory -> Copy if newer):

{
  "EmailSender:SmtpHost": "smtp.example.com",
}

Other optional settings include SmtpPort, ProtocolLog, SmtpCredential:UserName and SmtpCredential:Password.

Now you can use the fully configured ISmtpSender or IEmailWriter anywhere you want with no other setup! For example:

public class EmailService
{
    private readonly IEmailWriter _writeEmail;

    public EmailService(IEmailWriter writeEmail) {
        _writeEmail = writeEmail;
    }
}

That's how sending an email can become as simple as one line of code.

await _writeEmail.To("test@localhost").SendAsync();

See Also

Clone this wiki locally