使用C#通过Gmail SMTP服务器发送电子邮件

时间:2022-11-15 10:48:41

For some reason neither the accepted answer nor any others work for me for "Sending email in .NET through Gmail". Why would they not work?

出于某种原因,“通过Gmail发送.NET中的电子邮件”既没有被接受的答案也没有其他任何对我有用。他们为什么不工作?

UPDATE: I have tried all the answers (accepted and otherwise) in the other question, but none of them work.

更新:我在另一个问题中尝试了所有答案(接受和否则),但没有一个能够奏效。

I would just like to know if it works for anyone else, otherwise Google may have changed something (which has happened before).

我想知道它是否适用于其他任何人,否则谷歌可能已经改变了一些事情(之前发生过)。

When I try the piece of code that uses SmtpDeliveryMethod.Network, I quickly receive an SmtpException on Send(message). The message is

当我尝试使用SmtpDeliveryMethod.Network的代码片段时,我会在Send(消息)上快速收到SmtpException。信息是

The SMTP server requires a secure connection or the client was not authenticated.

SMTP服务器需要安全连接或客户端未经过身份验证。

The server response was:

服务器响应是:

5.5.1 Authentication Required. Learn more at" <-- seriously, it ends there.

5.5.1需要验证。在< - - 认真地了解更多内容。

UPDATE:

This is a question that I asked a long time ago, and the accepted answer is code that I've used many, many times on different projects.

这是我很久以前问过的一个问题,接受的答案是我在不同的项目中使用了很多次的代码。

I've taken some of the ideas in this post and other EmailSender projects to create an EmailSender project at Codeplex. It's designed for testability and supports my favourite SMTP services such as GoDaddy and Gmail.

我已经在这篇文章和其他EmailSender项目中采用了一些想法,在Codeplex上创建了一个EmailSender项目。它专为可测试性而设计,支持我最喜欢的SMTP服务,如GoDaddy和Gmail。

27 个解决方案

#1


268  

CVertex, make sure to review your code, and, if that doesn't reveal anything, post it. I was just enabling this on a test ASP.NET site I was working on, and it works.

CVertex,请务必检查您的代码,如果没有透露任何内容,请发布。我只是在我正在研究的测试ASP.NET网站上启用它,它可以工作。

Actually, at some point I had an issue on my code. I didn't spot it until I had a simpler version on a console program and saw it was working (no change on the Gmail side as you were worried about). The below code works just like the samples you referred to:

实际上,在某些时候我的代码存在问题。我没有发现它,直到我在控制台程序上有一个更简单的版本,并看到它正在工作(在你担心的Gmail方面没有变化)。以下代码的工作方式与您引用的示例类似:

using System;using System.Collections.Generic;using System.Linq;using System.Text;using System.Net.Mail;using System.Net;namespace ConsoleApplication2{    class Program    {        static void Main(string[] args)        {            var client = new SmtpClient("smtp.gmail.com", 587)            {                Credentials = new NetworkCredential("myusername@gmail.com", "mypwd"),                EnableSsl = true            };            client.Send("myusername@gmail.com", "myusername@gmail.com", "test", "testbody");            Console.WriteLine("Sent");            Console.ReadLine();        }    }}

I also got it working using a combination of web.config, http://msdn.microsoft.com/en-us/library/w355a94k.aspx and code (because there is no matching EnableSsl in the configuration file :( ).

我也使用web.config,http://msdn.microsoft.com/en-us/library/w355a94k.aspx和代码的组合工作(因为配置文件中没有匹配的EnableSsl :()。

#2


64  

THE FOLLOWING WILL ALMOST CERTAINLY BE THE ANSWER TO YOUR QUESTION IF ALL ELSE HAS FAILED:

如果所有人都失败了,以下几乎可以回答你的问题:

I got the exact same error, it turns out Google's new password strengh measuring algorithm has changed deeming my current password as too weak, and not telling me a thing about it (not even a message or warning)... How did I discover this? Well, I chose to change my password to see if it would help (tried everything else to no avail) and when I changed my password, it worked!

我得到了完全相同的错误,事实证明谷歌的新密码强度测量算法已经改变,认为我当前的密码太弱,并没有告诉我一件事情(甚至没有消息或警告)......我怎么发现这个?好吧,我选择更改我的密码,看看它是否会有所帮助(尝试其他一切无济于事),当我更改密码时,它有效!

Then, for an experiment, I tried changing my password back to my previous password to see what would happen, and Gmail didn't actually allow me to do this, citing the reason "sorry we cannot allow you to save this change as your chosen password is too weak" and wouldn't let me go back to my old password. I figured from this that it was erroring out because either a) you need to change your password once every x amount of months or b). as I said before, their password strength algorithms changed and therefore the weak password i had was not accepted, even though they did not say anything about this when trying to login ANYWHERE! This (number 2) is the most likely scenario, as my weak password was about 4 months old, and it let me use it in Gmail.

然后,为了进行实验,我尝试将密码更改回以前的密码以查看会发生什么,并且Gmail实际上不允许我这样做,理由是“抱歉我们不能允许您保存此更改作为您选择的密码太弱了“并且不会让我回到我的旧密码。我认为这是错误的,因为a)你需要每x个月或b)更改一次密码。正如我之前所说,他们的密码强度算法发生了变化,因此我所接受的弱密码未被接受,即使他们在尝试登录时没有说出任何相关信息!这个(数字2)是最可能的情况,因为我的弱密码大约是4个月,它让我在Gmail中使用它。

It's pretty bad that they said nothing about this, but it makes sense. Because most hijacked emails are logged into using software outside of gmail, and I'm guessing you are required to have a stronger password if you want to use Gmail outside of the Gmail environment.

他们对此没有任何说法,这是非常糟糕的,但这是有道理的。因为大多数被劫持的电子邮件是使用gmail以外的软件登录的,我猜你要在Gmail环境之外使用Gmail时需要更强的密码。

I hope this helps!

我希望这有帮助!

#3


59  

In addition to the other troubleshooting steps above, I would also like to add that if you have enabled two-factor authentication (also known as two-step verification) on your GMail account, you must generate an application-specific password and use that newly generated password to authenticate via SMTP.

除了上面的其他疑难解答步骤之外,我还想补充一点,如果您在GMail帐户上启用了双因素身份验证(也称为两步验证),则必须生成应用程序专用密码并使用新密码生成密码以通过SMTP进行身份验证。

To create one, visit: https://www.google.com/settings/ and choose Authorizing applications & sites to generate the password.

要创建一个,请访问:https://www.google.com/settings/并选择授权应用程序和网站以生成密码。

#4


43  

Turn On Access For Less Secure Apps and it will work for all no need to change password.

Link to Gmail Setting

链接到Gmail设置

使用C#通过Gmail SMTP服务器发送电子邮件

#5


28  

I've had some problems sending emails from my gmail account too, which were due to several of the aforementioned situations.Here's a summary of how I got it working, and keeping it flexible at the same time:

我在从我的Gmail帐户发送电子邮件时遇到了一些问题,这是由于上述几种情况造成的。这是我如何使其工作的总结,同时保持灵活性:

  • First of all setup your GMail account:
    • Enable IMAP and assert the right maximum number of messages (you can do so here)
    • 启用IMAP并断言正确的最大消息数(您可以在此处执行此操作)

    • Make sure your password is at least 7 characters and is strong (according to Google)
    • 确保您的密码至少为7个字符并且非常强大(根据Google)

    • Make sure you don't have to enter a captcha code first. You can do so by sending a test email from your browser.
    • 确保您不必先输入验证码。您可以通过从浏览器发送测试电子邮件来完成此操作。

  • 首先设置您的GMail帐户:启用IMAP并声明正确的最大邮件数量(您可以在此处执行此操作)确保您的密码至少为7个字符并且非常强大(根据Google)确保您不必首先输入验证码。您可以通过从浏览器发送测试电子邮件来完成此操作。

  • Make changes in web.config (or app.config, I haven't tried that yet but I assume it's just as easy to make it work in a windows application):
  • 在web.config(或app.config中进行更改,我还没有尝试过,但我认为在Windows应用程序中使它工作一样容易):

<configuration>    <appSettings>        <add key="EnableSSLOnMail" value="True"/>       </appSettings>    <!-- other settings -->     ...    <!-- system.net settings -->    <system.net>        <mailSettings>            <smtp from="yourusername@gmail.com" deliveryMethod="Network">                <network                     defaultCredentials="false"                     host="smtp.gmail.com"                     port="587"                     password="stR0ngPassW0rd"                     userName="yourusername@gmail.com"                    />                <!-- When using .Net 4.0 (or later) add attribute: enableSsl="true" and you're all set-->            </smtp>        </mailSettings>    </system.net></configuration>
Add a Class to your project:Imports System.Net.MailPublic Class SSLMail    Public Shared Sub SendMail(ByVal e As System.Web.UI.WebControls.MailMessageEventArgs)        GetSmtpClient.Send(e.Message)        'Since the message is sent here, set cancel=true so the original SmtpClient will not try to send the message too:        e.Cancel = True    End Sub    Public Shared Sub SendMail(ByVal Msg As MailMessage)        GetSmtpClient.Send(Msg)    End Sub    Public Shared Function GetSmtpClient() As SmtpClient        Dim smtp As New Net.Mail.SmtpClient        'Read EnableSSL setting from web.config        smtp.EnableSsl = CBool(ConfigurationManager.AppSettings("EnableSSLOnMail"))        Return smtp    End FunctionEnd Class

And now whenever you want to send emails all you need to do is call SSLMail.SendMail:

现在,无论何时您想发送电子邮件,您只需要调用SSLMail.SendMail:

e.g. in a Page with a PasswordRecovery control:

例如在具有PasswordRecovery控件的页面中:

Partial Class RecoverPasswordInherits System.Web.UI.PageProtected Sub RecoverPwd_SendingMail(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.MailMessageEventArgs) Handles RecoverPwd.SendingMail    e.Message.Bcc.Add("webmaster@example.com")    SSLMail.SendMail(e)End SubEnd Class

Or anywhere in your code you can call:

或者您可以在代码中的任何地方致电:

SSLMail.SendMail(New system.Net.Mail.MailMessage("from@from.com","to@to.com", "Subject", "Body"})

I hope this helps anyone who runs into this post! (I used VB.NET but I think it's trivial to convert it to any .NET language.)

我希望这有助于任何遇到这篇文章的人! (我使用VB.NET,但我认为将它转换为任何.NET语言都是微不足道的。)

#6


13  

Dim SMTPClientObj As New Net.Mail.SmtpClientSMTPClientObj.UseDefaultCredentials = FalseSMTPClientObj.Credentials = New System.Net.NetworkCredential("myusername@gmail.com", "mypwd")SMTPClientObj.Host = "smtp.gmail.com"SMTPClientObj.Port = 587SMTPClientObj.EnableSsl = TrueSMTPClientObj.Send("myusername@gmail.com","yourusername@gmail.com","test","testbody")

If you get an error like "The SMTP server requires a secure connection or the client was not authenticated. The server response was: 5.5.1 Authentication Required. Learn more at" as I get before this, make sure the line SMTPClientObj.UseDefaultCredentials = False included and this line should before the SMTPClientObj.Credentials.

如果您收到类似“SMTP服务器需要安全连接或客户端未通过身份验证的错误。服务器响应为:5.5.1需要身份验证。了解更多信息”,如前所述,请确保SMTPClientObj.UseDefaultCredentials =包含False,此行应在SMTPClientObj.Credentials之前。

I did try to switch these 2 lines the opposite way and the 5.5.1 Authentication Required error returned.

我确实尝试以相反的方式切换这两行,并返回5.5.1 Authentication Required错误。

#7


12  

Oh...It's amazing...First I Couldn't send an email for any reasons.But after I changed the sequence of these two lines as below, it works perfectly.

哦......真是太棒了......首先我无法发送任何原因的电子邮件。但是在我改变了这两行的顺序后,它完美无缺。

//(1)client.UseDefaultCredentials = true;//(2)client.Credentials = new System.Net.NetworkCredential("username@gmail.com", "password");

Hope this help!!! :)

希望这有帮助!!! :)

#8


9  

The problem is not one of technical ability to send through gmail. That works for most situations. If you can't get a machine to send, it is usually due to the machine not having been authenticated with a human at the controls at least once.

