Sample code of sending e-mail by using fluent email in. Net core

Time:2021-1-2

preface

In the actual project development, we will encounter many scenarios that need to send mail through the program, such as exception alarm, message, progress notification and so on. Generally, we use the native smtpclient class library, which can meet most of our scenarios. But it is not concise enough to use. Many scenarios need to be implemented by our own encapsulation methods, and the amount of code is very considerable. Fortunately, we have a very good component, which can meet most of our application scenarios. It is simple to use and powerful. Today we will talk about fluent email, which is also the mail sending component that we are actually using in the project. If you need to send email in. Net core, you are also recommended to try it.

FluentEmail

Fluent email is an open source and free mail sending component supporting. Net and. Net core on GitHub. At present, it has more than 1K stars, and with the growing maturity of. Net core in recent two years, its star growth trend is still very rapid. It’s at GitHub addresshttps://github.com/lukencode/FluentEmailIt is very powerful and practical. It supports razor’s mail template and sendgrid, mailgun and SMTP for sending mail. It is also very simple to use.

Nuget component

Fluent email is powerful, and it supports different scenarios with independent nuget packages. This low coupling split not only makes the dependency very clear, but also avoids introducing unnecessary code. The specific functions are included in the following component packages

Normal mail

Next, let’s demonstrate how to use fluent email to send e-mail. Since most of our business uses SMTP to send e-mail, we will take this as a demonstration. First, we will introduce it in the project FluentEmail.Smtp The latest version is 2.8.0


<PackageReference Include="FluentEmail.Smtp" Version="2.8.0" />

Next, we can write code happily. Its coding method is very simple and concise, mainly through chain programming

//If you use the SMTP service to send mail, you must set the SMTP service information
SmtpClient smtp = new SmtpClient
{
  //The address of the SMTP server (I'll take mailbox 126 as an example, which can be set according to the specific mailbox you use)
  Host = "smtp.126.com",
  UseDefaultCredentials = true,
  DeliveryMethod = SmtpDeliveryMethod.Network,
  //Enter the user name and password of your sending SMTP server here
  Credentials = new networkcredential ("mailbox user name", "mailbox password")
};
//Set default sending information
Email.DefaultSender = new SmtpSender(smtp);
var email = Email
  //Sender
  .From("[email protected]")
  //Addressee
  .To("[email protected]")
  //CC to
  .CC("[email protected]")
  //Message title
  . subject ("message title")
  //Email content
  . body ("email content");
//Determine whether the transmission is successful according to the transmission result
var result = email.Send();
//Or send it asynchronously
//await email.SendAsync();
if (result.Successful)
{
  //Send success logic
}
else
{
  //If the sending fails, you can pass the result.ErrorMessages View failure reasons
}

If the content you send contains HTML content, you can use the following methods

