NET Core Sample code for sending mail using FluentEmail

  • 2021-11-24 01:13:14
  • OfStack

Preface

In the actual project development, we will encounter many scenarios that need to send mail through programs, such as abnormal alarm, message, progress notification and so on. In general, we use the native SmtpClient class library, which can meet most of our scenarios. However, it is not simple enough to use, and many scenarios need our own encapsulation methods to implement, and the amount of code is very considerable. Thankfully, we have a great component that can meet most of our application scenarios, and it is simple to use and powerful, that is, FluentEmail, which is what we are going to talk about today, and this is also the mail sending component that we are actually using in the project. If you need to send email in. Net Core, it is also recommended to try 1.

FluentEmail

FluentEmail is an open source and free mail sending component supporting Net and Net Core on GitHub. At present, there are more than 1K Star, and with the maturity of Net Core in recent two years, its Star growth trend is still very rapid. Its address at GitHub is https://github. com/lukencode/FluentEmail. It is very powerful and practical. It supports the mail template of Razor and sends mail using SendGrid, MailGun and SMTP, and it is also very simple to use.

Nuget component

FluentEmail is powerful, and there are independent Nuget packages for different scenarios. This low-coupling split not only makes dependencies very clear, but also avoids introducing unnecessary code. The specific functions are included in the following component packages

FluentEmail. Core-The basic core package contains the basic model definitions and default settings, and the following reference packages contain this core package. FluentEmail. Smtp-A package that uses the SMTP service to send mail. FluentEmail. Razor-Generate the message delivery content from the Razor template. FluentEmail. Mailgun-Send mail using the Rest interface of Mailgun. FluentEmail. SendGrid-Send mail using the SendGrid interface. FluentEmail. Mailtrap-Send the message Mailtrap using the FluentEmail. Smtp packet. FluentEmail. MailKit-Send messages using the MailKit mail library.

Ordinary mail

Next, we will demonstrate how to use FluentEmail to send mail under 1. Because most of our actual business uses SMTP to send mail, we will take this as a demonstration. First, we introduce FluentEmail. Smtp package in the project, and the latest version is 2.8. 0 at present


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

Then we can write the code happily, and its coding method is very simple and concise, mainly through chain programming


// If you use smtp Service sending mail must be set smtp Service information 
SmtpClient smtp = new SmtpClient
{
  //smtp Server address ( I am here to 126 Mailbox, for example, can be set according to the specific mailbox you use )
  Host = "smtp.126.com",
  UseDefaultCredentials = true,
  DeliveryMethod = SmtpDeliveryMethod.Network,
  // Enter here that you are sending smtp User name and password for the server 
  Credentials = new NetworkCredential(" Mailbox User Name ", " Mailbox password ")
};
// Set the default sending information 
Email.DefaultSender = new SmtpSender(smtp);
var email = Email
  // Sender 
  .From("zhangsan@126.com")
  // Recipient 
  .To("lisi@qq.com")
  // Cc to 
  .CC("admin@126.com")
  // Message header 
  .Subject(" Message header ")
  // Mail content 
  .Body(" Mail content ");
// Judging 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
{
  // Send failure can be passed through result.ErrorMessages View the cause of failure 
}

If the content you send contains content in html format, you can use the following methods


var email = Email
  // Sender 
  .From("zhangsan@126.com")
  // Recipient 
  .To("lisi@qq.com")
  // Cc to 
  .CC("admin@126.com")
  // Message header 
  .Subject(" Message header ")
  // You only need to set the extra number 2 Parameters are true You can 
  .Body("<h1 align=\"center\">.NET Good Dafa </h1><p> Yes , This 1 There is nothing wrong with it </p>",true);
// Send 
var result = email.Send();

We can know that the second parameter is used to indicate whether the content is in html format by clicking on the method declaration of Body, and the default is false


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

If the message is addressed to multiple mailbox addresses, another overloaded method that can use the To method can accept List < FluentEmail.Core.Models.Address >