问题不在于通过gmail发送技术能力。这适用于大多数情况。如果您无法让机器发送,通常是由于机器未在控件上至少进行过一次人工认证。

The problem that most users face is that Google decides to change the outbound limits all the time. You should always add defensive code to your solution. If you start seeing errors, step off your send speed and just stop sending for a while. If you keep trying to send Google will sometimes add extra time to your delay period before you can send again.

大多数用户面临的问题是Google决定始终更改出站限额。您应该始终为您的解决方案添加防御性代码。如果您开始看到错误,请退出发送速度并停止发送一段时间。如果您一直试图发送Google,有时会在延迟期间增加额外的时间,然后再发送。

What I have done in my current system is to send with a 1.5 second delay between each message. Then if I get any errors, stop for 5 minutes and then start again. This usually works and will allow you to send up to the limits of the account (last I checked it was 2,000 for premier customer logins per day).

我在当前系统中所做的是在每条消息之间发送1.5秒的延迟。然后,如果我收到任何错误,请停止5分钟,然后重新开始。这通常有效,并且允许您发送帐户的限制(最后我检查它是每天首要客户登录的2,000)。

#9


9  

I had the same problem, but it turned out to be my virus protection was blocking outgoing "spam" email. Turning this off allowed me to use port 587 to send SMTP email via GMail

我遇到了同样的问题,但结果是我的病毒防护阻止了传出的“垃圾邮件”电子邮件。关闭它允许我使用端口587通过GMail发送SMTP电子邮件

#10


9  

Simple steps to fix this:

解决这个问题的简单步骤:

1)Sign in to your Gmail

1)登录您的Gmail

2)Navigate to this page https://www.google.com/settings/security/lesssecureapps & set to "Turn On"

2)导航到此页面https://www.google.com/settings/security/lesssecureapps并设置为“开启”

#11


8  

