Go to content

Bulletcode.NET

Mail

Bulletcode.NET includes a service for sending emails using SMTP, based on MailKitLite. To use it, call the AddMailService() extension method of the IServiceCollection:

services.AddMailService();

The MailOptions class contains settings related to sending emails. They can be changed by passing a callback to the AddMailService() method, or by adding a MailOptions section to the appsettings.json file.

  • Host — host name of the SMTP server. The default value is "localhost".
  • Port — the port number of the SMTP server. The default value is 25.
  • UseSSL — if true, SSL is required to connect to the SMTP server.
  • UserName — the user name used to login to the SMTP server.
  • Password — the password used to login to the SMTP server.
  • SenderName — the default sender name added to the From header of the sent emails.
  • SenderEmail — the default sender email address added to the From header of the sent emails.

The IMailService can be used to send emails. The email body can be passed directly as a string, using the SendHtml() method, or rendered using a Razor view with a specified model, using the SendView() method. For example:

_mailService.SendView( "to@example.com", "Mail/Example", model );

Emails are sent by a background process. The SendHtml() and SendView() methods add the email to the queue and return immediately.

When rendering the view, the RecipientAddress and RecipientName values are passed to the view data dictionary. The email subject is extracted from the Subject value in the view data dictionary. For example:

@{
    ViewData[ "Subject" ] = _( "Reset your password" );
}

<p>Hello, @ViewData[ "RecipientName" ]</p>

Internally, the SendView() method uses the IViewRendererFactory service to create a IViewRenderer for the specified view. The IViewRenderer has a RenderToStringAsync() method which accepts a model and an optional dictionary. This dictionary is used to populate the view data dictionary for the rendered view, and it’s updated with the values from the view data dictionary when the view finishes rendering.

The IViewRendererFactory creates a custom implementation of IUrlHelper which generates absolute URLs using the base URL of the server. This URL can customized by adding a ServerOptions section to the appsettings.json file.

  • ServerUrl — the base URL of the server. If null, the automatic detection mechanism is used.
  • ForceHttps — if true, the automatic detection mechanism always uses the HTTPS protocol, even when the server doesn’t use HTTPS (it can be useful when the server is behind a reverse proxy).

The IMailService also has CreateHtml() and CreateView() methods, which create an IMimeMessageFactory object representing the email message, which can be sent using the Send() method. This makes it possible to customize the message before it’s sent.