var email = Email
  // Sender 
  .From("zhangsan@126.com")
  // Message header 
  .Subject(" Message header ")
  // Mail content 
  .Body("<h1 align=\"center\">.NET Good Dafa </h1><p> Yes ,1 There is nothing wrong with it </p>",true);

// Build multiple recipient mailboxes 
string toUserStr = "oldwang@126.com;xiaoming@163.com;xiaoli@qq.com";
List<FluentEmail.Core.Models.Address> toUsers = toUserStr.Split(";")
  .Select(i => new FluentEmail.Core.Models.Address { EmailAddress = i }).ToList();
// Support incoming Address Set 
email.To(toUsers)
// Cc collection 
.CC(toUsers);
// Send 
var result = email.Send();

If we need to add an attachment to the mail we send, we can use the Attache method to add an attachment


var email = Email
    // Sender 
    .From("zhangsan@qq.com")
    // Recipient 
    .To("lisi@126.com")
    // Cc to 
    .CC("admin@126.com")
    // Message header 
    .Subject(" About .Net Core How is it ")
    // Mail content 
    .Body("<h1 align=\"center\">.NET Core</h1><p>.Net Core Is it excellent? Yes ,1 There's nothing wrong with it! ! ! </p>",true);

// Build attachments 
var stream = new MemoryStream();
var sw = new StreamWriter(stream);
sw.WriteLine(" How do you do , 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 attachments 
email.Attach(attachment);
var result = email.Send();

If you need to add more than one attachment, the Attach method supports passing in the Attachment collection


// Build attachments 
var stream = new MemoryStream();
var sw = new StreamWriter(stream);
sw.WriteLine(" How do you do , 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 attachments 
email.Attach(new List<FluentEmail.Core.Models.Attachment> { attachment, attachment2 });
var result = email.Send();

Using the Razor template

Above we have described the use of FluentEmail to send mail in a normal way, but sometimes we need to send a content that is dynamic or a content that is more complex in style than html Web pages. Usually, when we use native SmptClient, we splice html code, but this method is relatively time-consuming and laborious. For. Net programmers, Razor engine is the most familiar way for us to build dynamic html pages, and FluentEmail provides us with Razor template support. First, we introduce the FluentEmail. Razor template support component based on the previous one


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

Since ASP. NET Core 2.2 uses the view compilation function by default, the view will be compiled to the project name. Views. dll, but FluentEmail. Razor needs to read the contents of the view file, so add the following to the csproj file


<MvcRazorExcludeRefAssembliesFromPublish>true</MvcRazorExcludeRefAssembliesFromPublish>

Then we can use the Razor template to generate the email content, the specific way to use it


// Declare using razor The way of 
Email.DefaultRenderer = new RazorRenderer();
//razor Content 
var template = " How do you do @Model.Name Sir ,  Please verify that your phone number is @Model.Phone";
var email = Email
  .From("lisi@126.com")
  .To("zhangsan@qq.com")
  .Subject(" Mobile phone number verification ")
  // Pass custom POCO Class 
  //.UsingTemplate<UserInfo>(template, new UserInfo { Name = " Zhang 3", Phone Is it  = "100110119120" })
  // Or pass an anonymous object 
  .UsingTemplate(template, new { Name = " Zhang 3", Phone Is it  = "100110119120" });
var result = await email.SendAsync();

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


// If you use smtp Service sending mail must be set smtp Service information 
SmtpClient smtp = new SmtpClient
{
  //smtp Server address ( I am here to 126 Mailbox, for example, can be set according to the specific mailbox you use )
  Host = "smtp.126.com",
  UseDefaultCredentials = true,
  DeliveryMethod = SmtpDeliveryMethod.Network,
  // Enter here that you are sending smtp User name and password for the server 
  Credentials = new NetworkCredential(" Mailbox User Name ", " Mailbox password ")
};
// Set the default sending information 
Email.DefaultSender = new SmtpSender(smtp);
var email = Email
  // Sender 
  .From("zhangsan@126.com")
  // Recipient 
  .To("lisi@qq.com")
  // Cc to 
  .CC("admin@126.com")
  // Message header 
  .Subject(" Message header ")
  // Mail content 
  .Body(" Mail content ");
// Judging 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
{
  // Send failure can be passed through result.ErrorMessages View the cause of failure 
}
0

The reason why FluentEmail. Razor can support the powerful Razor template engine is mainly due to its internal integration of RazorLight. This is a very powerful Razor engine, which can parse Razor template string or Razor view file into specific string results. For details, please refer to the official GitHub address https://github.com/toddams/RazorLight. At present, the official version does not support. Net Core, and you can choose to download beta version


// If you use smtp Service sending mail must be set smtp Service information 
SmtpClient smtp = new SmtpClient
{
  //smtp Server address ( I am here to 126 Mailbox, for example, can be set according to the specific mailbox you use )
  Host = "smtp.126.com",
  UseDefaultCredentials = true,
  DeliveryMethod = SmtpDeliveryMethod.Network,
  // Enter here that you are sending smtp User name and password for the server 
  Credentials = new NetworkCredential(" Mailbox User Name ", " Mailbox password ")
};
// Set the default sending information 
Email.DefaultSender = new SmtpSender(smtp);
var email = Email
  // Sender 
  .From("zhangsan@126.com")
  // Recipient 
  .To("lisi@qq.com")
  // Cc to 
  .CC("admin@126.com")
  // Message header 
  .Subject(" Message header ")
  // Mail content 
  .Body(" Mail content ");
// Judging 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
{
  // Send failure can be passed through result.ErrorMessages View the cause of failure 
}
1

It is also very simple to use


// If you use smtp Service sending mail must be set smtp Service information 
SmtpClient smtp = new SmtpClient
{
  //smtp Server address ( I am here to 126 Mailbox, for example, can be set according to the specific mailbox you use )
  Host = "smtp.126.com",
  UseDefaultCredentials = true,
  DeliveryMethod = SmtpDeliveryMethod.Network,
  // Enter here that you are sending smtp User name and password for the server 
  Credentials = new NetworkCredential(" Mailbox User Name ", " Mailbox password ")
};
// Set the default sending information 
Email.DefaultSender = new SmtpSender(smtp);
var email = Email
  // Sender 
  .From("zhangsan@126.com")
  // Recipient 
  .To("lisi@qq.com")
  // Cc to 
  .CC("admin@126.com")
  // Message header 
  .Subject(" Message header ")
  // Mail content 
  .Body(" Mail content ");
// Judging 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
{
  // Send failure can be passed through result.ErrorMessages View the cause of failure 
}
2

Or use 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 more than these two ways, which are very powerful in terms of convenience and function. Interested students can refer to the GitHub address of RazorLight by themselves, and the explanation is very detailed. I won't discuss the use of RazorLight too much here.

As for the content of the email sent, there is a very important point that needs friendly reminder. 1. Public mailbox operators such as Netease or Tencent may need to manually open SMTP service. For details, please refer to https://www.ofstack.com/diannaojichu/520949. html1. Another important point is that if you use the mailbox of a public mailbox operator, they will have great restrictions on the title and content of the email, and there may be many problems. Moreover, to open Smtp service, you need to send SMS authentication to open it. Fortunately, most companies have their own mail systems, and there may not be so many problems in the actual process of sending mail.

Use in conjunction with dependency injection

In the actual development using. Net Core, dependency injection has become an indispensable development mode. If you are using an Net Core development project, but you are not yet exposed to dependency injection, you need to reflect on yourself first. FluentEmail, as a component that keeps pace with the times, can also be used in combination with dependency injection. In this way, we can configure some default settings at the time of registration. This wave of operations does not require the introduction of an additional package, if you need to use Smtp to introduce FluentEmail. Smtp package, if you need to use Razor template to introduce FluentEmail. Razor package, the function of this part of injection is actually included in FluentEmail. Core package


// If you use smtp Service sending mail must be set smtp Service information 
SmtpClient smtp = new SmtpClient
{
  //smtp Server address ( I am here to 126 Mailbox, for example, can be set according to the specific mailbox you use )
  Host = "smtp.126.com",
  UseDefaultCredentials = true,
  DeliveryMethod = SmtpDeliveryMethod.Network,
  // Enter here that you are sending smtp User name and password for the server 
  Credentials = new NetworkCredential(" Mailbox User Name ", " Mailbox password ")
};
// Set the default sending information 
Email.DefaultSender = new SmtpSender(smtp);
var email = Email
  // Sender 
  .From("zhangsan@126.com")
  // Recipient 
  .To("lisi@qq.com")
  // Cc to 
  .CC("admin@126.com")
  // Message header 
  .Subject(" Message header ")
  // Mail content 
  .Body(" Mail content ");
// Judging 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
{
  // Send failure can be passed through result.ErrorMessages View the cause of failure 
}
4

In the need to send mail directly into the class IFluentEmail, do not panic we use the above Email this class is actually the implementation of IFluentEmail this interface, so the use of the way is completely 1 to


// If you use smtp Service sending mail must be set smtp Service information 
SmtpClient smtp = new SmtpClient
{
  //smtp Server address ( I am here to 126 Mailbox, for example, can be set according to the specific mailbox you use )
  Host = "smtp.126.com",
  UseDefaultCredentials = true,
  DeliveryMethod = SmtpDeliveryMethod.Network,
  // Enter here that you are sending smtp User name and password for the server 
  Credentials = new NetworkCredential(" Mailbox User Name ", " Mailbox password ")
};
// Set the default sending information 
Email.DefaultSender = new SmtpSender(smtp);
var email = Email
  // Sender 
  .From("zhangsan@126.com")
  // Recipient 
  .To("lisi@qq.com")
  // Cc to 
  .CC("admin@126.com")
  // Message header 
  .Subject(" Message header ")
  // Mail content 
  .Body(" Mail content ");
// Judging 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
{
  // Send failure can be passed through result.ErrorMessages View the cause of failure 
}
5

If you need to send Razor view template related content, it is still the familiar recipe and the familiar taste, no different, just omit some of the default configuration we added at the time of registration


// If you use smtp Service sending mail must be set smtp Service information 
SmtpClient smtp = new SmtpClient
{
  //smtp Server address ( I am here to 126 Mailbox, for example, can be set according to the specific mailbox you use )
  Host = "smtp.126.com",
  UseDefaultCredentials = true,
  DeliveryMethod = SmtpDeliveryMethod.Network,
  // Enter here that you are sending smtp User name and password for the server 
  Credentials = new NetworkCredential(" Mailbox User Name ", " Mailbox password ")
};
// Set the default sending information 
Email.DefaultSender = new SmtpSender(smtp);
var email = Email
  // Sender 
  .From("zhangsan@126.com")
  // Recipient 
  .To("lisi@qq.com")
  // Cc to 
  .CC("admin@126.com")
  // Message header 
  .Subject(" Message header ")
  // Mail content 
  .Body(" Mail content ");
// Judging 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
{
  // Send failure can be passed through result.ErrorMessages View the cause of failure 
}
6

Summarize

The basic usage of FluentEmail is introduced here. Personally, I feel that its own functions are very powerful and it is very simple to use. To tell the truth, before I came into contact with FluentEmail, I often saw other languages integrating email components in the garden, which was really powerful. For example, integrating spring-boot-starter-mail in springboot was really convenient. Later, I was very pleased to come into contact with FluentEmail inadvertently. 1. It has powerful functions and ease of use. Secondly, it can be combined with Net Core to further optimize its use. At least in Net and.ES224Core, we also have a very convenient mail sending component. The author of FluentEmail also calls on more developers to understand and participate in the development and practice of FluentEmail, and finally posts its GitHub address https://github.com/lukencode/FluentEmail again


Related articles: