无法通过smtp gmail发送电子邮件

Can't send email through smtp gmail

在 C# 中,我尝试使用 Gmail 发送电子邮件。这是我的代码:

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: Failure sending mail. ---> System.IO.IOException: Unable to read data from the transport connection: The connection was closed.
at System.Net.Mail.SmtpReplyReaderFactory.ProcessRead(Byte[] buffer, Int32 offset, Int32 read, 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 secure communication using SSL. See RFC 3207 published by the Internet Engineering Task Force (IETF) for more information. An alternate connection method is where an SSL session is established up front before any protocol commands are sent. This connection method is sometimes called SMTP/SSL, SMTP over SSL, or SMTPS and by default uses port 465. This alternate connection method using SSL is not currently supported.

长话短说,来自其他网络资源的是端口 465 希望在连接设置时协商 SSL(SmtpClient 不支持),而 587 在初始非安全对话后使用 STARTTLS(SmtpClient 支持)