I'm not sure which .NET version is required for this because eglasius mentioned there is no matching enableSsl setting (I'm using .NET 4.0, but I suspect it to work in .NET 2.0 or later), but this configuration justed worked for me (and doesn't require you to use any programmatic configuration):

我不确定这需要哪个.NET版本,因为eglasius提到没有匹配的enableSsl设置(我使用的是.NET 4.0,但我怀疑它可以在.NET 2.0或更高版本中运行),但这个配置值得一试对我来说(并且不要求你使用任何程序化配置):

<system.net>  <mailSettings>    <smtp from="myusername@gmail.com" deliveryMethod="Network">      <network defaultCredentials="false" enableSsl="true" host="smtp.gmail.com" port="587" password="password" userName="myusername@gmail.com"/>    </smtp>  </mailSettings></system.net>

You might have to enable POP or IMAP on your Gmail account first:https://mail.google.com/mail/?shva=1#settings/fwdandpop

您可能必须先在Gmail帐户中启用POP或IMAP:https://mail.google.com/mail/?shva = 1#settings / fwdandpop

I recommend trying it with a normal mail client first...

我建议先用普通邮件客户端尝试...

#12


8  

If nothing else has worked here for you you may need to allow access to your gmail account from third party applications. This was my problem. To allow access do the following:

如果此处没有其他任何工作,您可能需要允许从第三方应用程序访问您的Gmail帐户。这是我的问题。要允许访问,请执行以下操作:

  1. Sign in to your gmail account.
  2. 登录您的Gmail帐户。

  3. Visit this page https://accounts.google.com/DisplayUnlockCaptcha and click on button to allow access.
  4. 访问此页面https://accounts.google.com/DisplayUnlockCaptcha并单击按钮以允许访问。

  5. Visit this page https://www.google.com/settings/security/lesssecureapps and enable access for less secure apps.
  6. 访问此页面https://www.google.com/settings/security/lesssecureapps并启用对安全性较低的应用的访问权限。

This worked for me hope it works for someone else!

这对我有用,希望它适用于其他人!

#13


6  

@Andres Pompiglio: Yes that's right you must change your password at least once..this codes works just fine:

@Andres Pompiglio:是的,你必须至少更改一次密码..这个代码工作得很好:

//Satrt Send Email Functionpublic string SendMail(string toList, string from, string ccList,    string subject, string body){    MailMessage message = new MailMessage();    SmtpClient smtpClient = new SmtpClient();    string msg = string.Empty;    try    {        MailAddress fromAddress = new MailAddress(from);        message.From = fromAddress;        message.To.Add(toList);        if (ccList != null && ccList != string.Empty)            message.CC.Add(ccList);        message.Subject = subject;        message.IsBodyHtml = true;        message.Body = body;        // We use gmail as our smtp client        smtpClient.Host = "smtp.gmail.com";           smtpClient.Port = 587;        smtpClient.EnableSsl = true;        smtpClient.UseDefaultCredentials = true;        smtpClient.Credentials = new System.Net.NetworkCredential(            "Your Gmail User Name", "Your Gmail Password");        smtpClient.Send(message);        msg = "Successful<BR>";    }    catch (Exception ex)    {        msg = ex.Message;    }    return msg;}//End Send Email Function

AND you can make a call to the function by using:

您可以使用以下方法调用该函数:

Response.Write(SendMail(recipient Address, "UserName@gmail.com", "ccList if any", "subject", "body"))

#14


5  

I also found that the account I used to log in was de-activated by google for some reason. Once I reset my password (to the same as it used to be), then I was able to send emails just fine. I was getting 5.5.1 message also.

我还发现,由于某种原因,我以前登录的帐户已被谷歌取消激活。一旦我重置密码(与以前一样),我就可以发送电子邮件了。我也收到5.5.1消息。

#15


5  

I had also try to many solution but make some changes it will work

我也试过很多解决方案,但做一些改变它会起作用

host = smtp.gmail.comport = 587username = email@gmail.compassword = passwordenabledssl = true

with smtpclient above parameters are work in gmail

使用smtpclient以上参数在gmail中工作

#16


5  

I was using corporate VPN connection. It was the reason why I couldn't send email from my application. It works if I disconnect from VPN.

我正在使用企业VPN连接。这就是我无法从我的应用程序发送电子邮件的原因。如果我从VPN断开连接,它会工作。

#17


4  

I ran into this same error ( "The SMTP server requires a secure connection or the client was not authenticated. The server response was: 5.5.1 Authentication Required. Learn more at" ) and found out that I was using the wrong password. I fixed the login credentials, and it sent correctly.

我遇到了同样的错误(“SMTP服务器需要安全连接或客户端未经过身份验证。服务器响应是:5.5.1需要身份验证。了解更多信息”)并发现我使用了错误的密码。我修复了登录凭据,并正确发送。

I know this is late, but maybe this will help someone else.

我知道这已经很晚了,但也许这会帮助别人。

#18


4  

Another thing that I've found is that you must change your password at least once.And try to use a secure level password (do not use the same user as password, 123456, etc.)

我发现的另一件事是你必须至少更改一次密码。并尝试使用安全级密码(不要使用相同的用户密码,123456等)

#19


4  

I was getting the same error and none of the above solutions helped.

我得到了同样的错误,上述解决方案都没有帮助。

My problem was that I was running the code from a remote server, which had never been used to log into the gmail account.

我的问题是我从远程服务器运行代码,该服务器从未用于登录gmail帐户。

I opened a browser on the remote server and logged into gmail from there. It asked a security question to verify it was me since this was a new location. After doing the security check I was able to authenticate through code.

我在远程服务器上打开了一个浏览器并从那里登录到了gmail。它问了一个安全问题,以确认这是我,因为这是一个新的位置。在进行安全检查后,我能够通过代码进行身份验证。

#20


4  

Yet another possible solution for you. I was having similar problems connecting to gmail via IMAP. After trying all the solutions that I came across that you will read about here and elsewhere on SO (eg. enable IMAP, enable less secure access to your mail, using https://accounts.google.com/b/0/displayunlockcaptcha and so on), I actually set up a new gmail account once more.

另一种可能的解决方案。我在通过IMAP连接到gmail时遇到了类似的问题。在尝试了我遇到的所有解决方案之后,您将在此处和其他地方阅读有关SO的信息(例如,启用IMAP,使用https://accounts.google.com/b/0/displayunlockcaptcha启用对邮件的安全性较低的访问权限所以,我实际上再次建立了一个新的Gmail帐户。

In my original test, the first gmail account I had created, I had connected to my main gmail account. This resulted in erratic behaviour where the wrong account was being referenced by google. For example, running https://accounts.google.com/b/0/displayunlockcaptcha opened up my main account rather than the one I had created for the purpose.

在我原来的测试中,我创建的第一个gmail帐户,我已经连接到我的主要Gmail帐户。这导致了谷歌引用错误帐户的不稳定行为。例如,运行https://accounts.google.com/b/0/displayunlockcaptcha会打开我的主帐户,而不是我为此目的创建的帐户。

So when I created a new account and did not connect it to my main account, after following all the appropriate steps as above, I found that it worked fine!

因此,当我创建一个新帐户并且未将其连接到我的主帐户时,在按照上述所有相应步骤操作后,我发现它工作正常!

I haven't yet confirmed this (ie. reproduced), but it apparently did it for me...hope it helps.

我还没有证实这一点(即转载),但它显然是为我做的...希望它有所帮助。

#21


4  

Turn on less secure apps for your account: https://www.google.com/settings/security/lesssecureapps

为您的帐户开启安全性较低的应用:https://www.google.com/settings/security/lesssecureapps

#22


4  

  1. First check your gmail account setting & turn On from "Access for less secure apps"使用C#通过Gmail SMTP服务器发送电子邮件
  2. 首先检查您的Gmail帐户设置,然后从“访问安全性较低的应用”开启

We strongly recommend that you use a secure app, like Gmail, to access your account. All apps made by Google meet these security standards. Using a less secure app, on the other hand, could leave your account vulnerable. Learn more.

我们强烈建议您使用Gmail等安全应用访问您的帐户。 Google生产的所有应用均符合这些安全标准。另一方面,使用安全性较低的应用可能会使您的帐户容易受到攻击。学到更多。

  1. Set

    smtp.UseDefaultCredentials = false;

    before

    smtp.Credentials = new NetworkCredential(fromAddress, fromPassword);
  2. 设置smtp.UseDefaultCredentials = false;在smtp.Credentials = new NetworkCredential(fromAddress,fromPassword)之前;

#23


3  

You can also connect via port 465, but due to some limitations of the System.Net.Mail namespace you may have to alter your code. This is because the namespace does not offer the ability to make implicit SSL connections. This is discussed at http://blogs.msdn.com/b/webdav_101/archive/2008/06/02/system-net-mail-with-ssl-to-authenticate-against-port-465.aspx, and I have supplied an example of how to use the CDO (Collaborative Data Object) in another discussion (GMail SMTP via C# .Net errors on all ports).

您也可以通过端口465进行连接,但由于System.Net.Mail命名空间的某些限制,您可能需要更改代码。这是因为命名空间不提供进行隐式SSL连接的能力。这在http://blogs.msdn.com/b/webdav_101/archive/2008/06/02/system-net-mail-with-ssl-to-authenticate-against-port-465.aspx上讨论,我提供了一个如何在另一个讨论中使用CDO(协作数据对象)的示例(GMail SMTP通过所有端口上的C#.Net错误)。

#24


3  

I had this problem resolved. Aparently that message is used in multiple error types.My problem was that i had reached my maximum of 500 sent mails.

我解决了这个问题。显然,该消息用于多种错误类型。我的问题是我已经达到了最多500封已发送的邮件。

log into the account and manually try to send a mail. If the limit has been reached it will inform you

登录帐户并手动尝试发送邮件。如果达到限制,它将通知您

#25


2  

One or more reasons are there for these error.

出现这些错误的原因有一个或多个。

  • Log in with your Gmail( or any other if ) in your local system.

    使用您本地系统中的Gmail(或任何其他if)登录。

  • Also check for Less Secure App and Set it to "Turn On" here is the Link for GMAIL.https://www.google.com/settings/security/lesssecureapps

    同时检查不太安全的应用程序并将其设置为“打开”这里是GMAIL的链接.https://www.google.com/settings/security/lesssecureapps

  • check for EnableSsl in your Email code, and also set it to true.

    检查电子邮件代码中的EnableSsl,并将其设置为true。

    smtp.EnableSsl = true;
  • Also check which port are you using currently. 25 is Global, but you can check it for others too like 587. check here. Does all SMTP communication happen over 25?

    还要检查您当前使用的是哪个端口。 25是全球,但你也可以像587一样检查其他人。点击这里。所有SMTP通信都发生在25以上吗?

  • IF YOU ARE ON REMOTE : Check the answer of Vlad Tamas above.

    如果你在远程:检查上面的Vlad Tamas的答案。

#26


2  

  smtp.Host = "smtp.gmail.com"; //host name    smtp.Port = 587; //port number    smtp.EnableSsl = true; //whether your smtp server requires SSL    smtp.DeliveryMethod = System.Net.Mail.SmtpDeliveryMethod.Network;    smtp.Credentials = new NetworkCredential(fromAddress, fromPassword);    smtp.Timeout = 20000;

#27


1  

Change your gmail password and try again, it should work after that.

更改您的Gmail密码并重试,之后应该可以使用。

Don't know why, but every time you change your hosting you have to change your password.

不知道为什么,但每次更改主机时都必须更改密码。

#1


268  

CVertex, make sure to review your code, and, if that doesn't reveal anything, post it. I was just enabling this on a test ASP.NET site I was working on, and it works.

CVertex,请务必检查您的代码,如果没有透露任何内容,请发布。我只是在我正在研究的测试ASP.NET网站上启用它,它可以工作。

Actually, at some point I had an issue on my code. I didn't spot it until I had a simpler version on a console program and saw it was working (no change on the Gmail side as you were worried about). The below code works just like the samples you referred to:

实际上,在某些时候我的代码存在问题。我没有发现它,直到我在控制台程序上有一个更简单的版本,并看到它正在工作(在你担心的Gmail方面没有变化)。以下代码的工作方式与您引用的示例类似:

using System;using System.Collections.Generic;using System.Linq;using System.Text;using System.Net.Mail;using System.Net;namespace ConsoleApplication2{    class Program    {        static void Main(string[] args)        {            var client = new SmtpClient("smtp.gmail.com", 587)            {                Credentials = new NetworkCredential("myusername@gmail.com", "mypwd"),                EnableSsl = true            };            client.Send("myusername@gmail.com", "myusername@gmail.com", "test", "testbody");            Console.WriteLine("Sent");            Console.ReadLine();        }    }}

I also got it working using a combination of web.config, http://msdn.microsoft.com/en-us/library/w355a94k.aspx and code (because there is no matching EnableSsl in the configuration file :( ).

我也使用web.config,http://msdn.microsoft.com/en-us/library/w355a94k.aspx和代码的组合工作(因为配置文件中没有匹配的EnableSsl :()。

#2


64  

THE FOLLOWING WILL ALMOST CERTAINLY BE THE ANSWER TO YOUR QUESTION IF ALL ELSE HAS FAILED:

如果所有人都失败了,以下几乎可以回答你的问题:

I got the exact same error, it turns out Google's new password strengh measuring algorithm has changed deeming my current password as too weak, and not telling me a thing about it (not even a message or warning)... How did I discover this? Well, I chose to change my password to see if it would help (tried everything else to no avail) and when I changed my password, it worked!

我得到了完全相同的错误,事实证明谷歌的新密码强度测量算法已经改变,认为我当前的密码太弱,并没有告诉我一件事情(甚至没有消息或警告)......我怎么发现这个?好吧,我选择更改我的密码,看看它是否会有所帮助(尝试其他一切无济于事),当我更改密码时,它有效!

Then, for an experiment, I tried changing my password back to my previous password to see what would happen, and Gmail didn't actually allow me to do this, citing the reason "sorry we cannot allow you to save this change as your chosen password is too weak" and wouldn't let me go back to my old password. I figured from this that it was erroring out because either a) you need to change your password once every x amount of months or b). as I said before, their password strength algorithms changed and therefore the weak password i had was not accepted, even though they did not say anything about this when trying to login ANYWHERE! This (number 2) is the most likely scenario, as my weak password was about 4 months old, and it let me use it in Gmail.

然后,为了进行实验,我尝试将密码更改回以前的密码以查看会发生什么,并且Gmail实际上不允许我这样做,理由是“抱歉我们不能允许您保存此更改作为您选择的密码太弱了“并且不会让我回到我的旧密码。我认为这是错误的,因为a)你需要每x个月或b)更改一次密码。正如我之前所说,他们的密码强度算法发生了变化,因此我所接受的弱密码未被接受,即使他们在尝试登录时没有说出任何相关信息!这个(数字2)是最可能的情况,因为我的弱密码大约是4个月,它让我在Gmail中使用它。

