2016年5月14日 星期六

[SMTP] SMTP client 發送Email

 SMTP   Email   C#   ASP.NET 


Introduction


在公司如果有架設SMTP(外送郵件伺服器),使用 System.Net.Mail.SmtpClient組件以程式碼發送通知Email將變成是很簡單的事情; 本範例將實作一段在ASP.NET MVC5利用WebConfigSMTP設定來發送Email的功能。

Implement


Web config

<configuration
<system.net>
    <mailSettings>
      <smtp from="mail@xxxx.com">
        <network defaultCredentials="false" host="smtp.xxxx.com" password="xxxx" port="25" userName="mail@xxxx.com"/>
      </smtp>
    </mailSettings>
  </system.net>
</configuration>


注意 defaultCredentials參數的設定方式: (MSDN)

True : 以預設登入使用者做認證。
False : 指定認證的帳號/密碼。




如果不使用WebConfig,也可以直接設定在代碼中實現配置。

SmtpClient mySMTP = new SmtpClient();

//如果smtpHost是指向localhost的話,則DeliveryMethodPickupDirectoryFromIis
#region SmtpClient (localhost)
//mySMTP.Host = "localhost";
//mySMTP.DeliveryMethod = SmtpDeliveryMethod.PickupDirectoryFromIis;
//mySMTP.PickupDirectoryLocation = @"C:\Inetpub\mailroot\Pickup";
#endregion

//如果smtpHost是指向遠端主機的話,則DeliveryMethodNetwork,可增加認證資料
#region SmtpClient (network)
mySMTP.Host = "smtp.xxxx.com";
var mailCredentialAccount = @"domain\AD_Account";
var mailCredentialPassword = @"XXXXXX";

mySMTP.DeliveryMethod = SmtpDeliveryMethod.Network;
mySMTP.Credentials = new System.Net.NetworkCredential(mailCredentialAccount, mailCredentialPassword);
#endregion







Back-end

Controller : Post back action

[HttpPost]
public ActionResult Index(VmEmailMsg viewModel)
{

            #region 建立MailMessage物件
            MailMessage msg = new MailMessage();
            msg.To.Add(viewModel.ToMailAddr);
            msg.From = new MailAddress(
                viewModel.FromMailAddr, viewModel.FromName, System.Text.Encoding.UTF8);
            msg.Subject = viewModel.Subject;
            msg.SubjectEncoding = Encoding.UTF8;
            msg.Body = viewModel.MailBody;
            msg.BodyEncoding = Encoding.UTF8;
            msg.IsBodyHtml = true;
            msg.Priority = MailPriority.Low; //Mail priority
            #endregion

            #region SmtpClient (network)
            SmtpClient smtpClient = new SmtpClient();

            //Setup the NetworkCredential fot SMTP
            //smtpClient.Host = this._smtpHost;
            //var mailCredentialAccount = this._account;
            //var mailCredentialPassword = this._pwd;
            //smtpClient.Credentials = new System.Net.NetworkCredential(mailCredentialAccount, mailCredentialPassword);

            smtpClient.DeliveryMethod = SmtpDeliveryMethod.Network;
            smtpClient.Send(msg);
            #endregion

            return View(viewModel);
}



Test


l   Input :





l   收到的Email :

 


Reference



沒有留言:

張貼留言