使用System.Net.Mail发送邮件

时间:2023-01-18 15:40:06
引用命名空间:
using System.Net.Mail;
/// <summary>
/// 发送HTML邮件,有抄送和密送
/// 需要在Web.config文件中的system.net下的mailSettings节点进行配置
/// </summary>
/// <param name="mailto">收件人地址</param>
/// <param name="mailcc">抄送地址</param>
/// <param name="mailbcc">密送地址</param>
/// <param name="mailsubject">邮件主题</param>
/// <param name="mailbody">邮件正文</param>
public static void SendMail(string mailto, string mailcc, string mailbcc, string mailsubject, string mailbody)
{
    MailMessage mMessage = new MailMessage();
    MailAddress mTo = new MailAddress(mailto);
    if (mailcc != "") { MailAddress mCC = new MailAddress(mailcc); mMessage.CC.Add(mCC); }
    if (mailbcc != "") { MailAddress mBCC = new MailAddress(mailbcc); mMessage.Bcc.Add(mBCC); }
    mMessage.To.Add(mTo);
    mMessage.Subject = mailsubject;
    //正文和主题的字符编码都设置为UTF8
    mMessage.SubjectEncoding = System.Text.Encoding.UTF8;
    mMessage.BodyEncoding = System.Text.Encoding.UTF8;
    mMessage.Body = mailbody;
    //正文支持html
    mMessage.IsBodyHtml = true;
    SmtpClient client = new SmtpClient();
    client.Send(mMessage);
}

调用:
SendMail("11111111@qq.com", "", "", "testdata", "<h1>hello</h1>");