Implementation method of sending mail in asp.net core (required)

Time:2021-10-15

preface

We know that at present, the. Net core does not support the SMTP protocol. When we use the mail sending function, we need to use some third-party components to achieve the purpose. Today, we will introduce two open-source mail sending components, mailkit and fluent email. I will introduce them respectively below.

MailKit

In asp.net core, mailkit can be used to send mail. It supports cross platform and IMAP, POP3, SMTP and other protocols.

You can install it in the following way:

Install-Package MailKit

Here is a simple example of sending mail:

var message = new MimeMessage ();
message.From.Add (new MailboxAddress ("Joey Tribbiani", "[email protected]"));
message.To.Add (new MailboxAddress ("Mrs. Chanandler Bong", "[email protected]"));

Message. Subject = "where to play on Sunday?";

Message. Body = new textpart ("plain") {text = "I want to go to 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 is also an open source project. With it, you can use razor template to send mail, and integrate some third-party mail sending programs, such as mailgun, but this package only supports SMTP under. Net 4.6. You can install it using the following command:


Install-Package FluentEmail.Razor

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

//Note: only. Net 4.6 is supported
Email.DefaultSender = new SmtpSender();

var email = Email
  .From("[email protected]")
  .To("[email protected]", "bob")
  . subject ("where to play on Sunday?")
  . body ("how about going to the Forbidden City?");

await email.SendAsync();

Alternatively, you can use the razor template to send:

//Note: only. Net 4.6 is supported
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("[email protected]")
  .To("[email protected]")
  .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 a template template with the template string of razor syntax, and then uses usingtemplate for rendering.

Cshtml template on disk

Adding your email razor template file is relatively large, and it is not elegant to use a string. Then you can put the template file on disk and load it in the following way:

//Note: only. Net 4.6 is supported
Email.DefaultSender = new SmtpSender();

Email.DefaultRenderer = new RazorRenderer();

var email = Email
  .From("[email protected]")
  .To("[email protected]", "bob")
  . subject ("where to play on Sunday?")
  .UsingTemplateFromFile($"{Directory.GetCurrentDirectory}/EmailTemplage.cshtml", new {Name ="Luke"})

Send mail using mailgun

Some people may not know 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 10000 emails a month, which is enough for many small and medium-sized websites.

When using mailgun to send mail, you first need to register an account, and then you can use the rest API provided by mailgun to manage the sent or received mail. Mailgun integrated with fluent email only needs to add the following packages:


Install-Package FluentEmail.Mailgun

After registering mailgun, you will be assigned an API key and a secondary domain name. In the program type, you need the following configuration:

//Both. Net core and. Net framework are supported
var sender = new MailgunSender(
  "Sandboxcf5f41bbf2f84f15a386c60e253b5fe8. Mailgun. Org", // mailgun secondary domain name
  "key-8d32c046d7f14ada8d5ba8253e3e30df" // Mailgun API Key
);

Email.DefaultSender = sender;

var email = Email
  .From("[email protected]")
  .To("[email protected]", "bob")
  . subject ("where to play on Sunday?")
  . body ("how about going to the Forbidden City?");

await email.SendAsync();

summary

From the above examples, we can see that mailkit and fluent email 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 if mailgun is used, it needs to be integrated by itself. The advantage of flentemail is that it provides razor template support and encapsulates mailgun. The disadvantage is that the SMTP protocol does not provide support for. Net core.

To sum up, if you use mailgun to send mail, you should choose fluent email. If you want to use SMTP protocol to link to your own mail server to send mail, you should use mailkit.

The above implementation method of sending e-mail in asp.net core (must see article) is all the content shared by Xiaobian. I hope it can give you a reference and support developpaer.