分享一点 .NetCore 后端 SMTP 邮件发送的业务代码

287 阅读1分钟

参考文章:smtpclient is obsolete the new way to send emails from your net app

https://jonathancrozier.com/blog/smtpclient-is-obsolete-the-new-way-to-send-emails-from-your-net-app

We don't recommend that you use the SmtpClient class for new development because SmtpClient doesn't support many modern protocols. Use MailKit or other libraries instead. For more information, see SmtpClient shouldn't be used on GitHub.

github.com/dotnet/plat…

如下这种写法已经淘汰过时,不过仍有学习意义

using System.Net;
using System.Net.Mail;

using static Adnc.Usr.WebApi.Controllers.MailNotificationControllerHelper;

namespace Adnc.Usr.WebApi.Controllers;

[Route("usr/[controller]")]
[ApiController]
public class MailNotificationController : Microsoft.AspNetCore.Mvc.ControllerBase
{
    private Microsoft.Extensions.Logging.ILogger<MailNotificationController> _logger;

    public MailNotificationController(Microsoft.Extensions.Logging.ILogger<MailNotificationController> logger)
    {
        _logger = logger;
    }

    private static readonly string DEFAULT_SMTP_HOST = "smtp.163.com";

    private static readonly int DEFAULT_SMTP_PORT = 25;

    private static readonly string _masterMailAddr = "填你的网易邮箱地址@163.com";

    private static readonly string _masterMaillDisplayName = "Email待办事项提醒程序";

    private static MailMessage BuildMailMsg(string mailSubjectText, string mailBodyText)
    {
        var msg = new MailMessage()
        {
            From = new MailAddress(_masterMailAddr, _masterMaillDisplayName),
            Subject = mailSubjectText,
            SubjectEncoding = System.Text.Encoding.UTF8,
            Body = mailBodyText,
            BodyEncoding = System.Text.Encoding.UTF8,
            IsBodyHtml = false,
            Priority = MailPriority.Normal,
        };
        IEnumerable<MailAddress> receiverMailAddressList = new List<MailAddress>
        {
            new MailAddress("填收件人地址@qq.com", "研发部刘某"),
        };
        foreach (var receiver in receiverMailAddressList)
        {
            msg.To.Add(receiver);
        }
        return msg;
    }

    [HttpPost]
    [AllowAnonymous]
    public async Task<ActionResult<string>> Send(CancellationToken cancellationToken)
    {
        string mailSubject = $"提醒:张三提交了1个新文件给您,请及时审批……";
        string mailBody =
            "详细信息如下:\n\r" +
            "1. Title 文件标题=某某产品测试报告;\n\r" +
            "2. Submitter 文件提交人=研发部张三;\n\r" +
            $"3. Date 文件提交日期 = {DateTime.Now:yyyy年MM月dd日 HH:mm};\n\r";

        MailMessage mailMsg = BuildMailMsg(mailSubject, mailBody);
        string accessToken = "网易设置的Pop3/SMTP邮箱客户端令牌";
        var config = new SmtpConfiguration(
            accessToken,
            DEFAULT_SMTP_HOST,
            DEFAULT_SMTP_PORT,
            true
            );
        var client = new SmtpClient
        {
            Host = config.SmtpHost,
            Port = config.SmtpPort,
            EnableSsl = config.EnableSsl,
            Credentials = new NetworkCredential("FileSystemStart", config.SmtpAccessToken)
        };
        try
        {
            await client.SendMailAsync(mailMsg, cancellationToken);
        }
        catch (SmtpException smtpErr)
        {
            string errMsg = $"Failed to send mail: {smtpErr.Message}";
            if (smtpErr.InnerException is not null)
            {
                errMsg += $": {smtpErr.InnerException.Message}";
            }
            _logger.LogError(errMsg);
            return Ok(errMsg);
        }
        catch (Exception err)
        {
            _logger.LogError(err.Message);
        }

        return Ok("Email sent successfully!");
    }
}

public record SmtpConfiguration(
    string SmtpAccessToken,
    string SmtpHost,
    int SmtpPort = 25,
    bool EnableSsl = true
);

public static class MailNotificationControllerHelper
{
}

推荐MailKit方式发送Email邮件

// MailKit方式发送Email邮件
using (SmtpClient smtpClient = new SmtpClient())
{
    smtpClient.Connect(_notificationMetadata.SmtpServer, _notificationMetadata.Port, true);
    smtpClient.Authenticate(_notificationMetadata.UserName ,_notificationMetadata.Password);
    smtpClient.Send(mimeMessage);
    smtpClient.Disconnect(true);
}