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

时间:2009-08-21 12:51:46

标签: c# gmail smtpclient

我无法使用我的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("donotreply@domain.com", "destination@domain.com", "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()

7 个答案:

答案 0 :(得分:60)

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

凭据属性

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

这是一个错误吗?

答案 1 :(得分:5)

Stackoverflow said before

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

Stackoverflow also says

因此,可能存在干扰连接的防火墙。我正在测试你的代码时遇到这个问题。尝试建议的TELNET测试。

答案 2 :(得分:2)

仅使用端口25为我工作。

答案 3 :(得分:1)

这有效,但它不是非常友好。查看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);

答案 4 :(得分:1)

这项工作非常完美。 在单独的文件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 = "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

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

答案 5 :(得分:0)

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

答案 6 :(得分:0)

在我的情况下运作正常:

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@domain.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;
}