C#发送邮件帮助类

using System.Configuration;
using System.Net.Mail;

        #region 发送邮件
/// < summary >
/// 发送邮件
/// </ summary >
/// < param name = "body" > 邮件内容 </ param >
/// < param name = "FilePath" > 附件路径/无附件请注释Attachments </ param >
public static void SendToMail( StringBuilder body, string FilePath)
{
//在配置文件里面配置好参数
string tomail = ConfigurationManager.AppSettings[ "TOMAIL"].ToString(); //收件人邮箱,多个收件人用","隔开
string ccmail = ConfigurationManager.AppSettings[ "CCMAIL"].ToString(); //抄送人邮箱,无抄件人的话注释掉cc
string sendmail = ConfigurationManager.AppSettings[ "SENDMAIL"].ToString(); //发件人邮箱
string sendpwd = ConfigurationManager.AppSettings[ "SENDPWD"].ToString(); //发件人邮箱密码
string fromemail = ConfigurationManager.AppSettings[ "FROMEMAIL"].ToString(); //头部信息中的邮箱信息
string name = ConfigurationManager.AppSettings[ "NAME"].ToString(); //发件人名称
string subject = ConfigurationManager.AppSettings[ "SUBJECT"].ToString(); //邮件主题

MailMessage mmsg = new MailMessage(); //实例化MailMessage
mmsg.To.Add(tomail); //添加收件人邮箱
mmsg.CC.Add(ccmail); //添加抄送人邮箱
mmsg.Attachments.Add( new Attachment(FilePath));
mmsg.From = new MailAddress(fromemail, name, Encoding.UTF8); //添加发件人邮箱、名字、编码
mmsg.Subject = subject; //邮件主题
mmsg.SubjectEncoding = Encoding.UTF8; //邮件标题编码
mmsg.Body = body.ToString(); //邮件内容
mmsg.BodyEncoding = Encoding.UTF8; //邮件内容编码
mmsg.IsBodyHtml = true; //是否是HTML邮件
mmsg.Priority = MailPriority.Normal; //邮件优先级
SmtpClient client = new SmtpClient(); //实例化SmtpClient(邮件传输协议)
client.Credentials = new System. Net. NetworkCredential(sendmail, sendpwd); //发件方邮箱和密码
client.Port = 587; //邮箱使用的端口
client.Host = "smtp.exmail.qq.com";
client.EnableSsl = true; //ssl加密
object userState = mmsg;
try
{
client.Send(mmsg);
Console.WriteLine( "发送成功");
}
catch ( System. Net. Mail. SmtpException ex)
{
Console.WriteLine(ex.Message, "发送邮件出错", ex);
}
}

public static StringBuilder SbBody()
{
StringBuilder sb = new StringBuilder();
sb.AppendLine( "在这里面拼接邮件内容/代码格式为html");
return sb;
}

#endregion

猜你喜欢

转载自blog.csdn.net/qq_28017061/article/details/80829626