您的位置:首页 > 编程语言 > C#

C# .NET 发送邮件 代码

2015-09-28 16:01 489 查看
using Common.Log;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Mail;
using System.Net.Security;
using System.Text;
using System.Threading.Tasks;
using System.Security.Cryptography.X509Certificates;

namespace Common.Tools
{
public class SendEmail
{
/// <summary>
/// 发送邮件
/// </summary>
/// <param name="MessageTo">收件人</param>
/// <param name="MessageSubject">邮件主题</param>
/// <param name="MessageBody">邮件正文</param>
/// <returns></returns>
public static bool Send(string MessageTo, string MessageSubject, string MessageBody)
{
//此处注册只为防止个别邮箱证书验证失败问题
ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(ValidateServerCertificate);
MailAddress MessageFrom = new MailAddress("***@qq.com");
MailMessage message = new MailMessage();
message.From = MessageFrom;
message.To.Add(MessageTo);              //收件人邮箱地址可以是多个以实现群发
message.Subject = MessageSubject;
message.Body = MessageBody;
message.IsBodyHtml = true;              //是否为html格式
message.Priority = MailPriority.High;  //发送邮件的优先等级

SmtpClient sc = new SmtpClient();
sc.Host = "smtp.qq.com";              //指定发送邮件的服务器地址或IP
sc.Port = 587; //一个是143,一个25                  //sc.Port = 587;                          //指定发送邮件端口
sc.UseDefaultCredentials = true;
sc.EnableSsl = true;
sc.Credentials = new System.Net.NetworkCredential("***@qq.com", "密码"); //指定登录服务器的用户名和密码
try
{
sc.Send(message);      //发送邮件
}
catch (Exception ex)
{
WriteLog.WriteErrorLog(ex.ToString());
return false;
}
return true;
}

private static bool ValidateServerCertificate(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors)
{
return true;
//throw new NotImplementedException();
}
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: