首页 > 解决方案 > 使用 SMTP 客户端发送电子邮件

问题描述

我正在尝试使用我的 gmail 凭据使用 SMTP 客户端发送电子邮件。这是正在使用的代码

        using (var mail = GetMailInfo())
        {
            using (SmtpClient client = new SmtpClient("smtp.gmail.com", 465))
            {
                    client.DeliveryMethod = System.Net.Mail.SmtpDeliveryMethod.Network;
                    client.Credentials = new NetworkCredential("**@gmail.com", "Password");
                    client.UseDefaultCredentials = false;
                    client.EnableSsl = true;
                    client.Send(mail);
            }
        }

我收到超时错误

操作已超时

如果我再试一次,我会收到另一个错误消息

服务不可用,正在关闭传输通道。服务器响应为:并发 SMTP 连接过多;请稍后再试。

我究竟做错了什么?

标签: c#smtpclient

解决方案


最后我弄清楚我的代码出了什么问题更新的代码如下

using (var mail = GetMailInfo())
    {
        using (SmtpClient client = new SmtpClient("smtp.gmail.com", 587)) // port is 587 instead of 465 as mentioned by @jdweng in the comment
        {
                client.DeliveryMethod = System.Net.Mail.SmtpDeliveryMethod.Network;
                client.UseDefaultCredentials = false; // this must be before the **Credentials** else this will reset the given credential                   
                client.Credentials = new NetworkCredential("**@gmail.com", "Password");
                
                client.EnableSsl = true;
                client.Send(mail);
        }
    }

在顶部,如果您使用的是 gmail,请转到设置并停用 2 向身份验证,并应激活安全性较低的应用程序的访问权限

所有这些都可以在这里找到


推荐阅读