欢迎来到尧图网

客户服务 关于我们

您的位置:首页 > 汽车 > 新车 > .net6 中实现邮件发送

.net6 中实现邮件发送

2025/5/16 6:33:46 来源:https://blog.csdn.net/qq_61709335/article/details/147052167  浏览:    关键词:.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 方法就可以发送邮件了。


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

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

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com

热搜词