简体   繁体   中英

System.Net.Mail.SmtpException {“Failure Sending Email.”}

Keeps breaking and crashing at client.Send(email); with the error above. Quadruple checked everything.

Here's my code:

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);
}

What am I doing wrong, please?

Gmail SMTP port is 587, not 465. You also need to set the SmtpClient.EnableSsl property to true .

client.EnableSsl = true;

It is possible that you might need to set client.UseDefaultCredentials to false prior to setting the new network credentials. This is not always the case though - all I know is that when other options have been exhausted, this tends to work.

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

Since you are using gmail, you will need to allow less secure applications in your google account security settings. If you are using 2-factor authentication you will need to create an application-specific password as well, and use that in your code.

    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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM