最近业务需求需要用到自动推送邮件的,写了个邮件推送类方便调用
此类是静态类,直接调用类方法
此类可以多个接收人和多个抄送人,分别用“;”号隔开即可;
using System;
using System.Net;
using System.Net.Mail;
using System.Text;
public class EmailSender
{
/// <summary>
/// 发送邮件
/// </summary>
/// <param name="fromAddress">发件人地址</param>
/// <param name="toAddress">收件人地址(可多人,用“;”号隔开)</param>
/// <param name="ccAddress">抄送人地址(可多人,用“;”号隔开)</param>
/// <param name="fromName">发件人名称</param>
/// <param name="passWord">发件授权码,非邮箱登陆密码</param>
/// <param name="smtpAddress">smtp服务器地址</param>
/// <param name="mailPort">发件箱端口</param>
/// <param name="subjectTitle">邮件标题</param>
/// <param name="body">邮件内容(支持html格式)</param>
/// <param name="attachment">附件路径</param>
public static bool SendEmail(string fromAddress, string toAddress, string ccAddress, string fromName, string passWord, string smtpAddress, int mailPort, string subjectTitle, string body, string attachment)
{
MailMessage mail = new MailMessage();
//设置收件人地址,可多个收件人,收件人之间用“;”号隔开即可
if (toAddress.Length > 0)
{
string[] toAdds = toAddress.Split(new char[] { ';' });
foreach (string to in toAdds)
{
mail.To.Add(new MailAddress(to));
}
}
//抄送人地址,可多个抄送人,抄送人之间用“;”号隔开即可
if (ccAddress.Length > 0)
{
string[] ccAdds = ccAddress.Split(new char[] { ';' });
foreach (string cc in ccAdds)
{
mail.CC.Add(new MailAddress(cc));
}
}
//设置发件人邮箱及名称
mail.From = new MailAddress(fromAddress, fromName);
mail.Subject = subjectTitle;//邮件标题
mail.SubjectEncoding = Encoding.UTF8; //标题格式为UTF8
mail.Body = body;//邮件内容
mail.BodyEncoding = Encoding.UTF8; //内容格式为UTF8
mail.IsBodyHtml = true;//设置邮件格式为html格式
//如果有附件就执行邮件附件添加,如果没有就不用添加
if (attachment.Length > 0)
{
mail.Attachments.Add(new Attachment(attachment));//添加附件
}
SmtpClient client = new SmtpClient();
//发送邮箱信息
client.Host = smtpAddress; //SMTP服务器地址
client.Port = mailPort; //SMTP端口,QQ邮箱填写587
client.EnableSsl = true; //启用SSL加密 (使用除QQ邮箱之外的最好关闭)
//发件人邮箱账号,授权码
client.Credentials = new System.Net.NetworkCredential(fromAddress, passWord);
try
{
client.Send(mail); //发送邮件
return true;
}
catch (Exception)
{
return false;
}
}
}
标签:string,C#,邮箱,发送,client,mail,new,邮件
From: https://blog.csdn.net/weixin_47361031/article/details/143249086