System.Net.Mail.SmtpException {“发送电子邮件失败。”}

时间:2016-07-20 09:29:36

标签: c# wpf system.net.mail

上述错误导致client.Send(email);处的破坏和崩溃。四重检查一切。

这是我的代码:

private void submit_Click(object sender, RoutedEventArgs e)
{
    string from = "************@gmail.com";
    string to = "*******@sru.edu";
    string subject = "PSLM Test";
    string body = "PSLM Test";
    string server = "smtp.gmail.com";
    int port = 465;
    string username = "************";
    string password = "*******";

    SmtpClient client = new SmtpClient(server, port);
    client.Credentials = new NetworkCredential(username, password);

    MailMessage email = new MailMessage(from, to, subject, body);

    email.Attachments.Add(new Attachment(GlobalVariables.attachedFilePath));
    email.Attachments.Add(new Attachment(GlobalVariables.formsAndTemplatesPath[0]));
    email.Attachments.Add(new Attachment(GlobalVariables.formsAndTemplatesPath[1]));
    email.Attachments.Add(new Attachment(GlobalVariables.formsAndTemplatesPath[2]));

    client.Send(email);
}

我做错了什么,拜托?

2 个答案:

答案 0 :(得分:4)

Gmail SMTP端口为587,而不是465.您还需要将SmtpClient.EnableSsl属性设置为true

client.EnableSsl = true;

可能您可能需要在设置新网络凭据之前将client.UseDefaultCredentials设置为false。但情况并非总是如此 - 我所知道的是,当其他选项耗尽时,这往往会起作用。

client.UseDefaultCredentials = false;
client.Credentials = new NetworkCredential(username, password);

由于您使用的是Gmail,因此您需要在Google帐户安全设置中允许安全性较低的应用程序。如果您使用双因素身份验证,则还需要创建特定于应用程序的密码,并在代码中使用该密码。

答案 1 :(得分:-1)

    SmtpClient client= new SmtpClient(server, port);

    client.Credentials = new System.Net.NetworkCredential(username, password);
    client.UseDefaultCredentials = true;
    client.DeliveryMethod = SmtpDeliveryMethod.Network;
    client.EnableSsl = true;

    MailMessage email = new MailMessage(from, to, subject, body);

    email.Attachments.Add(new Attachment(GlobalVariables.attachedFilePath));
    email.Attachments.Add(new Attachment(GlobalVariables.formsAndTemplatesPath[0]));
    email.Attachments.Add(new Attachment(GlobalVariables.formsAndTemplatesPath[1]));
    email.Attachments.Add(new Attachment(GlobalVariables.formsAndTemplatesPath[2]));

    client.Send(email);