1.appsettings.json 写入需要用到的基本信息
2.发送消息核心方法
public class SendHelperl { private readonly IConfiguration _configuration; public SendHelperl(IConfiguration configuration) { _configuration = configuration; } /// <summary> /// 发送邮件方法 /// </summary> /// <param name="mailTo">接收人邮件</param> /// <param name="mailTitle">发送邮件标题</param> /// <param name="mailContent">发送邮件内容</param> /// <returns></returns> public bool SendEmail(string mailTo, string mailTitle, string mailContent) { MailSetting mailSetting = new MailSetting(); _configuration.Bind("MailSetting", mailSetting); //设置发送方邮件信息,例如:qq邮箱 string stmpServer = mailSetting.StmpServer;//smtp服务器地址 string mailAccount = mailSetting.MailAccount;//邮箱账号 string pwd = mailSetting.Code;//邮箱密码(qq邮箱此处使用授权码,其他邮箱见邮箱规定使用的是邮箱密码还是授权码) //邮件服务设置 SmtpClient smtpClient = new SmtpClient(); smtpClient.DeliveryMethod = SmtpDeliveryMethod.Network;//指定电子邮件发送方式 smtpClient.Host = stmpServer;//指定发送方SMTP服务器 smtpClient.EnableSsl = true;//使用安全加密连接 smtpClient.UseDefaultCredentials = false;//不和请求一起发送 smtpClient.Credentials = new NetworkCredential(mailAccount, pwd);//设置发送账号密码 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; } } } public class MailSetting { public string Code { get; set; } public string? PassWord { get; set; } public string MailAccount { get; set; } public string StmpServer { get; set; } }
3.常见问题
Bad sequence of commands. The server response was: Error: need EHLO and AUTH first !
首先确定你的邮箱是否有授权,appsettings.json里面的授权码就是从这里来的
登录你的QQ邮箱,进入设置里面找到账户,开启红线处的服务,按照操作一步步往下,最后会生成一个授权码,将授权码复制到 appsettings.json的 code中
设置完成之后若还是报一样的错误,查看代码 smtpClient.UseDefaultCredentials 需要设置成false
标签:qq,string,smtpClient,发送,邮箱,Net6,public,邮件 From: https://www.cnblogs.com/SmallChen/p/17461314.html