【问题标题】:Can't send email through smtp gmail无法通过 smtp gmail 发送电子邮件
【发布时间】:2020-02-21 22:07:05
【问题描述】:

在 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:发送邮件失败。 ---> System.IO.IOException:无法从传输连接中读取数据:连接已关闭。
在 System.Net.Mail.SmtpReplyReaderFactory.ProcessRead(Byte[] buffer, Int32 offset, Int32 read, Boolean readLine)

【问题讨论】:

标签: c# smtp gmail smtpclient


【解决方案1】:

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

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);

【讨论】:

    【解决方案2】:

    来自 EnableSsl 属性的文档:

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

    长话短说,从其他网络来源得知,端口 465 需要在连接设置时协商 SSL(SmtpClient 不支持),而 587 在初始非安全对话后使用 STARTTLS(SmtpClient 支持)

    【讨论】:

      猜你喜欢
      • 2020-05-30
      • 1970-01-01
      • 1970-01-01
      • 2017-05-12
      • 1970-01-01
      • 1970-01-01
      • 2014-01-04
      • 2016-01-16
      相关资源
      最近更新 更多