需要注意的几点:
1、 MailMessage对象一定要写"from". 估计163的服务器有对from进行验证。
MailMessage mail = new System.Net.Mail.MailMessage("XXXXX@163.com", "XXXXXX@hotmail.com");
2、一定不要设置UseDefaultCredentials
不管是objMailServer.UseDefaultCredentials = true/false, 都不行。 不要写这句就可以。
设置成false, objMailServer.Credentials 会变成null; 设置成true,objMailServer.Credentials里的username和password都会变成空。
完整代码:
代码
/**//// <summary>
/// 功能:发送邮件,返回字符串:“发送成功”否则返回错误代码。
/// 创建:2007-08-23
/// </summary>
/// <param name="MailTo">MailTo为收信人地址</param>
/// <param name="Subject">Subject为标题</param>
/// <param name="Body">Body为信件内容</param>
/// <param name="BodyFormat">BodyFormat为信件内容格式:0为Text,1为Html</param>
/// <param name="Priority">Priority为优先级:0为低,1为中,2为高</param>
/// <param name="Attachments">Attachment为附件,为null则不发送</param>
public static string SendMail(System.Collections.ArrayList MailTo, string Subject, string Body, int BodyFormat, int Priority, string Attachments)
{
string result;
SmtpClient mail = new SmtpClient();
//发送方式
mail.DeliveryMethod = SmtpDeliveryMethod.Network;
//smtp服务器
mail.Host = "smtp.163.com";
//用户名凭证
mail.Credentials = new System.Net.NetworkCredential("mail_user_name", "mail_user_password");
//邮件信息
MailMessage message = new MailMessage();
//发件人
message.From = new MailAddress(mail_user_name@163.com);
//收件人
foreach (object item in MailTo)
{
message.To.Add(item.ToString());
}
//主题
message.Subject = Subject;
//内容
message.Body = Body;
//正文编码
message.BodyEncoding = System.Text.Encoding.UTF8;
//设置为HTML格式
message.IsBodyHtml = true;
//优先级
message.Priority = MailPriority.High;
try
{
mail.Send(message);
result = "发送成功";
return result;
}
catch (Exception e)
{
result = e.ToString();
}
return result;
}
/// 功能:发送邮件,返回字符串:“发送成功”否则返回错误代码。
/// 创建:2007-08-23
/// </summary>
/// <param name="MailTo">MailTo为收信人地址</param>
/// <param name="Subject">Subject为标题</param>
/// <param name="Body">Body为信件内容</param>
/// <param name="BodyFormat">BodyFormat为信件内容格式:0为Text,1为Html</param>
/// <param name="Priority">Priority为优先级:0为低,1为中,2为高</param>
/// <param name="Attachments">Attachment为附件,为null则不发送</param>
public static string SendMail(System.Collections.ArrayList MailTo, string Subject, string Body, int BodyFormat, int Priority, string Attachments)
{
string result;
SmtpClient mail = new SmtpClient();
//发送方式
mail.DeliveryMethod = SmtpDeliveryMethod.Network;
//smtp服务器
mail.Host = "smtp.163.com";
//用户名凭证
mail.Credentials = new System.Net.NetworkCredential("mail_user_name", "mail_user_password");
//邮件信息
MailMessage message = new MailMessage();
//发件人
message.From = new MailAddress(mail_user_name@163.com);
//收件人
foreach (object item in MailTo)
{
message.To.Add(item.ToString());
}
//主题
message.Subject = Subject;
//内容
message.Body = Body;
//正文编码
message.BodyEncoding = System.Text.Encoding.UTF8;
//设置为HTML格式
message.IsBodyHtml = true;
//优先级
message.Priority = MailPriority.High;
try
{
mail.Send(message);
result = "发送成功";
return result;
}
catch (Exception e)
{
result = e.ToString();
}
return result;
}