c# SmtpClient 类无法使用 gmail 发送电子邮件
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1311749/
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
c# SmtpClient class not able to send email using gmail
提问by Vince Panuccio
I'm having trouble sending email using my gmail account. Im pulling my hair out.
我在使用 Gmail 帐户发送电子邮件时遇到问题。我把头发拉出来。
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("[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 "
“SMTP 服务器需要安全连接或客户端未通过身份验证。服务器响应为:5.5.1 需要身份验证。了解更多信息”
Heres 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()
采纳答案by Vince Panuccio
You won't belive 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?
这是一个错误吗?
回答by Bdiem
In your case it means you have to send it with the email address you logged into Google with.
在您的情况下,这意味着您必须使用您登录 Google 的电子邮件地址发送它。
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。
回答by Johann Blake
I can verify that setting UseDefaultCredentials to false MUST be done before the NetworkCredentials is created. I had the same problem.
我可以验证必须在创建 NetworkCredentials 之前将 UseDefaultCredentials 设置为 false。我有同样的问题。
回答by karabara
Work for me only with port 25.
仅使用端口 25 为我工作。
回答by Mark Olschesky
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);
回答by Ahosan Karim Asik
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;
}
回答by Shibu Thomas
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 = "[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
邮件模板.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>