.net6 中实现邮件发送

发布于:2025-04-11 ⋅ 阅读:(34) ⋅ 点赞:(0)

一、开启邮箱服务

        先要开启邮箱的 SMTP 服务,获取授权码,在实现代码发送邮件中充当邮箱密码用。

在邮箱的 设置 > 账号 > POP3/IMAP/SMTP/Exchange/CardDAV/CalDAV服务中,把 SMTP 服务开启,获取授权码。

二、安装库

安装 MailKit 第三方库,直接管理 NuGet 包程序中搜 MailKit 。

三、实现代码

1、配置邮箱:将邮箱信息放置在 appsettings.json 配置文件中。

"EmailAccount": {
    "StmpServer": "smtp.qq.com",
    "MailAccount": "XXXXXXXXX@qq.com",
    "PassWord": "asoptnmyaswegehj"
  }

2、实现代码

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

namespace MySystem.Services
{
    public class SendEmailRepository : ISendEmailRepository
    {
        private readonly string _stmpServer;//smtp服务器地址
        private readonly string _mailAccount;//邮箱账号
        private readonly string _password;//邮箱密码(qq邮箱此处使用授权码,其他邮箱见邮箱规定使用的是邮箱密码还是授权码)
        public SendEmailRepository(IConfiguration configuration)
        {
            _stmpServer = configuration["EmailAccount:StmpServer"];
            _mailAccount = configuration["EmailAccount:MailAccount"];
            _password = configuration["EmailAccount:PassWord"];
        }
        public bool SendEmail(string mailTo, string mailTitle, string mailContent)
        {
            //邮件服务设置
            SmtpClient smtpClient = new SmtpClient();
            smtpClient.DeliveryMethod = SmtpDeliveryMethod.Network;//指定电子邮件发送方式
            smtpClient.Host = _stmpServer;//指定发送方SMTP服务器
            smtpClient.EnableSsl = true;//使用安全加密连接
            smtpClient.UseDefaultCredentials = false;//不和请求一起发送
            smtpClient.Credentials = new NetworkCredential(_mailAccount, _password);//设置发送账号密码

            MailMessage mailMessage = new MailMessage(_mailAccount, mailTo);//实例化邮件信息实体并设置发送方和接收方
            mailMessage.Subject = mailTitle;//设置发送邮件得标题
            mailMessage.Body = mailContent;//设置发送邮件内容
            mailMessage.BodyEncoding = Encoding.UTF8;//设置发送邮件得编码
            mailMessage.IsBodyHtml = false;//设置标题是否为HTML格式
            mailMessage.Priority = MailPriority.Normal;//设置邮件发送优先级

            try
            {
                smtpClient.Send(mailMessage);//发送邮件
                return true;
            }
            catch (SmtpException ex)
            {
                throw ex;
            }
        }
    }
}

这样只需要调用 SendEmailRepository 类的 SendEmail 方法就可以发送邮件了。


好记性不如烂笔头,在学习的路上留下点痕迹。希望能给你带来帮助,期待你的点赞和评论。

若有不足之处,还请斧正。


网站公告

今日签到

点亮在社区的每一天
去签到