C#发送邮件异常:根据验证过程,远程证书无效,何解???

/// <summary>
/// 发送邮件
/// </summary>
/// <param name="mailSubjct">邮件主题</param>
/// <param name="mailBody">邮件正文</param>
/// <param name="mailAddress">收件人</param>
/// <param name="mailFrom">发件人</param>
/// <param name="mailFromName">发件人用户名</param>
/// <param name="password">发件密码</param>
/// <param name="mailHost">SMTP服务器地址 </param>
/// <param name="mailPort">SMTP服务器端口</param>
/// <param name="flag">输出参数bool</param>
/// <returns></returns>
public static string sendMail(string mailSubjct, string mailBody, List<string> mailAddress, string mailFrom, string mailFromName, string password, string mailHost, int mailPort, out bool flag)
{
flag = true;
string str = string.Empty;
MailMessage msg = new MailMessage();

//msg.To.Add("YYY@qq.com");//收件人地址
Regex regex = new Regex(@"\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*");
for (int i = 0; i < mailAddress.Count; i++)
{
if (regex.IsMatch(mailAddress[i]))
{
msg.To.Add(mailAddress[i]);
}
}
//msg.CC.Add("XXX@qq.com");//抄送人地址

msg.From = new MailAddress(mailFrom, mailFromName);//发件人邮箱,名称
msg.Subject = mailSubjct;//邮件标题
msg.SubjectEncoding = Encoding.UTF8;//标题格式为UTF8
msg.Body = mailBody;//邮件内容
msg.BodyEncoding = Encoding.UTF8;//内容格式为UTF8
msg.IsBodyHtml = true;//是否HTML形式发送

SmtpClient client = new SmtpClient();
client.Host = mailHost;// "smtp.qq.com";//SMTP服务器地址
if (mailPort != 0)
client.Port = mailPort;//SMTP端口,QQ邮箱填写587
client.EnableSsl = true;//启用SSL加密
client.Credentials = new NetworkCredential(mailFrom, password);//发件人邮箱账号,密码
client.Timeout = 10000; //超时时间
try
{
//qq邮箱和163邮箱都可以正常发送,使用公司的邮箱和smtp时需加上此段,以免出现“根据验证过程,远程证书无效”异常
ServicePointManager.ServerCertificateValidationCallback =
delegate (Object obj, X509Certificate certificate, X509Chain chain, SslPolicyErrors errors) { return true; };

client.Send(msg);//发送邮件
}
catch (Exception exception)
{
str = exception.Message;
flag = false;
}
return str;
}

posted @ 2017-03-29 18:03  HI_Hub_MI  阅读(657)  评论(0编辑  收藏  举报