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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/704636/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-04 14:07:17  来源:igfitidea点击:

Sending email through Gmail SMTP server with C#

c#.netemailsmtpgmail

提问by CVertex

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(message) 上收到一个 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。

采纳答案by eglasius

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("[email protected]", "mypwd"),
                EnableSsl = true
            };
            client.Send("[email protected]", "[email protected]", "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.aspxand code (because there is no matching EnableSslin the configuration file :( ).

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

回答by Jason Short

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 有时会在您再次发送之前增加延迟时间。

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 次高级客户登录)。

回答by Jason Short

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 等)

回答by Albert Bori

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.

我知道这已经晚了,但也许这会对其他人有所帮助。

回答by Wiebe Tijsma

I'm not sure which .NET version is required for this because eglasius mentioned there is no matching enableSslsetting (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="[email protected]" deliveryMethod="Network">
      <network defaultCredentials="false" enableSsl="true" host="smtp.gmail.com" port="587" password="password" userName="[email protected]"/>
    </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...

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

回答by Terry Chng

Dim SMTPClientObj As New Net.Mail.SmtpClient
SMTPClientObj.UseDefaultCredentials = False
SMTPClientObj.Credentials = New System.Net.NetworkCredential("[email protected]", "mypwd")
SMTPClientObj.Host = "smtp.gmail.com"
SMTPClientObj.Port = 587
SMTPClientObj.EnableSsl = True
SMTPClientObj.Send("[email protected]","[email protected]","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 = Falseincluded 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 errorreturned.

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

回答by user464329

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 电子邮件

回答by Bryan Allred

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 via C# .Net errors on all ports)。

回答by maxcoder

@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, "[email protected]", "ccList if any", "subject", "body"))

回答by RKL

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 消息。