Reputation: 3
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?
Upvotes: 0
Views: 5060
Reputation: 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);
Upvotes: -1
Reputation: 4808
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.
Upvotes: 4