今天在做自動發送EMail給客戶的程式碰到了一個問題:
出現錯誤:SMTP 伺服器需要安全連接,或用戶端未經驗證。 伺服器回應為: 5.5.1 Authentication Required.
上網找了一陣子發現是gmail權限預設不能讓不明程式發送EMAIL,因此需要到google設定自己的電子郵件允許一般應用程式使用,也就是下圖最下面那排要啟用!!
啟用方法:
登入你的Google後→至Google帳號設定頁面→安全性較低的應用程式存取權限→啟用
啟用方法:
登入你的Google後→至Google帳號設定頁面→安全性較低的應用程式存取權限→啟用
async public Task<string> SendEmailAsync(string Email)
{
string emailFrom = "email@yahoo.com"; //你的email
string password = "password";
string emailTo = Email; //"someone@domain.com";
string subject = "Hello";
string body = "Hello, I'm just writing this to say Hi!";
using (MailMessage mail = new MailMessage())
{
mail.From = new MailAddress(emailFrom);
mail.To.Add(emailTo);
mail.Subject = subject;
mail.Body = body;
mail.IsBodyHtml = false;
// 設true的話body可用HTML語法
//mail.Attachments.Add(new Attachment("C:\\SomeFile.txt")); //附件
using (SmtpClient smtp = new SmtpClient())
{
smtp.Host = "smtp.gmail.com";
smtp.Port = 587;
smtp.UseDefaultCredentials = false;
smtp.Credentials = new NetworkCredential(emailFrom, password);
smtp.EnableSsl = true;
try { await smtp.SendMailAsync(mail); }
catch { return " 的EMail位址不存在"; }
}
return "提醒EMail已發送!";
}
}
呼叫:
async private void BtnSendEmail_Click(object sender, EventArgs e)
{
string result="";
sting Email="someone@gmail.com";
result = await RemindHelper.SendEmailAsync(Email);
Label1.Text = result;
}
沒有留言:
張貼留言