[C#] 使用Gmail發送信件

使用Gmail發送信件 
using System;
using System.Collections.Generic;

public void SendMail(string Subject, string Body, IEnumerable ToUser)
{
    string account = "XXX@gmail.com";//登入Mail Server的帳號
    string password = "*******";//登入Mail Server的密碼
    string from = "XXX@gmail.com";//實際發送信件的Mail地址
    string host = "smtp.gmail.com";//發Mail的Server位置
    string port = "587";//發Mail的Server位置使用的Port
    bool enableSsl = true;//是否啟用SSL憑證

    System.Net.Mail.MailMessage MyMail = new System.Net.Mail.MailMessage();
    MyMail.From = new System.Net.Mail.MailAddress(from);

    foreach (var i in ToUser)
    {
        MyMail.To.Add(i.ToString());//設定收件者Email
    }

    MyMail.Subject = Subject;
    MyMail.Body = Body; //設定信件內容
    MyMail.IsBodyHtml = true; //是否使用html格式
    System.Net.Mail.SmtpClient MySMTP = new System.Net.Mail.SmtpClient(host, Int32.Parse(port));
    MySMTP.Credentials = new System.Net.NetworkCredential(account, password);
    MySMTP.EnableSsl = enableSsl;//是否啟用SSL憑證

    try
    {
        MySMTP.Send(MyMail);
        MyMail.Dispose(); //釋放資源
    }
    catch (Exception ex)
    {
        ex.ToString();
    }
}
參考網址: 
By Hao★

留言

熱門文章

[Web] Mac 安裝 Telnet

[Windows] 排程輸出、輸入指令

[C#] Stream.CopyTo 方法使用