我正在使用以下代码发送电子邮件。代码在我的本地机器上正常工作。但是在生产服务器上,我得到了错误消息

var fromAddress = new MailAddress("mymailid@gmail.com");
var fromPassword = "xxxxxx";
var toAddress = new MailAddress("yourmailid@yourdoamain.com");

string subject = "subject";
string body = "body";

System.Net.Mail.SmtpClient smtp = new System.Net.Mail.SmtpClient
{
    Host = "smtp.gmail.com",
    Port = 587,
    EnableSsl = true,
    DeliveryMethod = System.Net.Mail.SmtpDeliveryMethod.Network,
    UseDefaultCredentials = false,
    Credentials = new NetworkCredential(fromAddress.Address, fromPassword)       
};

using (var message = new MailMessage(fromAddress, toAddress)
{
    Subject = subject,
    Body = body
})

smtp.Send(message);

在我的Gmail A/c上,我从生产服务器运行代码后收到了以下电子邮件

Hi , Someone recently used your password to try to sign in to your Google Account mymailid@gmail.com. This person was using an application such as an email, client or mobile device. We prevented the sign-in attempt in case this was a hijacker trying to access your account. Please review the details of the sign-in attempt: Friday, 3 January 2014 13:56:08 o'clock UTC IP Address: xxx.xx.xx.xxx (abcd.net.) Location: Philadelphia PA, Philadelphia, PA, USA If you do not recognise this sign-in attempt, someone else might be trying to access your account. You should sign in to your account and reset your password immediately. Reset password If this was you and you are having trouble accessing your account, complete the troubleshooting steps listed at http://support.google.com/mail?p=client_login Yours sincerely, The Google Accounts team


当前回答

当您尝试从不同的时区或IP地址计算机登录时,通常会发生这种情况。您的生产服务器和您使用的邮件id都位于不同的时区。以下两种方案任选其一:

1)通过远程访问登录生产服务器,并使用您的凭证登录gmail一次。他们会要求确认,确认后注销。

或者2)登录gmail到你的本地计算机,按照这个链接,选择审查这个活动,并采取适当的行动。

其他回答

当您尝试从不同的时区或IP地址计算机登录时,通常会发生这种情况。您的生产服务器和您使用的邮件id都位于不同的时区。以下两种方案任选其一:

1)通过远程访问登录生产服务器,并使用您的凭证登录gmail一次。他们会要求确认,确认后注销。

或者2)登录gmail到你的本地计算机,按照这个链接,选择审查这个活动,并采取适当的行动。

Tomasz Madeyski的评论解决了我的问题…他告诉存在一个错误的SetDefaultCredential,他说:

问题是在UseDefaultCredentials setter中有这样的代码:this.transport. credentials = value ?(ICredentialsByHost) CredentialCache。DefaultNetworkCredentials: (ICredentialsByHost) null;它覆盖由凭证设置器设置的凭证。对我来说,它看起来像SmtpClient的bug。”

如果你输入smtpClient。设置凭证后UseDefaultCredentials = false…这一行设置为空这些凭据…

更新2022

更不安全的应用程序方法不再工作

您应该迁移到GMail SMTP API

仅使用gmail id和密码发送电子邮件不再有效。您必须从谷歌云控制台设置api并创建OAuth凭据。

链接到谷歌云控制台

连结至官方指南

链接到一个简单的指南

原来的答案

这是一个安全问题。Gmail默认情况下阻止自定义应用程序访问您的电子邮件帐户。您可以将其设置为接受应用程序的登录。

登录您的电子邮件后,点击这里

这将带您到下面的页面

嗨,我也有同样的问题,

我是怎么解决它的。就是打开不太安全的应用。 在连接到我的gmail帐户后。我输入了这个链接:https://www.google.com/settings/security/lesssecureapps

然后我打开安全应用程序,它就工作了。 上面也说过

2022年5月30日之后,Gmail改变了对外部应用程序的政策 使用谷歌SMTP发送电子邮件详细信息。 Solition是登录谷歌帐户,您要发送电子邮件,启用谷歌两步验证,并为外部应用程序创建密码