透過 MAIL Server 寄送信件

透過 MAIL Server 寄送信件

using System.Net;
using System.Net.Mail;

public static class Mail
{
    // 寄信相關常數
    private const string SmtpServ = "";
    private const int SmtpPort = 25;
    private const string MailFrom = "";
    private const string SmtpUser = "";
    private const string SmtpPwd = "";

    /// <summary>
    /// 透過 ERP MAIL 寄送信件
    /// </summary>
    /// <param name="mailto">寄件人清單</param>
    /// <param name="subject">信件標題</param>
    /// <param name="body">內文(可HTML)</param>
    /// <param name="attachfile">附件</param>
    private static void SendMail(MailAddress[] mailto, string subject, string body, string attachfile = "")
    {
        using (MailMessage mail = new MailMessage())
        {
            mail.From = new MailAddress(MailFrom);

            foreach (MailAddress lv_MailTo in mailto)
            {
                mail.To.Add(lv_MailTo);
            }

            mail.Subject = subject;
            mail.Body = body;
            mail.IsBodyHtml = true;

            //夾帶檔案
            if (attachfile.Trim() != string.Empty)
                mail.Attachments.Add(new Attachment(attachfile));

            using (SmtpClient smtp = new SmtpClient(SmtpServ, SmtpPort))
            {
                smtp.Credentials = new NetworkCredential(SmtpUser, SmtpPwd);
                smtp.Send(mail);
            }
        }
    }
}