var email = Email
  //Sender
  .From("[email protected]")
  //Addressee
  .To("[email protected]")
  //CC to
  .CC("[email protected]")
  //Message title
  . subject ("message title")
  //Just set the second parameter to true
  . body ("< H1 align = \" center \ ">. Net Dafa is good < / H1 > < p > Yes, there is no < / P >", true);
//Send
var result = email.Send();

The second parameter is used to indicate whether the content is in HTML format. The default value is false


IFluentEmail Body (string body, bool isHtml = false);

If the recipients of the e-mail are multiple e-mail addresses, another overload method of to method can be used to accept list< FluentEmail.Core.Models .Address>

var email = Email
  //Sender
  .From("[email protected]")
  //Message title
  . subject ("message title")
  //Email content
  . body ("< H1 align = \" center \ ">. Net Dafa is good < / H1 > < p > Yes, there is no problem at all < / P >", true);

//Building multiple recipient mailbox
string toUserStr = "[email protected];[email protected];[email protected]";
List<FluentEmail.Core.Models.Address> toUsers = toUserStr.Split(";")
  .Select(i => new FluentEmail.Core.Models.Address { EmailAddress = i }).ToList();
//Supports incoming address collection
email.To(toUsers)
//CC collection
.CC(toUsers);
//Send
var result = email.Send();

If we need to add an attachment to the sent message, we can use the attach method to add the attachment

var email = Email
    //Sender
    .From("[email protected]")
    //Addressee
    .To("[email protected]")
    //CC to
    .CC("[email protected]")
    //Message title
    . subject ("about. Net core")
    //Email content
    . body ("< H1 align =" center ">. Net core < / H1 > < p >. Net core is excellent? Yes, no problem at all!!! </p>",true);

//Build attachments
var stream = new MemoryStream();
var sw = new StreamWriter(stream);
sw.WriteLine ("Hello, this is the content of the text");
sw.Flush();
stream.Seek(0, SeekOrigin.Begin);
var attachment = new FluentEmail.Core.Models.Attachment
{
  Data = stream,
  ContentType = "text/plain",
  Filename = "Hello.txt"
};
//Add attachment
email.Attach(attachment);
var result = email.Send();

If you need to add multiple attachments, the attach method supports passing in the attachment collection

//Build attachments
var stream = new MemoryStream();
var sw = new StreamWriter(stream);
sw.WriteLine ("Hello, this is the content of the text");
sw.Flush();
stream.Seek(0, SeekOrigin.Begin);
//Annex 1
var attachment = new FluentEmail.Core.Models.Attachment
{
  Data = stream,
  ContentType = "text/plain",
  Filename = "Hello.txt"
};

//Annex 2
var attachment2 = new FluentEmail.Core.Models.Attachment
{
  Data = File.OpenRead(@"D:\test.txt"),
  ContentType = "text/plain",
  Filename = "test.txt"
};

//Add attachment
email.Attach(new List<FluentEmail.Core.Models.Attachment> { attachment, attachment2 });
var result = email.Send();

Using the razor template

In the above content, we introduced the use of fluent email to send e-mail in the conventional way, but sometimes we need to send some dynamic content or send some HTML web content with complex style. Usually we use native smptclient by splicing HTML code, but this method is relatively time-consuming and laborious. For. Net programmers, razor engine is the most familiar way to build dynamic HTML pages, and fluent email provides us with razor template support. First of all, we introduce the FluentEmail.Razor Template support component


<PackageReference Include="FluentEmail.Razor" Version="2.8.0" />

because ASP.NET Core2.2 starts with the view compilation function by default, and the view will be compiled into the project name Views.dll , but FluentEmail.Razor You also need to read the contents of the view file, so add the following contents to the csproj file


<MvcRazorExcludeRefAssembliesFromPublish>true</MvcRazorExcludeRefAssembliesFromPublish>

Then we can use the razor template to generate the email content, and the specific usage

//Declare how to use razor
Email.DefaultRenderer = new RazorRenderer();
//Razor content
Var template = [email protected] Model.Name Please verify that your telephone number [email protected] Model.Phone ";
var email = Email
  .From("[email protected]")
  .To("[email protected]")
  . subject ("mobile phone number verification")
  //Passing custom poco classes
  //. usingtemplate < userinfo > (template, new userinfo {name = Zhang San, phone = 100110119120})
  //Or pass an anonymous object
  . usingtemplate (template, new {name = Zhang San, phone = 100110119120});
var result = await email.SendAsync();

Of course, it supports not only razor strings, but also razor view files

var email = Email
  .From("[email protected]")
  .To("[email protected]")
  . subject ("mobile phone number verification")
  //Passing custom poco classes
  //.UsingTemplateFromFile<UserInfo>($"{Directory.GetCurrentDirectory()}/template.cshtml", 
  //New userinfo {name = Zhang San, phone = 100110119120};
  //The first parameter is the view file location, and the second parameter is the model object
  .UsingTemplateFromFile($"{Directory.GetCurrentDirectory()}/template.cshtml", 
    New {name = Zhang San, phone = 100110119120});
var result = await email.SendAsync();

FluentEmail.Razor The reason why it can support the powerful razor template engine is mainly due to its internal integration of razorlight, which is a very powerful razor engine. You can parse the razor template string or razor view file into specific string results. For details, please refer to the official GitHub address of razorlighthttps://github.com/toddams/RazorLightAt present, the official version does not support. Net core. You can choose to download the beta version


Install-Package RazorLight -Version 2.0.0-beta10

It’s also very simple to use

//How to use the razor string
var engine = new RazorLightEngineBuilder()
	.UseEmbeddedResourcesProject(typeof(Program))
	.UseMemoryCachingProvider()
	.Build();
string template = "Hello, @Model.Name. Welcome to RazorLight repository";
ViewModel model = new ViewModel {Name = "John Doe"};
//Result is the parsed string
string result = await engine.CompileRenderStringAsync("templateKey", template, model);

Or using the razor view file


var engine = new RazorLightEngineBuilder()
	.UseFileSystemProject("${Directory.GetCurrentDirectory()}")
	.UseMemoryCachingProvider()
	.Build();
var model = new {Name = "John Doe"};
string result = await engine.CompileRenderAsync("template.cshtml", model);

Of course, it supports not only these two ways, but also the convenience and function. Interested students can check the GitHub address of razorlight and explain it in great detail. I won’t talk too much about how to use razorlight here.

There is a very important point about the content of the e-mail to be sent. For public e-mail operators such as Netease or Tencent, some may need to manually start the SMTP service. Please refer to the specific settingshttps://www.jb51.net/diannaojichu/520949.htmlOne article. Another important point is that if you use the mailbox of the public mailbox operator, they will have more restrictions on the title and content of the email, and there may be more problems. Moreover, to start the SMTP service, you need to send SMS authentication. Fortunately, most companies have their own e-mail system, and there may not be so many problems in the actual process of sending e-mail.

Combined with dependency injection

In the actual development using. Net core, dependency injection has become an indispensable development mode. If you are using. Net core to develop a project, but you have not contacted dependency injection yet, you need to reflect on yourself first. As a component that keeps pace with the times, fluent email can also be used in combination with dependency injection. In this way, we can uniformly configure some default settings when registering. This wave of operation does not need to introduce additional packages. If you need to use SMTP, you can do so FluentEmail.Smtp Package, if you need to use the razor template, introduce it FluentEmail.Razor Package, the function of this part of injection is actually included in FluentEmail.Core Inside the bag

public void ConfigureServices(IServiceCollection services)
{
  SmtpClient smtp = new SmtpClient
  {
    //The address of the SMTP server (I'll take mailbox 126 as an example, which can be set according to the specific mailbox you use)
    Host = "smtp.qq.com",
    UseDefaultCredentials = true,
    DeliveryMethod = SmtpDeliveryMethod.Network,
    //Enter the user name and password of your sending SMTP server here
    Credentials = new NetworkCredential("[email protected]", "zhangsan")
  };
  //Some default settings can be added during injection
  services
    //Set default sending user
    .AddFluentEmail("[email protected]")
    //Add razor template support
    //.AddRazorRenderer($"{Directory.GetCurrentDirectory()}/Views")
    .AddRazorRenderer()
    //Configure default SMTP service information
    .AddSmtpSender(smtp);
}

If you directly inject ifluentemail into the class that needs to send e-mail, you don’t need to panic. The email class we used above actually implements the interface ifluentemail, so the usage is completely consistent

public async Task<IActionResult> SendEmail([FromServices]IFluentEmail email)
{
   Var result = await email // sender
    //Sender
    .From("[email protected]")
    //Addressee
    .To("[email protected]")
    //CC to
    .CC("[email protected]")
    //Message title
    . subject ("message title")
    //Email content
    . body ("email content"). Sendasync();
  return View();
}

If you need to send the content related to the razor view template, it’s still the familiar formula and the familiar taste. There’s no difference, but it omits some default configurations that we added when registering

public async Task<IActionResult> SendEmail([FromServices]IFluentEmail email)
{
   Var result = await email // sender
    //Sender
    .From("[email protected]")
    //Addressee
    .To("[email protected]")
    //CC to
    .CC("[email protected]")
    //Message title
    . subject ("message title")
    //Email content
    . body ("email content"). Sendasync();
  return View();
}

summary

Let’s introduce the basic usage of fluent email here. I personally feel that its own function is very powerful and easy to use. To tell you the truth, before I came into contact with fluent email, I often saw in the garden that other languages integrated email sending components, which are really very powerful. For example, integrating spring boot starter mail in springboot is really very convenient. Later, I came into contact with fluent email by accident. I’m very pleased with its powerful function and ease of use. Secondly, it can be combined with. Net core to further optimize its use. At least in. Net and. Net core, we also have a very convenient email sending component. The author of fluent email also calls for more developers to understand and participate in the development and practice of fluent email, and finally paste its GitHub address againhttps://github.com/lukencode/FluentEmail

This article about. Net core using fluent email to send e-mail sample code is introduced here. For more related. Net core sending e-mail content, please search previous articles of developer or continue to browse the following related articles. I hope you can support developer more in the future!

Recommended Today

Summary of recent use of gin

Recently, a new project is developed by using gin. Some problems are encountered in the process. To sum up, as a note, I hope it can help you. Cross domain problems Middleware: func Cors() gin.HandlerFunc { return func(c *gin.Context) { //Here you can use * or the domain name you specify c.Header(“Access-Control-Allow-Origin”, “*”) //Allow header […]