节日将至,需要写一个托盘程序,定时发送邮件至客户邮箱
于是架了一个CMail服务器,建立了一个用户post@5liao.cc
开始写程序

static string sendMail(string to, string title, string content)
{
string strHost = "xxx.xxx.xxx.x"; //STMP服务器地址
string strAccount = "post@5liao.cc"; //SMTP服务帐号
string strPwd = "1122333"; //SMTP服务密码
string strFrom = "post@5liao.cc"; //发送方邮件地址
SmtpClient _smtpClient = new SmtpClient();
_smtpClient.DeliveryMethod = SmtpDeliveryMethod.Network;//指定电子邮件发送方式
_smtpClient.Host = strHost; ;//指定SMTP服务器
_smtpClient.Credentials = new System.Net.NetworkCredential(strAccount, strPwd);//用户名和密码
MailMessage _mailMessage = new MailMessage(strFrom, to);
_mailMessage.Subject = title;//主题
_mailMessage.Body = content;//内容
_mailMessage.BodyEncoding = System.Text.Encoding.UTF8;//正文编码
_mailMessage.IsBodyHtml = true;//设置为HTML格式
_mailMessage.Priority = MailPriority.High;//优先级
try
{
_smtpClient.Send(_mailMessage);
return "发送成功";
}
catch (Exception ex)
{
return ex.Message;
}
}
本以为很简单,调用上面方法后,却总是提示“身份认证失败”。
郁闷了,换成搜狐邮箱后发送成功。于是考虑是服务器配置问题。关防火墙,关杀毒软件,关CMail的ESMTP仍然无效(应该是ESMTP的问题)。
网上搜索资料。改用System.Web.Mail后发送成功
(因是winform,需要对System.Web进行引用)

static string sendMail(string to,string title,string content)
{
System.Web.Mail.MailMessage _mailMessage = new System.Web.Mail.MailMessage();
_mailMessage.Body = content;
_mailMessage.From = "post@5liao.cc";
_mailMessage.Subject = title;
_mailMessage.To = to;
_mailMessage.BodyEncoding = System.Text.Encoding.UTF8;
_mailMessage.BodyFormat = MailFormat.Html;
_mailMessage.Fields.Add("http://schemas.microsoft.com/cdo/configuration/smtpauthenticate", 1);
_mailMessage.Fields.Add("http://schemas.microsoft.com/cdo/configuration/sendusername", "post@5liao.cc");
_mailMessage.Fields.Add("http://schemas.microsoft.com/cdo/configuration/sendpassword", "******");
System.Web.Mail.SmtpMail.SmtpServer = "XXx.xxx.xxx.x";
try
{
System.Web.Mail.SmtpMail.Send(_mailMessage);
return "发送成功";
}
catch(Exception ex)
{
return ex.Message;
}
}
虽然提示System.Web.Mail已过时,但发送邮件成功了。可能为邮件服务器设置了需要验证的原因。综合网上资料