It's pretty bad that they said nothing about this, but it makes sense. Because most hijacked emails are logged into using software outside of gmail, and I'm guessing you are required to have a stronger password if you want to use Gmail outside of the Gmail environment.

他们对此没有任何说法,这是非常糟糕的,但这是有道理的。因为大多数被劫持的电子邮件是使用gmail以外的软件登录的,我猜你要在Gmail环境之外使用Gmail时需要更强的密码。

I hope this helps!

我希望这有帮助!

#3


59  

In addition to the other troubleshooting steps above, I would also like to add that if you have enabled two-factor authentication (also known as two-step verification) on your GMail account, you must generate an application-specific password and use that newly generated password to authenticate via SMTP.

除了上面的其他疑难解答步骤之外,我还想补充一点,如果您在GMail帐户上启用了双因素身份验证(也称为两步验证),则必须生成应用程序专用密码并使用新密码生成密码以通过SMTP进行身份验证。

To create one, visit: https://www.google.com/settings/ and choose Authorizing applications & sites to generate the password.

要创建一个,请访问:https://www.google.com/settings/并选择授权应用程序和网站以生成密码。

#4


43  

Turn On Access For Less Secure Apps and it will work for all no need to change password.

Link to Gmail Setting

链接到Gmail设置

使用C#通过Gmail SMTP服务器发送电子邮件

#5


28  

I've had some problems sending emails from my gmail account too, which were due to several of the aforementioned situations.Here's a summary of how I got it working, and keeping it flexible at the same time:

