Asp.net core .NET6 发送邮件

 1、Nuget安装Mailkit

2、appsettings.json 添加邮箱配置信息

"EmailInfo": {
    "SmtpServer": "smtphz.qiye.163.com",
    "Port": 465,
    "Username": "你的邮箱账号",
    "Password": "你的邮箱密码"
  }

3、添加EmailInfoConst.cs

 /// 
    /// 邮箱信息
    /// 
    public class EmailInfoConst
    {
        /// 
        /// SMTP服务器地址
        /// 
        public string SmtpServer { get; set; }
        /// 
        /// 端口
        /// 
        public int Port { get; set; }
        /// 
        /// 用户名
        /// 
        public string Username { get; set; }
        /// 
        /// 密码
        /// 
        public string Password { get; set; }
    }

4、Program.cs 注入邮箱配置信息

builder.Services.AddSingleton(builder.Configuration.GetSection("EmailInfo").Get());

5、添加EmailHelper.cs 帮助类

/// 
    /// 发送邮箱
    /// 
    [Serializable]
    public static class EmailHelper
    {
        public static string SendEmail(EmailInfoConst emailInfo, string title, string receiveNmae, string receiveEmail, TextPart body)
        {
            try
            {
                MimeMessage message = new MimeMessage();
                //发件人
                message.From.Add(new MailboxAddress("测试发送用户", emailInfo.Username));
                //收件人
                message.To.Add(new MailboxAddress(receiveNmae, receiveEmail));
                //标题
                message.Subject = title;
                生成一个支持Html的TextPart
                //TextPart body = new TextPart(TextFormat.Html)
                //{
                //    Text = "

测试内容

" //}; //创建Multipart添加附件 Multipart multipart = new Multipart("mixed"); multipart.Add(body); //正文 message.Body = multipart; using (SmtpClient client = new SmtpClient()) { //Smtp服务器 client.Connect(emailInfo.SmtpServer, emailInfo.Port, true); if (client.IsConnected) { //登录 client.Authenticate(emailInfo.Username, emailInfo.Password); //发送 string result = client.Send(message); } //断开 client.Disconnect(true); return "发送邮件成功"; } } catch (Exception ex) { return "发送失败"; } } }

5、使用

1.构造函数注入EmailInfoConst 

private readonly ILogger _logger;
        private EmailInfoConst _emailInfo;
        public HomeController(ILogger logger, EmailInfoConst emailInfo)
        {
            _logger = logger;
            _emailInfo = emailInfo;
        }

2.调用SendEmail函数

//生成一个支持Html的TextPart
TextPart body = new TextPart(TextFormat.Html)
        {
            Text = "

测试邮件

" }; body.Text += $"

请勿回复

"; string sendResult = EmailHelper.SendEmail(_emailInfo, "邮箱测试", "接收人", "接收邮箱", body);

参考1:.net core之邮件发送 - 掘金

参考2:Asp.net core 发送邮件_眸笑丶的博客-CSDN博客_.net core 发邮件

你可能感兴趣的:(.NET,CORE,.net6,数据库)