Implementation method of sending mail in ASP. NET Core

  • 2021-09-20 20:00:11
  • OfStack

Preface

We know that at present, NET Core does not support SMTP protocol. When we use the function of sending mail, we need to use some third-party components to achieve our goal. Today, we introduce two open source mail sending components, which are MailKit and FluentEmail. I will introduce them respectively below.

MailKit

In ASP. NET Core, you can use MailKit to send mail, which supports cross-platform, and supports IMAP, POP3, SMTP and other protocols.

You can install it in the following ways:

Install-Package MailKit

Here is a simple example of sending mail:


var message = new MimeMessage ();
message.From.Add (new MailboxAddress ("Joey Tribbiani", "joey@friends.com"));
message.To.Add (new MailboxAddress ("Mrs. Chanandler Bong", "chandler@friends.com"));

message.Subject = " Where to play on Sunday? ";

message.Body = new TextPart ("plain") { Text = " I want to visit the Forbidden City, how about " };

using (var client = new SmtpClient ()) {
  // For demo-purposes, accept all SSL certificates (in case the server supports STARTTLS)
  client.ServerCertificateValidationCallback = (s,c,h,e) => true;

  client.Connect ("smtp.friends.com", 587, false);

  // Note: since we don't have an OAuth2 token, disable
  // the XOAUTH2 authentication mechanism.
  client.AuthenticationMechanisms.Remove ("XOAUTH2");

  // Note: only needed if the SMTP server requires authentication
  client.Authenticate ("joey", "password");

  client.Send (message);
  client.Disconnect (true);
}

If the Body content you want to send is HTML, you can use the following:


var bodyBuilder = new BodyBuilder();
bodyBuilder.HtmlBody = @"<b>This is bold and this is <i>italic</i></b>";
message.Body = bodyBuilder.ToMessageBody();

Fluent Email

Fluent Email This is also an open source project, with which you can use the Razor template to send mail, and can integrate a number of third-party mail sending programs such as Mailgun, etc., but this package only supports SMTP under. NET 4.6. You can use the following command to install it:


Install-Package FluentEmail.Razor

You can use the most basic way to send email, which is as follows:


// Note:  .NET 4.6  To support 
Email.DefaultSender = new SmtpSender();

var email = Email
  .From("foo@email.com")
  .To("bar@email.com", "bob")
  .Subject(" Where to play on Sunday? ")
  .Body(" I want to visit the Forbidden City, OK? ");

await email.SendAsync();

Alternatively, you can use the Razor template to send:


// Note:  .NET 4.6  To support 
Email.DefaultSender = new SmtpSender();

// Using Razor templating package
Email.DefaultRenderer = new RazorRenderer();

var template = "Dear @Model.Name, You are totally @Model.Compliment.";

var email = Email
  .From("bob@hotmail.com")
  .To("somedude@gmail.com")
  .Subject("woo nuget")
  .UsingTemplate(template, new { Name = "Luke", Compliment = "Awesome" });

Email. DefaultRenderer tells FulentEmail which renderer to use (you can also implement your own), then provides an template template with Razor syntax template string, and then uses UsingTemplate for rendering.

cshtml template on disk

Add your email Razor template file is relatively large, and it is not elegant to express it in string, so you can put the template file on disk and load it in the following way:


// Note:  .NET 4.6  To support 
Email.DefaultSender = new SmtpSender();

Email.DefaultRenderer = new RazorRenderer();

var email = Email
  .From("foo@email.com")
  .To("bar@email.com", "bob")
  .Subject(" Where to play on Sunday? ")
  .UsingTemplateFromFile($"{Directory.GetCurrentDirectory}/EmailTemplage.cshtml", new {Name ="Luke"})

Send mail using Mailgun

Some people may not be clear about Mailgun. Mailgun is a foreign mail service company. For example, the famous Github mail service is hosted on it. The free Maingun account can send 10,000 emails every month, which is enough for many small and medium-sized websites.

When using Mailgun to send emails, you first need to register an account, and then you can use Rest API provided by Mailgun to manage the emails sent or received. Mailgun using FluentEmail integration only needs to add the following packages:


Install-Package FluentEmail.Mailgun

After registering Mailgun, you will be assigned 1 API Key and 1 level 2 domain name. In the program type, you need the following configuration:


//  Simultaneous support  .NET Core  And  .NET Framework
var sender = new MailgunSender(
  "sandboxcf5f41bbf2f84f15a386c60e253b5fe8.mailgun.org", // Mailgun 2 Class domain name 
  "key-8d32c046d7f14ada8d5ba8253e3e30df" // Mailgun API Key
);

Email.DefaultSender = sender;

var email = Email
  .From("foo@email.com")
  .To("bar@email.com", "bob")
  .Subject(" Where to play on Sunday? ")
  .Body(" I want to visit the Forbidden City, OK? ");

await email.SendAsync();

Summarize

From the above examples, we can see that MailKit and FluentEmail have their own advantages and disadvantages. The advantage of MailKit is that it supports many protocols and is cross-platform, but the disadvantage is that it does not provide support for Razor, and it needs to be integrated by itself if Mailgun is used. The advantage of FlentEmail is that it provides support for the Razor template and encapsulates Mailgun, but the disadvantage is that the SMTP protocol does not provide support for. NET Core.

To sum up, if you use Mailgun to send mail, then FluentEmail is your choice, and if you want to use SMTP protocol to link to your own mail server to send mail, then you should use MailKit.


Related articles: