C# SmtpClient 类无法使用 gmail 发送电子邮件

发布于 2024-08-02 17:16:55 字数 2042 浏览 6 评论 0原文

我在使用 Gmail 帐户发送电子邮件时遇到问题。我正在拔头发。

相同的设置在 Thunderbird 中运行良好。

这是代码。我也尝试过 465 端口,但没有成功。

SmtpClient ss = new SmtpClient("smtp.gmail.com", 587);
ss.Credentials = new NetworkCredential("username", "pass");
ss.EnableSsl = true;
ss.Timeout = 10000;
ss.DeliveryMethod = SmtpDeliveryMethod.Network;
ss.UseDefaultCredentials = false;

MailMessage mm = new MailMessage("[email protected]", "[email protected]", "subject here", "my body");
mm.BodyEncoding = UTF8Encoding.UTF8;
mm.DeliveryNotificationOptions = DeliveryNotificationOptions.OnFailure;
ss.Send(mm);

这是错误

SMTP 服务器需要安全连接,或者客户端未经过身份验证。服务器响应是:5.5.1 需要身份验证。了解更多信息

这里是堆栈跟踪

   at System.Net.Mail.MailCommand.CheckResponse(SmtpStatusCode statusCode, String response)
   at System.Net.Mail.MailCommand.Send(SmtpConnection conn, Byte[] command, String from)
   at System.Net.Mail.SmtpTransport.SendMail(MailAddress sender, MailAddressCollection recipients, String deliveryNotify, SmtpFailedRecipientException& exception)
   at System.Net.Mail.SmtpClient.Send(MailMessage message)
   at email_example.Program.Main(String[] args) in C:\Users\Vince\Documents\Visual Studio 2008\Projects\email example\email example\Program.cs:line 23
   at System.AppDomain._nExecuteAssembly(Assembly assembly, String[] args)
   at System.AppDomain.ExecuteAssembly(String assemblyFile, Evidence assemblySecurity, String[] args)
   at Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssembly()
   at System.Threading.ThreadHelper.ThreadStart_Context(Object state)
   at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
   at System.Threading.ThreadHelper.ThreadStart()

I'm having trouble sending email using my gmail account. I'm pulling my hair out.

The same settings work fine in Thunderbird.

Here's the code. I've also tried port 465 with no luck.

SmtpClient ss = new SmtpClient("smtp.gmail.com", 587);
ss.Credentials = new NetworkCredential("username", "pass");
ss.EnableSsl = true;
ss.Timeout = 10000;
ss.DeliveryMethod = SmtpDeliveryMethod.Network;
ss.UseDefaultCredentials = false;

MailMessage mm = new MailMessage("[email protected]", "[email protected]", "subject here", "my body");
mm.BodyEncoding = UTF8Encoding.UTF8;
mm.DeliveryNotificationOptions = DeliveryNotificationOptions.OnFailure;
ss.Send(mm);

Heres the 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

