C# 通过SMTP协议发送邮件
₯最近需要做个信息推送功能,需要发送信息到Outlook邮箱,在这做个记录。
- 邮件参数类MailParams
class MailParams
{
/// <summary>
/// fromName:发件人
/// displayName:发件人显示名称
/// subject:标题
/// bodyContent:内容
/// ec:字符编码
/// isHtml:邮件正文是否为Html
/// mp:邮件优先级
/// sendToList:收件人列表
/// ccList:抄送人列表
/// atamList:附件路径列表
/// </summary>
private string fromName;
private string displayName;
private string subject;
private string bodyContent;
private Encoding ec;
private bool isHtml;
private MailPriority mp;
private string[] sendToList;
private string[] ccList;
private string[] atamList;
public MailParams(string fromName, string displayName, string subject, string bodyContent, Encoding ec, bool isHtml, MailPriority mp, string[] sendToList, string[] ccList, string[] atamList)
{
this.fromName = fromName;
this.displayName = displayName;
this.subject = subject;
this.bodyContent = bodyContent;
this.ec = ec;
this.isHtml = isHtml;
this.mp = mp;
this.sendToList = sendToList;
this.ccList = ccList;
this.atamList = atamList;
}
public string GetFromName() { return fromName; }
public string GetDisplayName() { return displayName; }
public string GetSubject() { return subject; }
public string GetBodyContent() { return bodyContent; }
public Encoding GetEC() { return ec; }
public bool GetIsHtml() { return isHtml; }
public MailPriority GetMP() { return mp; }
public string[] GetSendToList() { return sendToList; }
public string[] GetCCList() { return ccList; }
public string[] GetAtamList() { return atamList; }
}
- 邮件发送方法
public static void SendMessage(MailParams mps)
{
SmtpClient client = new SmtpClient();
client.DeliveryMethod = SmtpDeliveryMethod.Network;
client.Host = 【SMTP服务器地址】; //公司提供的地址不需要账号用户名和密码
client.Port = 25;
client.UseDefaultCredentials = true;
MailMessage msg = new MailMessage();
if (mps.GetSendToList().Length > 0)
msg.To.Add(mps.GetSendToList().Aggregate((s, s1) => s + "," + s1));
else
msg.To.Clear();
if (mps.GetCCList().Length > 0)
msg.CC.Add(mps.GetCCList().Aggregate((s, s1) => s + "," + s1));
else
msg.CC.Clear();
if (mps.GetAtamList().Length > 0)
{
Attachment[] atams=Array.ConvertAll(mps.GetAtamList().Cast<string>().ToArray(), r => new Attachment(r));
foreach (Attachment atm in atams)
msg.Attachments.Add(atm);
}
else
msg.Attachments.Clear();
msg.From = new MailAddress(mps.GetFromName(), mps.GetDisplayName());
msg.Subject = mps.GetSubject();
msg.Body = mps.GetBodyContent();
msg.BodyEncoding = mps.GetEC();
msg.IsBodyHtml = mps.GetIsHtml();
msg.Priority = mps.GetMP();
try{
client.Send(msg);
}
catch (SmtpException ex){
MessageBox.Show(ex.Message);
}
}
- 调用方法
SendMessage(new MailParams(【自定义邮箱地址】,
【自定义邮箱名称】,
【邮件标题】,
【邮件内容】,
Encoding.UTF8,
true,MailPriority.High,
new string[] {【收件邮箱1,收件邮箱2...】},
new string[] {【抄送邮箱1,抄送邮箱2...】},
new string[] {【附件路径1,附件路径2...】}
);