码迷,mamicode.com
首页 > 其他好文 > 详细

发送邮件功能

时间:2019-05-05 20:37:16      阅读:174      评论:0      收藏:0      [点我收藏+]

标签:public   try   list   错误   word   out   sum   for   pcl   

/// <summary>
/// 发送邮件功能,发送邮箱需要开通stmp服务
/// </summary>
/// <param name="userEmailAddress">发件人地址</param>
/// <param name="userName">发件人姓名(可为空)</param>
/// <param name="password">密码</param>
/// <param name="host">邮件服务器地址</param>
/// <param name="port">端口</param>
/// <param name="sendToList">收件人(多个电子邮件地址之间必须用逗号字符(“,”)分隔)</param>
/// <param name="sendCCList">抄送人(多个电子邮件地址之间必须用逗号字符(“,”)分隔)</param>
/// <param name="subject">主题</param>
/// <param name="body">内容</param>
/// <param name="attachmentsPath">附件路径</param>
/// <param name="errorMessage">错误信息</param>
public static bool SendMessage(string userEmailAddress, string userName, string password, string host, int port,
string[] sendToList, string[] sendCCList, string subject, string body, string[] attachmentsPath, out string errorMessage)
{
errorMessage = string.Empty;
SmtpClient client = new SmtpClient();
client.Credentials = new System.Net.NetworkCredential(userEmailAddress, password);//用户名、密码
client.DeliveryMethod = SmtpDeliveryMethod.Network;//指定电子邮件发送方式
client.Host = host;//邮件服务器
client.Port = port;//端口号 非SSL方式,默认端口号为:25
client.UseDefaultCredentials = true;

MailMessage msg = new MailMessage();
//加发件人
foreach (string send in sendToList)
{
msg.To.Add(send);
}
//加抄送
foreach (string cc in sendCCList)
{
msg.To.Add(cc);
}

//在有附件的情况下添加附件
if (attachmentsPath != null && attachmentsPath.Length > 0)
{
foreach (string path in attachmentsPath)
{
var attachFile = new Attachment(path);
msg.Attachments.Add(attachFile);
}
}
msg.From = new MailAddress(userEmailAddress, userName);//发件人地址
msg.Subject = subject;//邮件标题
msg.Body = body;//邮件内容
msg.BodyEncoding = System.Text.Encoding.UTF8;//邮件内容编码
msg.IsBodyHtml = true;//是否是HTML邮件
msg.Priority = MailPriority.High;//邮件优先级

try
{
client.Send(msg);
return true;
}
catch (System.Net.Mail.SmtpException ex)
{
errorMessage = ex.Message;
return false;
}
}

发送邮件功能

标签:public   try   list   错误   word   out   sum   for   pcl   

原文地址:https://www.cnblogs.com/redfull/p/10816029.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!