发送邮件时无法连接到远程服务器c#
我目前正试图通过System.Net.Mail.MailMessage发送电子邮件,但在运行代码时,我生成了此异常,发送邮件失败。内部异常是:无法连接到远程服务器。我相信我正在连接远程服务器,但我很好奇为什么会出现这种异常 下面是我的代码的外观:发送邮件时无法连接到远程服务器c#,c#,.net,email,io,html-email,C#,.net,Email,Io,Html Email,我目前正试图通过System.Net.Mail.MailMessage发送电子邮件,但在运行代码时,我生成了此异常,发送邮件失败。内部异常是:无法连接到远程服务器。我相信我正在连接远程服务器,但我很好奇为什么会出现这种异常 下面是我的代码的外观: try { System.Net.Mail.MailMessage msg = new System.Net.Mail.MailMessage(); msg.Subject = "Te
try
{
System.Net.Mail.MailMessage msg = new System.Net.Mail.MailMessage();
msg.Subject = "Testing Email";
msg.From = new System.Net.Mail.MailAddress("test@gmail.com");
msg.To.Add(new System.Net.Mail.MailAddress("isavepluscom@gmail.com"));
msg.Body = "testing the email";
System.Net.Mail.SmtpClient smpt = new System.Net.Mail.SmtpClient();
smpt.Host = "smtp.gmail.com";
smpt.Port = 587;
smpt.EnableSsl = true;
smpt.Credentials = new System.Net.NetworkCredential("test@gmail.com", "1234567890");
smpt.Send(msg);
}
catch (Exception ex)
{
}
即使我在代码中设置了凭据,我的webconfig文件中还需要什么吗?能否尝试将代码缩短为以下内容
var smptClient = new SmtpClient("smtp.gmail.com", 587)
{
Credentials = new NetworkCredential("isavepluscom@gmail.com", "123456789"),
EnableSsl = true
};
smptClient.Send("isavepluscom@gmail.com", "test@gmail.com", "Testing Email", "testing the email");
你能试着把你的代码缩短成下面这样吗
var smptClient = new SmtpClient("smtp.gmail.com", 587)
{
Credentials = new NetworkCredential("isavepluscom@gmail.com", "123456789"),
EnableSsl = true
};
smptClient.Send("isavepluscom@gmail.com", "test@gmail.com", "Testing Email", "testing the email");
看起来像是一个安全例外。确保打开587端口进行通信,如果是服务器,默认情况下我将被阻止。看起来像是安全异常。确保打开587端口进行通信,如果它是服务器,默认情况下我将被阻止。尝试替换此行
msg.To.Add(新系统.Net.Mail.MailAddress()isavepluscom@gmail.com"));代码>带有以下消息。添加(“isavepluscom@gmail.com");` 还要替换此行msg.From=new System.Net.Mail.MailAddress(“test@gmail.com");代码>带有msg.From=新邮件地址(“test@gmail.com");代码>否这不起作用,它仍然给我错误:无法连接到远程服务器。Gmail
期望在..上接收其凭据的端口是什么?你在gmail上是否有一个名为test
的帐户设置以及确切的密码。。?希望你用正确的证件替换它。我确定它是587,是的,我用我自己的证件替换它。为了安全起见,我在这里放了一个假的。看我的答案,我刚刚用我自己的Gmail帐户/密码测试了这个。。更容易阅读尝试替换这一行msg.to.Add(新的System.Net.Mail.MailAddress(“isavepluscom@gmail.com"));代码>带有以下消息。添加(“isavepluscom@gmail.com");` 还要替换此行msg.From=new System.Net.Mail.MailAddress(“test@gmail.com");代码>带有msg.From=新邮件地址(“test@gmail.com");代码>否这不起作用,它仍然给我错误:无法连接到远程服务器。Gmail
期望在..上接收其凭据的端口是什么?你在gmail上是否有一个名为test
的帐户设置以及确切的密码。。?希望你用正确的证件替换它。我确定它是587,是的,我用我自己的证件替换它。为了安全起见,我在这里放了一个假的。看我的答案,我刚刚用我自己的Gmail帐户/密码测试了这个。。更容易阅读我知道你做了什么,但问题仍然存在,可能是我的服务器防火墙阻止了连接,我将尝试使用它,看看可能是这样的情况,但是代码在我使用我自己的网络帐户进行测试时确实起作用。谢谢,我看到你做了什么,但问题仍然存在,可能是我的服务器防火墙阻止了连接,我将尝试使用它,看看可能是这样的情况,但是代码在我使用自己的帐户在我们的网络上进行最终测试时仍然有效。谢谢