I am experiencing some problems sending emails with MailMessage. I have two email accounts, ([email protected], and [email protected]) and I would like account2 to send an email to account one at a button click event.
This is what I have but it's not working. I'm getting and exception saying it's forbidden.
try
{
//do submit
MailMessage emailMessage = new MailMessage();
emailMessage.From = new MailAddress("[email protected]", "Account2");
emailMessage.To.Add(new MailAddress("[email protected]", "Account1"));
emailMessage.Subject = "SUBJECT";
emailMessage.Body = "BODY";
emailMessage.Priority = MailPriority.Normal;
SmtpClient MailClient = new SmtpClient("smtp.gmail.com");
MailClient.Credentials = new System.Net.NetworkCredential("[email protected]", "password");
MailClient.Send(emailMessage);
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
I have a feeling it's a problem with the Smtp but I have no clue.
Try this:
using (MailMessage emailMessage = new MailMessage())
{
emailMessage.From = new MailAddress("[email protected]", "Account2");
emailMessage.To.Add(new MailAddress("[email protected]", "Account1"));
emailMessage.Subject = "SUBJECT";
emailMessage.Body = "BODY";
emailMessage.Priority = MailPriority.Normal;
using (SmtpClient MailClient = new SmtpClient("smtp.gmail.com", 587))
{
MailClient.EnableSsl = true;
MailClient.Credentials = new System.Net.NetworkCredential("[email protected]", "password");
MailClient.Send(emailMessage);
}
}
I added the port to the smtp client and enabled SSL. If port 587 doesn't work, try port 465.