整理的两种邮件发送方式,内容来自网络。
1.普通发送
/// <summary>
/// 发送邮件
/// </summary>
/// <param name="userEmail">发件人邮箱</param>
/// <param name="userPswd">邮箱帐号密码</param>
/// <param name="toEmail">收件人邮箱</param>
/// <param name="mailServer">邮件服务器</param>
/// <param name="subject">邮件标题</param>
/// <param name="mailBody">邮件内容</param>
/// <param name="attachFiles">邮件附件</param>
public static void SendEmail(string userEmail,string userPswd,string toEmail,string mailServer,string subject,string mailBody,string[] attachFiles)
{
//邮箱帐号的登录名
string username = userEmail.Substring(0, userEmail.IndexOf('@'));
//邮件发送者
MailAddress from = new MailAddress(userEmail);
//邮件接收者
MailAddress to = new MailAddress(toEmail);
MailMessage mailobj = new MailMessage(from, to);
// 添加发送和抄送
// mailobj.To.Add("");
// mailobj.CC.Add("");
//邮件标题
mailobj.Subject = subject;
//邮件内容
mailobj.Body = mailBody;
foreach (string attach in attachFiles)
{
mailobj.Attachments.Add(new Attachment(attach));
}
//邮件不是html格式
mailobj.IsBodyHtml = false;
//邮件编码格式
mailobj.BodyEncoding = System.Text.Encoding.GetEncoding("GB2312");
//邮件优先级
mailobj.Priority = MailPriority.High;
//Initializes a new instance of the System.Net.Mail.SmtpClient class
//that sends e-mail by using the specified SMTP server.
SmtpClient smtp = new SmtpClient(mailServer,587);
smtp.EnableSsl = true;
//或者用:
//SmtpClient smtp = new SmtpClient();
//smtp.Host = mailServer;
//不使用默认凭据访问服务器
smtp.UseDefaultCredentials = true;
smtp.Credentials = new NetworkCredential(username, userPswd);
//使用network发送到smtp服务器
smtp.DeliveryMethod = SmtpDeliveryMethod.Network;
try
{
//开始发送邮件
smtp.Send(mailobj);
// object userState = mailobj;
//smtp.SendAsync(mailobj, userState);
}
catch (Exception e)
{
Console.WriteLine(e.Message);
Console.WriteLine(e.StackTrace);
}
}
2.ssl发送(公司邮箱)
private static bool SendMail(string toMail, string Body)
{
ServicePointManager.ServerCertificateValidationCallback += (se, cert, chain, sslerror) =>
{
return true;
};
// Using Ssl3 rather than Tls here makes no difference
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls;
var client = new SmtpClient
{
Timeout = 10000,
DeliveryMethod = SmtpDeliveryMethod.Network,
EnableSsl = true,
UseDefaultCredentials = false,
Host = "mail.XXX.com",
//Port = 587
Port = 25
};
//client.ClientCertificates.Add();
client.Credentials = new System.Net.NetworkCredential("xxxx@xxxxx.com", "Tl123456");
System.Net.Mail.MailMessage msg = new System.Net.Mail.MailMessage();
msg.To.Add(toMail);
msg.From = new MailAddress("xxxx@xxxxx.com", "noreply", System.Text.Encoding.UTF8);
/* 上面3个参数分别是发件人地址(可以随便写),发件人姓名,编码*/
msg.Subject = "来自OA的消息提醒";//邮件标题
msg.SubjectEncoding = System.Text.Encoding.UTF8;//邮件标题编码
msg.Body = Body;//邮件内容
msg.BodyEncoding = System.Text.Encoding.UTF8;//邮件内容编码
msg.IsBodyHtml = false;//是否是HTML邮件
msg.Priority = MailPriority.High;//邮件优先级
try
{
client.Send(msg);
return true;
}
catch (Exception ex)
{
return false;
}
}