.net6 中实现邮件发送

一、开启邮箱服务

先要开启邮箱的 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 方法就可以发送邮件了。


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

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

相关推荐
码哥字节5 小时前
为什么 Claude Code 读你的代码库,光靠 embedding 根本不够?
claude·代码规范
雨落倾城夏未凉2 天前
第四章c#方法-参数数组和可选参数(16)
后端·c#
kisshyshy2 天前
从递归到迭代,一文吃透二叉树的核心知识与 JavaScript 实现
javascript·算法·代码规范
唐青枫3 天前
线程不是越多越快:C#.NET Thread 生命周期、同步与后台工作线程实战
c#·.net
唐青枫4 天前
别只会反射:C#.NET Emit 动态生成代码实战详解
c#·.net
Caco_D4 天前
一行代码抓遍全网 20 个热榜!Aneiang.Pa 4.0 发布 — 极简 .NET 爬虫库
爬虫·.net
咕白m6254 天前
.NET 环境下 Word 超链接批量提取方案
c#·.net
用户91721561902114 天前
C# 通信协议增量解析:用状态机处理半包和粘包
c#
小码编匠5 天前
C# 工控上位机必备:数据转换工具类与十个核心模块
后端·c#·.net