我在从我的Gmail帐户发送电子邮件时遇到了一些问题,这是由于上述几种情况造成的。这是我如何使其工作的总结,同时保持灵活性:

  • First of all setup your GMail account:
    • Enable IMAP and assert the right maximum number of messages (you can do so here)
    • 启用IMAP并断言正确的最大消息数(您可以在此处执行此操作)

    • Make sure your password is at least 7 characters and is strong (according to Google)
    • 确保您的密码至少为7个字符并且非常强大(根据Google)

    • Make sure you don't have to enter a captcha code first. You can do so by sending a test email from your browser.
    • 确保您不必先输入验证码。您可以通过从浏览器发送测试电子邮件来完成此操作。

  • 首先设置您的GMail帐户:启用IMAP并声明正确的最大邮件数量(您可以在此处执行此操作)确保您的密码至少为7个字符并且非常强大(根据Google)确保您不必首先输入验证码。您可以通过从浏览器发送测试电子邮件来完成此操作。

  • Make changes in web.config (or app.config, I haven't tried that yet but I assume it's just as easy to make it work in a windows application):
  • 在web.config(或app.config中进行更改,我还没有尝试过,但我认为在Windows应用程序中使它工作一样容易):

<configuration>    <appSettings>        <add key="EnableSSLOnMail" value="True"/>       </appSettings>    <!-- other settings -->     ...    <!-- system.net settings -->    <system.net>        <mailSettings>            <smtp from="yourusername@gmail.com" deliveryMethod="Network">                <network                     defaultCredentials="false"                     host="smtp.gmail.com"                     port="587"                     password="stR0ngPassW0rd"                     userName="yourusername@gmail.com"                    />                <!-- When using .Net 4.0 (or later) add attribute: enableSsl="true" and you're all set-->            </smtp>        </mailSettings>    </system.net></configuration>
Add a Class to your project:Imports System.Net.MailPublic Class SSLMail    Public Shared Sub SendMail(ByVal e As System.Web.UI.WebControls.MailMessageEventArgs)        GetSmtpClient.Send(e.Message)        'Since the message is sent here, set cancel=true so the original SmtpClient will not try to send the message too:        e.Cancel = True    End Sub    Public Shared Sub SendMail(ByVal Msg As MailMessage)        GetSmtpClient.Send(Msg)    End Sub    Public Shared Function GetSmtpClient() As SmtpClient        Dim smtp As New Net.Mail.SmtpClient        'Read EnableSSL setting from web.config        smtp.EnableSsl = CBool(ConfigurationManager.AppSettings("EnableSSLOnMail"))        Return smtp    End FunctionEnd Class

And now whenever you want to send emails all you need to do is call SSLMail.SendMail:

现在,无论何时您想发送电子邮件,您只需要调用SSLMail.SendMail:

e.g. in a Page with a PasswordRecovery control:

例如在具有PasswordRecovery控件的页面中:

Partial Class RecoverPasswordInherits System.Web.UI.PageProtected Sub RecoverPwd_SendingMail(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.MailMessageEventArgs) Handles RecoverPwd.SendingMail    e.Message.Bcc.Add("webmaster@example.com")    SSLMail.SendMail(e)End SubEnd Class

Or anywhere in your code you can call:

或者您可以在代码中的任何地方致电:

SSLMail.SendMail(New system.Net.Mail.MailMessage("from@from.com","to@to.com", "Subject", "Body"})

I hope this helps anyone who runs into this post! (I used VB.NET but I think it's trivial to convert it to any .NET language.)

我希望这有助于任何遇到这篇文章的人! (我使用VB.NET,但我认为将它转换为任何.NET语言都是微不足道的。)

#6


13  

Dim SMTPClientObj As New Net.Mail.SmtpClientSMTPClientObj.UseDefaultCredentials = FalseSMTPClientObj.Credentials = New System.Net.NetworkCredential("myusername@gmail.com", "mypwd")SMTPClientObj.Host = "smtp.gmail.com"SMTPClientObj.Port = 587SMTPClientObj.EnableSsl = TrueSMTPClientObj.Send("myusername@gmail.com","yourusername@gmail.com","test","testbody")

If you get an error like "The SMTP server requires a secure connection or the client was not authenticated. The server response was: 5.5.1 Authentication Required. Learn more at" as I get before this, make sure the line SMTPClientObj.UseDefaultCredentials = False included and this line should before the SMTPClientObj.Credentials.

如果您收到类似“SMTP服务器需要安全连接或客户端未通过身份验证的错误。服务器响应为:5.5.1需要身份验证。了解更多信息”,如前所述,请确保SMTPClientObj.UseDefaultCredentials =包含False,此行应在SMTPClientObj.Credentials之前。

I did try to switch these 2 lines the opposite way and the 5.5.1 Authentication Required error returned.

我确实尝试以相反的方式切换这两行,并返回5.5.1 Authentication Required错误。

#7


12  

Oh...It's amazing...First I Couldn't send an email for any reasons.But after I changed the sequence of these two lines as below, it works perfectly.

哦......真是太棒了......首先我无法发送任何原因的电子邮件。但是在我改变了这两行的顺序后,它完美无缺。

//(1)client.UseDefaultCredentials = true;//(2)client.Credentials = new System.Net.NetworkCredential("username@gmail.com", "password");

Hope this help!!! :)

希望这有帮助!!! :)

#8


9  

The problem is not one of technical ability to send through gmail. That works for most situations. If you can't get a machine to send, it is usually due to the machine not having been authenticated with a human at the controls at least once.

问题不在于通过gmail发送技术能力。这适用于大多数情况。如果您无法让机器发送,通常是由于机器未在控件上至少进行过一次人工认证。

The problem that most users face is that Google decides to change the outbound limits all the time. You should always add defensive code to your solution. If you start seeing errors, step off your send speed and just stop sending for a while. If you keep trying to send Google will sometimes add extra time to your delay period before you can send again.

大多数用户面临的问题是Google决定始终更改出站限额。您应该始终为您的解决方案添加防御性代码。如果您开始看到错误,请退出发送速度并停止发送一段时间。如果您一直试图发送Google,有时会在延迟期间增加额外的时间,然后再发送。

What I have done in my current system is to send with a 1.5 second delay between each message. Then if I get any errors, stop for 5 minutes and then start again. This usually works and will allow you to send up to the limits of the account (last I checked it was 2,000 for premier customer logins per day).

