c#SmtpClient类不能使用Gmail发送电子邮件
我无法使用我的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服务器需要一个安全的连接,或者客户端没有被authentication,服务器的响应是:5.5.1需要authentication。
inheritance人堆栈跟踪
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()
你不会相信什么解决了我的问题。
凭证属性
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);
这是一个错误?
Stackoverflow之前说过
在你的情况下,这意味着你必须发送与您login到谷歌的电子邮件地址。
Stackoverflow也说
所以也许有一个干扰连接的防火墙。 我在testing代码的时候遇到了这个问题。 尝试build议的TELNETtesting。
只为港口工作25。
这工作,但它不是很友善的performance。 查看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);
这项工作是完美的。 在单独的文件MailTemplate.html
创build邮件模板。
添加正版NetworkCredentials – login名和密码
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>
我可以validation设置UseDefaultCredentials为false务必在创buildNetworkCredentials之前完成。 我有同样的问题。
它在我的情况下工作正常:
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; }