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

时间:2022-11-15 10:53:13

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的代码时。在网络上,我很快就收到了发送(消息)的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.

我在这篇文章和其他电子邮件发件人项目中采纳了一些想法,在Codeplex上创建一个电子邮件发件人项目。它是为可测试性而设计的,支持我最喜欢的SMTP服务,如GoDaddy和Gmail。

27 个解决方案

#1


263  

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的组合。配置,http://msdn.microsoft.com/en-us/library/w355a94k.aspx和代码(因为配置文件中没有匹配的EnableSsl:()。

#2


63  

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实际上并没有允许我这样做,原因为由“对不起我们不能允许你保存这一变化为您选择的密码太弱”,不让我回到我的旧密码。我想从这是错误,因为一个)你需要改变你的密码一次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


58  

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


41  

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个字符,并且是强的(根据谷歌)
    • 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个字符,并且是强的(根据谷歌),确保您不必首先输入验证码。您可以通过从浏览器发送测试电子邮件来实现这一点。
  • 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):
  • 在网络进行更改。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.Mail

Public 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 Function

End 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:

在有密码控制的页面:

Partial Class RecoverPassword
Inherits System.Web.UI.Page

Protected 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 Sub

End 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语言都是很简单的。

#6


13  

Dim SMTPClientObj As New Net.Mail.SmtpClient
SMTPClientObj.UseDefaultCredentials = False
SMTPClientObj.Credentials = New System.Net.NetworkCredential("myusername@gmail.com", "mypwd")
SMTPClientObj.Host = "smtp.gmail.com"
SMTPClientObj.Port = 587
SMTPClientObj.EnableSsl = True
SMTPClientObj.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 .凭证之前。

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

我确实尝试将这两行转换成相反的方式,5.5.1验证所要求的错误返回。

#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.

大多数用户面临的问题是谷歌决定一直更改出站限制。您应该始终在解决方案中添加防御性代码。如果您开始看到错误,请停止发送速度,暂时停止发送。如果您一直尝试发送谷歌,那么在您再次发送之前,有时会添加额外的时间到您的延迟期。

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分钟,然后重新开始。这通常是有效的,并且允许您发送到帐户的限制(上次我检查的是,主要客户每天登录2000次)。

#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


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...

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

#11


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!

这对我有用,希望对别人有用!

#12


8  

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并设置为“打开”

#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 Function
public 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.com
port = 587
username = email@gmail.com
password = password
enabledssl = 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时遇到了类似的问题。在尝试了我遇到的所有解决方案之后,你将在这里和其他地方读到。启用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  

  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来访问您的帐户。谷歌生产的所有应用程序都符合这些安全标准。另一方面,使用不那么安全的应用程序可能会让你的账户变得脆弱。学习更多的知识。

  1. Set

    smtp.UseDefaultCredentials = false;
    

    before

    之前

    smtp.Credentials = new NetworkCredential(fromAddress, fromPassword);
    

#22


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的一些限制。可能需要更改代码的邮件名称空间。这是因为命名空间不提供生成隐式SSL连接的能力。这在http://blogs.msdn.com/b/webdav_101/archive/2008/06/02/system-net-mail-with- sslto -authenticate- port-465.aspx中得到了讨论,我还提供了一个示例,说明如何在另一个讨论(通过c# . net错误在所有端口上使用CDO(协作数据对象))。

#23


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

登录帐户并手动尝试发送邮件。如果超过了限度,就会通知你

#24


3  

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

为你的账户打开不那么安全的应用:https://www.google.com/settings/security/lesssecureapps

#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


263  

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的组合。配置,http://msdn.microsoft.com/en-us/library/w355a94k.aspx和代码(因为配置文件中没有匹配的EnableSsl:()。

#2


63  

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实际上并没有允许我这样做,原因为由“对不起我们不能允许你保存这一变化为您选择的密码太弱”,不让我回到我的旧密码。我想从这是错误,因为一个)你需要改变你的密码一次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


58  

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


41  

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个字符,并且是强的(根据谷歌)
    • 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个字符,并且是强的(根据谷歌),确保您不必首先输入验证码。您可以通过从浏览器发送测试电子邮件来实现这一点。
  • 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):
  • 在网络进行更改。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.Mail

Public 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 Function

End 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:

在有密码控制的页面:

Partial Class RecoverPassword
Inherits System.Web.UI.Page

Protected 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 Sub

End 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语言都是很简单的。

#6


13  

Dim SMTPClientObj As New Net.Mail.SmtpClient
SMTPClientObj.UseDefaultCredentials = False
SMTPClientObj.Credentials = New System.Net.NetworkCredential("myusername@gmail.com", "mypwd")
SMTPClientObj.Host = "smtp.gmail.com"
SMTPClientObj.Port = 587
SMTPClientObj.EnableSsl = True
SMTPClientObj.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 .凭证之前。

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

我确实尝试将这两行转换成相反的方式,5.5.1验证所要求的错误返回。

#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.

大多数用户面临的问题是谷歌决定一直更改出站限制。您应该始终在解决方案中添加防御性代码。如果您开始看到错误,请停止发送速度,暂时停止发送。如果您一直尝试发送谷歌,那么在您再次发送之前,有时会添加额外的时间到您的延迟期。

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分钟,然后重新开始。这通常是有效的,并且允许您发送到帐户的限制(上次我检查的是,主要客户每天登录2000次)。

#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


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...

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

#11


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!

这对我有用,希望对别人有用!

#12


8  

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并设置为“打开”

#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 Function
public 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.com
port = 587
username = email@gmail.com
password = password
enabledssl = 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时遇到了类似的问题。在尝试了我遇到的所有解决方案之后,你将在这里和其他地方读到。启用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  

  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来访问您的帐户。谷歌生产的所有应用程序都符合这些安全标准。另一方面,使用不那么安全的应用程序可能会让你的账户变得脆弱。学习更多的知识。

  1. Set

    smtp.UseDefaultCredentials = false;
    

    before

    之前

    smtp.Credentials = new NetworkCredential(fromAddress, fromPassword);
    

#22


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的一些限制。可能需要更改代码的邮件名称空间。这是因为命名空间不提供生成隐式SSL连接的能力。这在http://blogs.msdn.com/b/webdav_101/archive/2008/06/02/system-net-mail-with- sslto -authenticate- port-465.aspx中得到了讨论,我还提供了一个示例,说明如何在另一个讨论(通过c# . net错误在所有端口上使用CDO(协作数据对象))。

#23


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

登录帐户并手动尝试发送邮件。如果超过了限度,就会通知你

#24


3  

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

为你的账户打开不那么安全的应用:https://www.google.com/settings/security/lesssecureapps

#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.

不知道为什么,但每次你改变你的主机,你必须改变你的密码。