ASP. NET Core uses MialKit to implement mail sending function
- 2021-11-10 09:22:40
- OfStack
The specific code is as follows:
# Guide pack
First we need to import MailKit NuGet Bag, NuGet The Install Package command is shown in the extension below.
# Reference namespace
using MailKit.Net.Smtp;
using MimeKit;
# Mail sending help class
/// <summary>
/// Send Mail
/// </summary>
/// <param name="Name"> Sender's name </param>
/// <param name="receive"> Receiving mailbox </param>
/// <param name="sender"> Sending mailbox </param>
/// <param name="password"> Mailbox password </param>
/// <param name="host"> Mailbox host </param>
/// <param name="port"> Mailbox port </param>
/// <param name="subject"> Mail Subject </param>
/// <param name="body"> Mail content </param>
/// <returns></returns>
public async Task<bool> SendMailAsync(string Name, string receive, string sender, string password, string host, int port, string subject, string body)
{
try
{
# MimeMessage Representative 1 Object of an e-mail message
var message = new MimeMessage();
# Add Sender Address Name Sender's name sender Sender's mailbox
message.From.Add(new MailboxAddress(Name, sender));
# Add a recipient address
message.To.Add(new MailboxAddress("", receive));
# Set up message subject information
message.Subject = subject;
# Set up message content
var bodyBuilder = new BodyBuilder() { HtmlBody = body };
message.Body = bodyBuilder.ToMessageBody();
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;
// Note: since we don't have an OAuth2 token, disable
// the XOAUTH2 authentication mechanism.
client.AuthenticationMechanisms.Remove("XOAUTH2");
client.CheckCertificateRevocation = false;
//client.SslProtocols = System.Security.Authentication.SslProtocols.Tls12;
client.Connect(host, port, MailKit.Security.SecureSocketOptions.Auto);
// Note: only needed if the SMTP server requires authentication
client.Authenticate(sender, password);
await client.SendAsync(message);
client.Disconnect(true);
return true;
}
}
catch (Exception ex)
{
}
return false;
}
With the help of this simple mail sending class, we can already realize the mail sending function.
# Extension (NuGet Common Command)
1. Install the specified version: install-package < Package name > -version < Version number >
2. Update package: Update-Package < Package name >
3. Reinstall all Nuget packages (the entire solution will be reinstalled)
update-package -reinstall
4. Reinstall all Nuget packages for the specified project
update-package -project < Project name > -reinstall
5. Normal unloading: uninstall-package < Package name >
6. Forced uninstall: Uninstall-Package < Package name > -Force
Summarize