簡體   English   中英

無法通過 smtp gmail 發送 email

[英]Can't send email through smtp gmail

在 C# 中,我嘗試使用 Gmail 發送 email。 這是我的代碼:

MailMessage mail = new MailMessage();
SmtpClient SmtpServer = new SmtpClient("smtp.gmail.com");

mail.From = new MailAddress("myemail@gmail.com");
mail.To.Add("myemailto@gmail.com");
mail.Subject = "Test Mail";
mail.Body = "This is for testing SMTP mail from GMAIL";

SmtpServer.Port = 465;
SmtpServer.Credentials = new System.Net.NetworkCredential("myemail@gmail.com", "mypsw");
SmtpServer.UseDefaultCredentials = false;
SmtpServer.DeliveryMethod = SmtpDeliveryMethod.Network;
SmtpServer.EnableSsl = true;

SmtpServer.Send(mail);

我得到錯誤:

{System.Net.Mail.SmtpException:發送郵件失敗。 ---> System.IO.IOException:無法從傳輸連接讀取數據:連接已關閉。
在 System.Net.Mail.SmtpReplyReaderFactory.ProcessRead(字節 [] 緩沖區,Int32 偏移量,Int32 讀取,Boolean readLine)

某處有答案,但我不記得在哪里,所以我將在下面為您編寫代碼。 如果有人找到答案,請發表評論,我會在那里指出。

var smtpClient = new SmtpClient
{
    Host = "smtp.gmail.com",
    Port = 587, // Port 
    EnableSsl = true,
    Credentials = new NetworkCredential("yourmail@gmail.com", "yourpw")
};

MailMessage msg = new MailMessage();
msg.IsBodyHtml = true;
msg.Subject = "Subject";

msg.From = new MailAddress("yourmail@gmail.com");


msg.Body = "Body here";
msg.Bcc.Add(li[i].Value);
smtpClient.Send(msg);

來自 EnableSsl 屬性的文檔:

The SmtpClient class only supports the SMTP Service Extension for Secure SMTP over Transport Layer Security as defined in RFC 3207. In this mode, the SMTP session begins on an unencrypted channel, then a STARTTLS command is issued by the client to the server to switch to使用 SSL 進行安全通信。 有關詳細信息,請參閱 Internet 工程任務組 (IETF) 發布的 RFC 3207。 另一種連接方法是在發送任何協議命令之前預先建立 SSL session。 此連接方法有時稱為 SMTP/SSL、SMTP over SSL 或 SMTPS,默認使用端口 465。目前不支持使用 ZEA52C36203C5F99C3CE2442D531B1A22 的替代連接方法。

來自其他 web 來源的長話短說是端口 465 期望在連接設置時協商 SSL(SmtpClient 不支持),而 587 在初始非安全對話后使用 STARTTLS(由 SmtpClient 支持)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM