好日子,伙计们, 我有一个代码用于发送带有附件的电子邮件,我从Finding the exact cause for the exception - System.Net.Sockets.SocketException
引用了该附件以下是代码:
namespace SendEmail
{
class Email
{
public static void Main(string[] args)
{
MailMessage mail = new MailMessage();
SmtpClient SmtpServer = new SmtpClient("smtp.gmail.com");
try
{
mail.From = new MailAddress("harish.1138@gmail.com");
mail.To.Add("harish_1138@yahoo.com");
mail.Subject = "Test Mail - 1";
mail.Body = "mail with attachment";
System.Net.Mail.Attachment attachment;
attachment = new System.Net.Mail.Attachment("C:\\EmailTest.xlsx");
mail.Attachments.Add(attachment);
SmtpServer.Port = 587;
SmtpServer.Credentials = new System.Net.NetworkCredential("harish.1138@gmail.com", "SamplePWD");
SmtpServer.EnableSsl = true;
SmtpServer.Send(mail);
MessageBox.Show("Mail Sent");
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
}
}
}
当我执行此操作时,我得到一个例外:
消息=" SMTP服务器需要安全连接或客户端未经过身份验证。服务器响应为:5.5.1需要身份验证。在"
了解详情如何修复身份验证所需的异常。这是否意味着阻止我发送电子邮件?
非常感谢
答案 0 :(得分:0)
抛出此异常,当您无法访问SMTP服务器时。
通常您使用密码和用户名登录电子邮件,当涉及到SMTP服务器请求时,您将IP作为登录凭据发送。
如果您的IP未获得授权,则不会允许您使用该IP并将被阻止。
您需要提供凭据,以覆盖IP身份验证:
SmtpClient SmtpServer = new SmtpClient("smtp.gmail.com");
SmtpServer .Host = "mail.youroutgoingsmtpserver.com";
SmtpServer Credentials = new System.Net.NetworkCredential("yourusername", "yourpassword");
如果它不允许您,则谷歌会阻止您访问。
使用此参考:
答案 1 :(得分:0)
我让它工作...... 这里提到:The SMTP server requires a secure connection or the client was not authenticated. The server response was: 5.5.1 Authentication Required? 正如@ymonad所建议的那样。
namespace SendEmail
{
class Email
{
public static void Main(string[] args)
{
try
{
using (MailMessage mail = new MailMessage())
{
mail.From = new MailAddress("harish.1138@gmail.com");
mail.To.Add("harish_1138@yahoo.com");
mail.Subject = "Test Mail - 1";
mail.Body = "mail with attachment";
System.Net.Mail.Attachment attachment;
attachment = new System.Net.Mail.Attachment("C:\\EmailTest.xlsx");
mail.Attachments.Add(attachment);
using (SmtpClient SmtpServer = new SmtpClient("smtp.gmail.com", 587))
{
SmtpServer.UseDefaultCredentials = false; //Need to overwrite this
SmtpServer.Credentials = new System.Net.NetworkCredential("harish.1138@gmail.com", "SamplePWD");
SmtpServer.EnableSsl = true;
SmtpServer.Send(mail);
}
}
MessageBox.Show("Mail Sent");
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
}
}
}
并且必须打开不太安全的应用程序,如下所示: https://stackoverflow.com/a/38024407/5266708
它完美无缺......