c# - 发送电子邮件时如何修复 'No connection could be made because the target machine actively refused it' 错误

标签 c# email smtp gmail

我正在尝试发送一封简单的测试电子邮件来检查邮件类在 C# 中的工作方式,但是在尝试调用 smtp.send(message); 时我收到以下错误: SocketException:无法建立连接,因为目标机器主动拒绝它 173.194.207.109:587 我已经查看了 wireshark 中的数据包(尽管不可否认我没有理解它们的知识)并且每次我尝试发送电子邮件时谷歌似乎都会发回 [RST, ACK] 数据包。有办法进一步诊断吗?

var fromAddress = new MailAddress("FROM@gmail.com", "FROM NAME");
var toAddress = new MailAddress("TO@gmail.com", "TO NAME");
const string fromPassword = "password";
const string subject = "Subject";
const string body = "Body";

var smtp = new SmtpClient
{
    Host = "smtp.gmail.com",
    Port = 587,
    EnableSsl = true,
    DeliveryMethod = SmtpDeliveryMethod.Network,
    UseDefaultCredentials = false,
    Credentials = new NetworkCredential(fromAddress.Address, fromPassword)
};
using (var message = new MailMessage(fromAddress, toAddress)
{
    Subject = subject,
    Body = body
})
{
    smtp.Send(message);
}    

最佳答案

看起来您可能想要更改您的 port 值,因为您有 EnableSsl = true,

Connect to smtp.gmail.com on port 465, if you're using SSL. (Connect on port 587 if you're using TLS.) Sign in with a Google username and password for authentication to connect with SSL or TLS. Reference

尝试:

var fromAddress = new MailAddress("FROM@gmail.com", "FROM NAME");
var toAddress = new MailAddress("TO@gmail.com", "TO NAME");
const string fromPassword = "password";
const string subject = "Subject";
const string body = "Body";

var smtp = new SmtpClient
{
    Host = "smtp.gmail.com",
    Port = 465, //or try: port = 587, or port = 25
    EnableSsl = true,
    DeliveryMethod = SmtpDeliveryMethod.Network,
    UseDefaultCredentials = false,
    Credentials = new NetworkCredential(fromAddress.Address, fromPassword)
};
using (var message = new MailMessage(fromAddress, toAddress)
{
    Subject = subject,
    Body = body
})
{
    smtp.Send(message);
}

StackOverflow Answer也可以作为很好的引用使用。

关于c# - 发送电子邮件时如何修复 'No connection could be made because the target machine actively refused it' 错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54043107/

相关文章:

c# - 从 asp.net web 应用程序打开本地系统上的文本文件

c# - 字符串上的模式匹配

php - 错误监控/处理/提醒系统中PHP服务的最佳实践

python - 为什么 Django 根据谷歌是一个 'less secure' 应用程序?

smtp - 如何通过 SMTP 中继(可能是 sendmail)延迟邮件传送

C# 出现错误。无法从 System.Data.DataRow 隐式转换为 DataRow

php - MySQL 选择一个包含替换文本的列,它等于一个值

email - golang & postfix - 收到的电子邮件 header 是本地主机

c# - 间歇性 "The server response was: 5.7.1 Unable to relay"错误

c# - Collider2D 在不同的游戏对象上触发 C# Unity3D 不工作