我在当前系统中所做的是在每条消息之间发送1.5秒的延迟。然后,如果我收到任何错误,请停止5分钟,然后重新开始。这通常有效,并且允许您发送帐户的限制(最后我检查它是每天首要客户登录的2,000)。

#9


9  

I had the same problem, but it turned out to be my virus protection was blocking outgoing "spam" email. Turning this off allowed me to use port 587 to send SMTP email via GMail

我遇到了同样的问题,但结果是我的病毒防护阻止了传出的“垃圾邮件”电子邮件。关闭它允许我使用端口587通过GMail发送SMTP电子邮件

#10


9  

Simple steps to fix this:

解决这个问题的简单步骤:

1)Sign in to your Gmail

1)登录您的Gmail

2)Navigate to this page https://www.google.com/settings/security/lesssecureapps & set to "Turn On"

2)导航到此页面https://www.google.com/settings/security/lesssecureapps并设置为“开启”

#11


8  

I'm not sure which .NET version is required for this because eglasius mentioned there is no matching enableSsl setting (I'm using .NET 4.0, but I suspect it to work in .NET 2.0 or later), but this configuration justed worked for me (and doesn't require you to use any programmatic configuration):

我不确定这需要哪个.NET版本,因为eglasius提到没有匹配的enableSsl设置(我使用的是.NET 4.0,但我怀疑它可以在.NET 2.0或更高版本中运行),但这个配置值得一试对我来说(并且不要求你使用任何程序化配置):

<system.net>  <mailSettings>    <smtp from="myusername@gmail.com" deliveryMethod="Network">      <network defaultCredentials="false" enableSsl="true" host="smtp.gmail.com" port="587" password="password" userName="myusername@gmail.com"/>    </smtp>  </mailSettings></system.net>

You might have to enable POP or IMAP on your Gmail account first:https://mail.google.com/mail/?shva=1#settings/fwdandpop

您可能必须先在Gmail帐户中启用POP或IMAP:https://mail.google.com/mail/?shva = 1#settings / fwdandpop

I recommend trying it with a normal mail client first...

我建议先用普通邮件客户端尝试...

#12


8  

If nothing else has worked here for you you may need to allow access to your gmail account from third party applications. This was my problem. To allow access do the following:

如果此处没有其他任何工作,您可能需要允许从第三方应用程序访问您的Gmail帐户。这是我的问题。要允许访问,请执行以下操作:

  1. Sign in to your gmail account.
  2. 登录您的Gmail帐户。

  3. Visit this page https://accounts.google.com/DisplayUnlockCaptcha and click on button to allow access.
  4. 访问此页面https://accounts.google.com/DisplayUnlockCaptcha并单击按钮以允许访问。

  5. Visit this page https://www.google.com/settings/security/lesssecureapps and enable access for less secure apps.
  6. 访问此页面https://www.google.com/settings/security/lesssecureapps并启用对安全性较低的应用的访问权限。

This worked for me hope it works for someone else!

这对我有用,希望它适用于其他人!

#13


6  

@Andres Pompiglio: Yes that's right you must change your password at least once..this codes works just fine:

@Andres Pompiglio:是的,你必须至少更改一次密码..这个代码工作得很好:

//Satrt Send Email Functionpublic string SendMail(string toList, string from, string ccList,    string subject, string body){    MailMessage message = new MailMessage();    SmtpClient smtpClient = new SmtpClient();    string msg = string.Empty;    try    {        MailAddress fromAddress = new MailAddress(from);        message.From = fromAddress;        message.To.Add(toList);        if (ccList != null && ccList != string.Empty)            message.CC.Add(ccList);        message.Subject = subject;        message.IsBodyHtml = true;        message.Body = body;        // We use gmail as our smtp client        smtpClient.Host = "smtp.gmail.com";           smtpClient.Port = 587;        smtpClient.EnableSsl = true;        smtpClient.UseDefaultCredentials = true;        smtpClient.Credentials = new System.Net.NetworkCredential(            "Your Gmail User Name", "Your Gmail Password");        smtpClient.Send(message);        msg = "Successful<BR>";    }    catch (Exception ex)    {        msg = ex.Message;    }    return msg;}//End Send Email Function

AND you can make a call to the function by using:

您可以使用以下方法调用该函数:

Response.Write(SendMail(recipient Address, "UserName@gmail.com", "ccList if any", "subject", "body"))

#14


5  

I also found that the account I used to log in was de-activated by google for some reason. Once I reset my password (to the same as it used to be), then I was able to send emails just fine. I was getting 5.5.1 message also.

我还发现,由于某种原因,我以前登录的帐户已被谷歌取消激活。一旦我重置密码(与以前一样),我就可以发送电子邮件了。我也收到5.5.1消息。

#15


5  

I had also try to many solution but make some changes it will work

我也试过很多解决方案,但做一些改变它会起作用

host = smtp.gmail.comport = 587username = email@gmail.compassword = passwordenabledssl = true

with smtpclient above parameters are work in gmail

使用smtpclient以上参数在gmail中工作

#16


5  

I was using corporate VPN connection. It was the reason why I couldn't send email from my application. It works if I disconnect from VPN.

我正在使用企业VPN连接。这就是我无法从我的应用程序发送电子邮件的原因。如果我从VPN断开连接,它会工作。

#17


4  

I ran into this same error ( "The SMTP server requires a secure connection or the client was not authenticated. The server response was: 5.5.1 Authentication Required. Learn more at" ) and found out that I was using the wrong password. I fixed the login credentials, and it sent correctly.

我遇到了同样的错误(“SMTP服务器需要安全连接或客户端未经过身份验证。服务器响应是:5.5.1需要身份验证。了解更多信息”)并发现我使用了错误的密码。我修复了登录凭据,并正确发送。

I know this is late, but maybe this will help someone else.

我知道这已经很晚了,但也许这会帮助别人。

#18


4  

Another thing that I've found is that you must change your password at least once.And try to use a secure level password (do not use the same user as password, 123456, etc.)

我发现的另一件事是你必须至少更改一次密码。并尝试使用安全级密码(不要使用相同的用户密码,123456等)

#19


4  

I was getting the same error and none of the above solutions helped.

我得到了同样的错误,上述解决方案都没有帮助。

My problem was that I was running the code from a remote server, which had never been used to log into the gmail account.

我的问题是我从远程服务器运行代码,该服务器从未用于登录gmail帐户。

I opened a browser on the remote server and logged into gmail from there. It asked a security question to verify it was me since this was a new location. After doing the security check I was able to authenticate through code.

我在远程服务器上打开了一个浏览器并从那里登录到了gmail。它问了一个安全问题,以确认这是我,因为这是一个新的位置。在进行安全检查后,我能够通过代码进行身份验证。

#20


4  

Yet another possible solution for you. I was having similar problems connecting to gmail via IMAP. After trying all the solutions that I came across that you will read about here and elsewhere on SO (eg. enable IMAP, enable less secure access to your mail, using https://accounts.google.com/b/0/displayunlockcaptcha and so on), I actually set up a new gmail account once more.

另一种可能的解决方案。我在通过IMAP连接到gmail时遇到了类似的问题。在尝试了我遇到的所有解决方案之后,您将在此处和其他地方阅读有关SO的信息(例如,启用IMAP,使用https://accounts.google.com/b/0/displayunlockcaptcha启用对邮件的安全性较低的访问权限所以,我实际上再次建立了一个新的Gmail帐户。

In my original test, the first gmail account I had created, I had connected to my main gmail account. This resulted in erratic behaviour where the wrong account was being referenced by google. For example, running https://accounts.google.com/b/0/displayunlockcaptcha opened up my main account rather than the one I had created for the purpose.

在我原来的测试中,我创建的第一个gmail帐户,我已经连接到我的主要Gmail帐户。这导致了谷歌引用错误帐户的不稳定行为。例如,运行https://accounts.google.com/b/0/displayunlockcaptcha会打开我的主帐户,而不是我为此目的创建的帐户。

So when I created a new account and did not connect it to my main account, after following all the appropriate steps as above, I found that it worked fine!

因此,当我创建一个新帐户并且未将其连接到我的主帐户时,在按照上述所有相应步骤操作后,我发现它工作正常!

I haven't yet confirmed this (ie. reproduced), but it apparently did it for me...hope it helps.

我还没有证实这一点(即转载),但它显然是为我做的...希望它有所帮助。

#21


4  

Turn on less secure apps for your account: https://www.google.com/settings/security/lesssecureapps

为您的帐户开启安全性较低的应用:https://www.google.com/settings/security/lesssecureapps

#22


4  

  1. First check your gmail account setting & turn On from "Access for less secure apps"使用C#通过Gmail SMTP服务器发送电子邮件
  2. 首先检查您的Gmail帐户设置,然后从“访问安全性较低的应用”开启

We strongly recommend that you use a secure app, like Gmail, to access your account. All apps made by Google meet these security standards. Using a less secure app, on the other hand, could leave your account vulnerable. Learn more.

我们强烈建议您使用Gmail等安全应用访问您的帐户。 Google生产的所有应用均符合这些安全标准。另一方面,使用安全性较低的应用可能会使您的帐户容易受到攻击。学到更多。

  1. Set

    smtp.UseDefaultCredentials = false;

    before

    smtp.Credentials = new NetworkCredential(fromAddress, fromPassword);
  2. 设置smtp.UseDefaultCredentials = false;在smtp.Credentials = new NetworkCredential(fromAddress,fromPassword)之前;

#23


3  

You can also connect via port 465, but due to some limitations of the System.Net.Mail namespace you may have to alter your code. This is because the namespace does not offer the ability to make implicit SSL connections. This is discussed at http://blogs.msdn.com/b/webdav_101/archive/2008/06/02/system-net-mail-with-ssl-to-authenticate-against-port-465.aspx, and I have supplied an example of how to use the CDO (Collaborative Data Object) in another discussion (GMail SMTP via C# .Net errors on all ports).

您也可以通过端口465进行连接,但由于System.Net.Mail命名空间的某些限制,您可能需要更改代码。这是因为命名空间不提供进行隐式SSL连接的能力。这在http://blogs.msdn.com/b/webdav_101/archive/2008/06/02/system-net-mail-with-ssl-to-authenticate-against-port-465.aspx上讨论,我提供了一个如何在另一个讨论中使用CDO(协作数据对象)的示例(GMail SMTP通过所有端口上的C#.Net错误)。

#24


3  

I had this problem resolved. Aparently that message is used in multiple error types.My problem was that i had reached my maximum of 500 sent mails.

我解决了这个问题。显然,该消息用于多种错误类型。我的问题是我已经达到了最多500封已发送的邮件。

log into the account and manually try to send a mail. If the limit has been reached it will inform you

登录帐户并手动尝试发送邮件。如果达到限制,它将通知您

#25


2  

One or more reasons are there for these error.

出现这些错误的原因有一个或多个。

  • Log in with your Gmail( or any other if ) in your local system.

    使用您本地系统中的Gmail(或任何其他if)登录。

  • Also check for Less Secure App and Set it to "Turn On" here is the Link for GMAIL.https://www.google.com/settings/security/lesssecureapps

    同时检查不太安全的应用程序并将其设置为“打开”这里是GMAIL的链接.https://www.google.com/settings/security/lesssecureapps

  • check for EnableSsl in your Email code, and also set it to true.

    检查电子邮件代码中的EnableSsl,并将其设置为true。

    smtp.EnableSsl = true;
  • Also check which port are you using currently. 25 is Global, but you can check it for others too like 587. check here. Does all SMTP communication happen over 25?

    还要检查您当前使用的是哪个端口。 25是全球,但你也可以像587一样检查其他人。点击这里。所有SMTP通信都发生在25以上吗?

  • IF YOU ARE ON REMOTE : Check the answer of Vlad Tamas above.

    如果你在远程:检查上面的Vlad Tamas的答案。

#26


2  

  smtp.Host = "smtp.gmail.com"; //host name    smtp.Port = 587; //port number    smtp.EnableSsl = true; //whether your smtp server requires SSL    smtp.DeliveryMethod = System.Net.Mail.SmtpDeliveryMethod.Network;    smtp.Credentials = new NetworkCredential(fromAddress, fromPassword);    smtp.Timeout = 20000;

#27


1  

Change your gmail password and try again, it should work after that.

更改您的Gmail密码并重试,之后应该可以使用。

Don't know why, but every time you change your hosting you have to change your password.

不知道为什么,但每次更改主机时都必须更改密码。