Here's the stack trace

   at System.Net.Mail.MailCommand.CheckResponse(SmtpStatusCode statusCode, String response)
   at System.Net.Mail.MailCommand.Send(SmtpConnection conn, Byte[] command, String from)
   at System.Net.Mail.SmtpTransport.SendMail(MailAddress sender, MailAddressCollection recipients, String deliveryNotify, SmtpFailedRecipientException& exception)
   at System.Net.Mail.SmtpClient.Send(MailMessage message)
   at email_example.Program.Main(String[] args) in C:\Users\Vince\Documents\Visual Studio 2008\Projects\email example\email example\Program.cs:line 23
   at System.AppDomain._nExecuteAssembly(Assembly assembly, String[] args)
   at System.AppDomain.ExecuteAssembly(String assemblyFile, Evidence assemblySecurity, String[] args)
   at Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssembly()
   at System.Threading.ThreadHelper.ThreadStart_Context(Object state)
   at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
   at System.Threading.ThreadHelper.ThreadStart()

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(7

情泪▽动烟 2024-08-09 17:16:55

你不会相信是什么解决了我的问题。

Credentials 属性

ss.Credentials = new NetworkCredential("username", "pass");

必须在之后声明

ss.UseDefaultCredentials = false;

所以最终的工作代码列表是

SmtpClient ss = new SmtpClient("smtp.gmail.com", 587);
ss.EnableSsl = true;
ss.Timeout = 10000;
ss.DeliveryMethod = SmtpDeliveryMethod.Network;
ss.UseDefaultCredentials = false;
ss.Credentials = new NetworkCredential("username", "pass");

MailMessage mm = new MailMessage("[email protected]", "[email protected]", "subject here", "my body");
mm.BodyEncoding = UTF8Encoding.UTF8;
mm.DeliveryNotificationOptions = DeliveryNotificationOptions.OnFailure;
ss.Send(mm);

这是一个错误吗?

You won't believe what fixed my problem.

The Credentials property

ss.Credentials = new NetworkCredential("username", "pass");

must be declared after

ss.UseDefaultCredentials = false;

So the final working code listing is

SmtpClient ss = new SmtpClient("smtp.gmail.com", 587);
ss.EnableSsl = true;
ss.Timeout = 10000;
ss.DeliveryMethod = SmtpDeliveryMethod.Network;
ss.UseDefaultCredentials = false;
ss.Credentials = new NetworkCredential("username", "pass");

MailMessage mm = new MailMessage("[email protected]", "[email protected]", "subject here", "my body");
mm.BodyEncoding = UTF8Encoding.UTF8;
mm.DeliveryNotificationOptions = DeliveryNotificationOptions.OnFailure;
ss.Send(mm);

Is this a bug?

迟到的我 2024-08-09 17:16:55

Stackoverflow之前说过

在你的情况下,这意味着你必须发送它与您登录 Google 所用的电子邮件地址。

Stackoverflow 还说

所以也许有防火墙干扰与连接。我现在在测试您的代码时遇到这个问题。尝试建议的 TELNET 测试。

Stackoverflow said before

In your case it means you have to send it with the email address you logged into Google with.

Stackoverflow also says

So maybe there's a firewall that interferes with the connection. I'm encountering this problem right now while testing your code. Try the suggested TELNET-Test.

随风而去 2024-08-09 17:16:55

我只使用端口 25 工作。

Work for me only with port 25.

笑红尘 2024-08-09 17:16:55

这可行,但性能不太友好。查看 client.SendAsync:
http://msdn.microsoft.com/en-us/library/x5x13z6h.aspx

一个示例用例:

 var message = new MailMessage("from", "to", "subject", "body");
 var client = new SmtpClient("smtp.gmail.com", 587)
            {
                Credentials = new NetworkCredential("login", "password"),
                EnableSsl = true
            };
            client.SendCompleted += (s, e) =>
            {
                client.Dispose();
                message.Dispose();
            };
            client.SendAsync(message, null);

This works, but it's not very performance friendly. Check out client.SendAsync:
http://msdn.microsoft.com/en-us/library/x5x13z6h.aspx

An example use case:

 var message = new MailMessage("from", "to", "subject", "body");
 var client = new SmtpClient("smtp.gmail.com", 587)
            {
                Credentials = new NetworkCredential("login", "password"),
                EnableSsl = true
            };
            client.SendCompleted += (s, e) =>
            {
                client.Dispose();
                message.Dispose();
            };
            client.SendAsync(message, null);
酒解孤独 2024-08-09 17:16:55

这部作品堪称完美。
在单独的文件 MailTemplate.html 中创建邮件模板。

添加真正的 NetworkCredentials - 登录名和密码

private void SendMail()
    {
    string filename = Server.MapPath("~/MailTemplate.html");
    string username = UserName.Text.ToString();

    string mailbody = System.IO.File.ReadAllText(filename);
    mailbody = mailbody.Replace("##NAME##", username);
    string to = Email.Text;
    string from = "[email protected]";

    MailMessage message = new MailMessage(from, to);
    message.Subject = "Auto Response Email";
    message.Body = mailbody;
    message.BodyEncoding = Encoding.UTF8;
    message.IsBodyHtml = true;
    SmtpClient client = new SmtpClient("smtp.gmail.com", 587);
    System.Net.NetworkCredential basicCredential = new System.Net.NetworkCredential("[email protected]", "test123#");
    client.EnableSsl = true;
    client.UseDefaultCredentials = true;
    client.Credentials = basicCredential;
    try
    {
        client.Send(message);
        SuccessMessage.Text = "Email Sending successfully";

    }
    catch (Exception ex)
    {

        ErrorMessage.Text = ex.Message.ToString();
    }
}

MailTemplate.html

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8" />
    <title>Title</title>
</head>
<body>
    <div style="border: thin solid #0066FF; width: 550px; margin: 25px auto; padding: 15px; font-family: 'Microsoft Himalaya'; font-size: x-large; font-style: normal; color: #0066FF; background-color: #EfEFF2;">
        <br />
        <p style="vertical-align: middle">Dear ##NAME##,</p>
    </div>
</body>
</html>

This work's perfectly.
Create a mail Template in a separate file MailTemplate.html.

Add genuine NetworkCredentials - login and Password

private void SendMail()
    {
    string filename = Server.MapPath("~/MailTemplate.html");
    string username = UserName.Text.ToString();

    string mailbody = System.IO.File.ReadAllText(filename);
    mailbody = mailbody.Replace("##NAME##", username);
    string to = Email.Text;
    string from = "[email protected]";

    MailMessage message = new MailMessage(from, to);
    message.Subject = "Auto Response Email";
    message.Body = mailbody;
    message.BodyEncoding = Encoding.UTF8;
    message.IsBodyHtml = true;
    SmtpClient client = new SmtpClient("smtp.gmail.com", 587);
    System.Net.NetworkCredential basicCredential = new System.Net.NetworkCredential("[email protected]", "test123#");
    client.EnableSsl = true;
    client.UseDefaultCredentials = true;
    client.Credentials = basicCredential;
    try
    {
        client.Send(message);
        SuccessMessage.Text = "Email Sending successfully";

    }
    catch (Exception ex)
    {

        ErrorMessage.Text = ex.Message.ToString();
    }
}

MailTemplate.html

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8" />
    <title>Title</title>
</head>
<body>
    <div style="border: thin solid #0066FF; width: 550px; margin: 25px auto; padding: 15px; font-family: 'Microsoft Himalaya'; font-size: x-large; font-style: normal; color: #0066FF; background-color: #EfEFF2;">
        <br />
        <p style="vertical-align: middle">Dear ##NAME##,</p>
    </div>
</body>
</html>
海螺姑娘 2024-08-09 17:16:55

我可以验证必须在创建 NetworkCredentials 之前将 UseDefaultCredentials 设置为 false 。我也有同样的问题。

I can verify that setting UseDefaultCredentials to false MUST be done before the NetworkCredentials is created. I had the same problem.

风柔一江水 2024-08-09 17:16:55

在我的情况下效果很好:

private void btnTestConnection_Click(object sender, EventArgs e)
     {
    btnTestConnection.Enabled = false;
    SmtpClient ss = new SmtpClient(txtSmtpHostName.Text.Trim(), Convert.ToInt32(numSmtpHostPort.Value));
    ss.EnableSsl = chkSmtpSecureType.Checked;
    ss.Timeout = 10000;
    ss.DeliveryMethod = SmtpDeliveryMethod.Network;
    ss.UseDefaultCredentials = false;
    ss.Credentials = new NetworkCredential(txtSmtpAccount.Text.Trim(), txtSmtpPassword.Text);

    MailMessage mm = new MailMessage(txtSmtpFromEmail.Text.Trim(), "[email protected]", "subject", "my body");
    mm.BodyEncoding = UTF8Encoding.UTF8;
    mm.DeliveryNotificationOptions = DeliveryNotificationOptions.OnFailure;
    ss.SendCompleted += (s, b) =>
    {
        ss.Dispose();
        mm.Dispose();
    };
    try
    {
        ss.Send(mm);
        ss.Dispose();
        mm.Dispose();
        MessageBox.Show("Connection successfully");
    }
    catch (Exception ep)
    {
        MessageBox.Show("Connection error: " + ep.Message, "Smtp Connection Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
    }
    btnTestConnection.Enabled = true;
}

It works fine in my case:

private void btnTestConnection_Click(object sender, EventArgs e)
     {
    btnTestConnection.Enabled = false;
    SmtpClient ss = new SmtpClient(txtSmtpHostName.Text.Trim(), Convert.ToInt32(numSmtpHostPort.Value));
    ss.EnableSsl = chkSmtpSecureType.Checked;
    ss.Timeout = 10000;
    ss.DeliveryMethod = SmtpDeliveryMethod.Network;
    ss.UseDefaultCredentials = false;
    ss.Credentials = new NetworkCredential(txtSmtpAccount.Text.Trim(), txtSmtpPassword.Text);

    MailMessage mm = new MailMessage(txtSmtpFromEmail.Text.Trim(), "[email protected]", "subject", "my body");
    mm.BodyEncoding = UTF8Encoding.UTF8;
    mm.DeliveryNotificationOptions = DeliveryNotificationOptions.OnFailure;
    ss.SendCompleted += (s, b) =>
    {
        ss.Dispose();
        mm.Dispose();
    };
    try
    {
        ss.Send(mm);
        ss.Dispose();
        mm.Dispose();
        MessageBox.Show("Connection successfully");
    }
    catch (Exception ep)
    {
        MessageBox.Show("Connection error: " + ep.Message, "Smtp Connection Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
    }
    btnTestConnection.Enabled = true;
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文