查阅资料得知,.net 的自带组件System.Net.Mail发送邮件支持Explicit SSL但是不支持Implicit SSL,国内大部门邮件服务器都是Implicit SSL,所以无法通过465端口发邮件
有人说了,那干嘛要用呢,我用25不好好的么,为甚恶魔不用25呢?
这个问题问得好,很多云服务器像阿里、腾讯购买的新机都是把25端口封禁的,想要用25端口需要手动申请解封,据阿里工作客服所说,审核通过率感人
那么今天就记录一下如何使用465端口成功发邮件
需要NuGet两个包MimeKit、MailKit
using MailKit.Net.Smtp;
using MimeKit;
using System;
using System.IO;
public int SendVcodeByEmail(string email)
{
Regex emailRegex = new Regex(@"^[A-Za-z\d]+([-_.][A-Za-z\d]+)*@([A-Za-z\d]+[-.]){1,2}[A-Za-z\d]{2,5}$");
if (!emailRegex.IsMatch(email)) throw new MyException(_localizer["邮箱格式非法"]); //Illegal mailbox format
int.TryParse(config[0], out var vLength);
var vCode = CommonCode.GenerateRandomText(vLength);//验证码
var message = new MimeMessage();
message.From.Add(new MailboxAddress("发送人姓名","发件人邮箱"));
message.To.Add(new MailboxAddress("收件人姓名", "收件人"));
message.Subject ="注册邮箱验证"; //邮件标题
var builder = new BodyBuilder
{
HtmlBody = "测试正文</br>正文换行"//正文
};
message.Body = builder.ToMessageBody();
using (var client = new MailKit.Net.Smtp.SmtpClient())
{
client.ServerCertificateValidationCallback = (s, c, h, e) => true;
var mSendMail = "发件人邮箱";
var mSendPwd = "发件人邮箱授权密码";//不是邮箱密码
client.Connect("smtp.qiye.163.com",465, true);//网易、QQ支持 25(未加密),465和587(SSL加密)
client.Authenticate(mSendMail, mSendPwd);
try
{
client.Send(message);//发送邮件
client.Disconnect(true);
return 1;// "SUCCESS";
}
catch (SmtpCommandException ex)
{
throw new MyException(ex.Message);
}
catch (Exception ex)
{
throw new MyException(ex.Message);
}
}
}