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

问题描述 投票:0回答:2

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

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

mail.From = new MailAddress("[email protected]");
mail.To.Add("[email protected]");
mail.Subject = "Test Mail";
mail.Body = "This is for testing SMTP mail from GMAIL";

SmtpServer.Port = 465;
SmtpServer.Credentials = new System.Net.NetworkCredential("[email protected]", "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(Byte []缓冲区,Int32偏移量,Int32读取,布尔值readLine)

c# smtp gmail smtpclient
2个回答
1
投票

在某处有答案,但我不记得在哪里,所以我将在下面为您编写代码。如果有人找到答案,请发表评论,我会指出。

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

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

msg.From = new MailAddress("[email protected]");


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

0
投票

来自EnableSsl属性的文档:

SmtpClient类仅支持RFC 3207中定义的用于通过传输层安全的安全SMTP的SMTP服务扩展。在这种模式下,SMTP会话在未加密的通道上开始,然后客户端向服务器发出STARTTLS命令以切换到使用SSL的安全通信。有关更多信息,请参见Internet工程任务组(IETF)发布的RFC 3207。另一种连接方法是在发送任何协议命令之前先建立SSL会话。有时将此连接方法称为SMTP / SSL,基于SSL的SMTP或SMTPS,默认情况下使用端口465。当前不支持使用SSL的此备用连接方法。

长话短说,其他Web来源是端口465希望在连接建立时协商SSL(SmtpClient不支持),而587在初始非安全对话框(SmtpClient支持)之后使用STARTTLS。>

© www.soinside.com 2019 - 2024. All rights reserved.