.net6 中实现邮件发送

一、开启邮箱服务

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

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

二、安装库

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

三、实现代码

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

复制代码
"EmailAccount": {
    "StmpServer": "smtp.qq.com",
    "MailAccount": "[email protected]",
    "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 方法就可以发送邮件了。


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

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

相关推荐
love530love3 小时前
【笔记】在 MSYS2(MINGW64)中安装 python-maturin 的记录
运维·开发语言·人工智能·windows·笔记·python
阿卡蒂奥4 小时前
C# 结合PaddleOCRSharp搭建Http网络服务
开发语言·http·c#
江沉晚呤时5 小时前
SQL Server 事务详解:概念、特性、隔离级别与实践
java·数据库·oracle·c#·.netcore
泉飒5 小时前
lua注意事项
开发语言·笔记·lua
明月看潮生7 小时前
青少年编程与数学 02-020 C#程序设计基础 14课题、程序调试
开发语言·青少年编程·c#·编程与数学
lulinhao7 小时前
VLAN的作用和原理
网络·笔记·vlan
Gladiator5758 小时前
记录-day002-git
代码规范
moxiaoran57538 小时前
uni-app学习笔记十八--uni-app static目录简介
笔记·学习·uni-app
航Hang*8 小时前
WEBSTORM前端 —— 第3章:移动 Web —— 第4节:移动适配-VM
前端·笔记·edge·less·css3·html5·webstorm
HinsCoder9 小时前
【技能拾遗】——家庭宽带单线复用布线与配置(移动2025版)
运维·网络·笔记·智能路由器·iptv·移动·单线复用