简体   繁体   English

C# SmtpClient class 无法使用 ZDE01C1D48DB6C321C6374571ZED8 发送 email

[英]C# SmtpClient class not able to send email using gmail

I'm having trouble sending email using my gmail account.我在使用我的 gmail 帐户发送 email 时遇到问题。 I'm pulling my hair out.我正在拔头发。

The same settings work fine in Thunderbird.相同的设置在 Thunderbird 中运行良好。

Here's the code.这是代码。 I've also tried port 465 with no luck.我也尝试过端口 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("donotreply@example.com", "destination@example.com", "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. SMTP 服务器需要安全连接或客户端未通过身份验证。 The server response was: 5.5.1 Authentication Required.服务器响应为:5.5.1 需要身份验证。 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()

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("donotreply@example.com", "destination@example.com", "subject here", "my body");
mm.BodyEncoding = UTF8Encoding.UTF8;
mm.DeliveryNotificationOptions = DeliveryNotificationOptions.OnFailure;
ss.Send(mm);

Is this a bug?这是一个错误吗?

Stackoverflow said before Stackoverflow 之前说过

In your case it means you have to send it with the email address you logged into Google with.在您的情况下,这意味着您必须使用您登录 Google 时使用的 email 地址发送它。

Stackoverflow also says Stackoverflow 还说

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.尝试建议的 TELNET-Test。

Work for me only with port 25.仅使用端口 25 为我工作。

This works, but it's not very performance friendly.这行得通,但它对性能不是很友好。 Check out client.SendAsync: http://msdn.microsoft.com/en-us/library/x5x13z6h.aspx查看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);

This work's perfectly.这部作品很完美。 Create a mail Template in a separate file MailTemplate.html .在单独的文件MailTemplate.html中创建邮件模板。

Add genuine NetworkCredentials - login and Password添加正版 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 = "test@gmail.com";

    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("test@gmail.com", "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邮件模板.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>

I can verify that setting UseDefaultCredentials to false MUST be done before the NetworkCredentials is created.我可以验证必须在创建 NetworkCredentials 之前将 UseDefaultCredentials 设置为 false。 I had the same problem.我有同样的问题。

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(), "test@example.com", "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;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM