///
/// 发送邮件
///
/// 发件人地址
/// 发件人姓名 (可为空)
/// 密码
/// 邮件服务器地址
///
/// 收件人 (多个电子邮件地址之间必须用逗号字符(「,」)分隔)
/// 抄送人 (多个电子邮件地址之间必须用逗号字符(「,」)分隔)
/// 主题
/// 内容
/// 附件路径
/// 错误信息
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;
}
}
正文完
发表至: C#学习笔记
2019-06-24