摘要:C# 透過office 365 發送 mail
//這段一定要, 跳過憑證無效用的
public static bool ValidateServerCertificate(Object sender, X509Certificate certificate, X509Chain chain, System.Net.Security.SslPolicyErrors sslPolicyErrors)
{
return true;
}
private void simpleButton2_Click(object sender, EventArgs e)
{
// 這段一定要, 要寫這個才可以跳過 "根據驗證程序,遠端憑證是無效的" 的錯誤
System.Net.ServicePointManager.ServerCertificateValidationCallback =
new System.Net.Security.RemoteCertificateValidationCallback(ValidateServerCertificate);
System.Net.Mail.SmtpClient smtpClient =
new System.Net.Mail.SmtpClient("xxxxx.xxxxxx.xxx.com"); // 365 主機, 在365 outlook 設定中個人郵件設定
smtpClient.Port = 587; // 365 好像都是用587
smtpClient.EnableSsl = true; //這一定要設 true
System.Net.NetworkCredential credentials =
new System.Net.NetworkCredential("xxxx@xxxmicrosoft.com", "xxxxx"); //365 帳號密碼
smtpClient.Credentials = credentials;
//smtpClient.ClientCertificates = false; //這行不用寫
for (int i = 0; i < 10; i++) //連續發送10次測試效能
{
System.Net.Mail.MailMessage mail = new System.Net.Mail.MailMessage();
// 寄件人這個好像不能亂寫, 一定要寫真實office 365 上面的郵箱和人名 , 不然會沒反應
mail.From = new System.Net.Mail.MailAddress("xxxx@xxxxxxxxxxxx", "xxxxxx");
mail.To.Add("xxxxx@gmail.com");
mail.Subject = "office 365 " + i.ToString();
mail.Body = "this is my message body";
mail.IsBodyHtml = true;
mail.Attachments.Add(new System.Net.Mail.Attachment("xxxxxxx")); //夾附件測試
smtpClient.Send(mail); // <--發送
mail.Dispose();
}
smtpClient = null;
}