c# SmtpClient 类无法使用 gmail 发送电子邮件
Posted
技术标签:
【中文标题】c# SmtpClient 类无法使用 gmail 发送电子邮件【英文标题】:c# SmtpClient class not able to send email using gmail 【发布时间】:2010-11-21 15:45:28 【问题描述】:我在使用我的 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()
【问题讨论】:
【参考方案1】:*** said before
在您的情况下,这意味着您必须使用您登录 Google 时使用的电子邮件地址发送。
*** also says
所以可能有防火墙干扰了连接。我现在在测试您的代码时遇到了这个问题。尝试建议的 TELNET-Test。
【讨论】:
【参考方案2】:你不会相信是什么解决了我的问题。
凭据属性
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);
这是一个错误吗?
【讨论】:
我会说不,因为当我更改为 UseDefaultCredentials = true 时,我希望任何现有的凭据都被覆盖。 Kenny,您需要以正确的顺序声明属性似乎有点违反直觉。 遇到同样的错误,必须先设置 UseDefaultCredentials 才能使用 Credentials 属性。有点违反直觉,属性不应该依赖于顺序 @VincePanuccio 我检查了使用反射器的情况。设置 ss.UseDefaultCredentials = false 本质上是将 Credentials 重置为 null。这就是你遇到麻烦的原因。但这也意味着 ss.UseDefaultCredentials = false 根本没有必要,它最终什么也没做 你为什么在 int 上使用 Convert.ToInt32?【参考方案3】:我可以验证必须在创建 NetworkCredentials 之前将 UseDefaultCredentials 设置为 false。我遇到了同样的问题。
【讨论】:
【参考方案4】:仅使用端口 25 为我工作。
【讨论】:
【参考方案5】:这可行,但对性能不太友好。查看 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);
【讨论】:
【参考方案6】:在我的情况下效果很好:
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;
【讨论】:
【参考方案7】:这项工作非常完美。
在单独的文件 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>
【讨论】:
以上是关于c# SmtpClient 类无法使用 gmail 发送电子邮件的主要内容,如果未能解决你的问题,请参考以下文章