I am trying to send email, but I receive the following error:
An attempt was made to access a socket in a way forbidden by its access permissions 72.52.4.90:587
Code:
var mail = new MailMessage();
var client = new SmtpClient();
client.Port = 587;
client.Host = "smtp.gmail.com";
client.EnableSsl = true;
client.Timeout = 10000;
client.DeliveryMethod = SmtpDeliveryMethod.Network;
client.UseDefaultCredentials = false;
client.Credentials = new NetworkCredential("myemail@gmail.com", "password");
mail.From = new MailAddress("myemail@gmail.com");
mail.To.Add(new MailAddress("myemail@gmail.com"));
mail.BodyEncoding = UTF8Encoding.UTF8;
mail.DeliveryNotificationOptions = DeliveryNotificationOptions.OnFailure;
mail.Subject = "this is a test email.";
mail.Body = "this is my test email body";
client.Send(mail);
NOTE: This code is based on other questions and answers already here in StackOverflow. However, after an extensive search, it appears that no one else has experienced this particular issue so far. According to the other Q&A this code should be working.
UPDATE: After being told that this was a duplicate I've modified my code to the following, however, I'm still getting the same error.
private static void Main(string[] args)
{
var From = new MailAddress("myemail@gmail.com", "Me");
var To = new MailAddress("myemail@gmail.com", "Me Too");
var client = new SmtpClient
{
Host = "smtp.gmail.com",
Port = 587, //25
EnableSsl = true,
DeliveryMethod = SmtpDeliveryMethod.Network,
UseDefaultCredentials = false,
Credentials = new NetworkCredential(From.Address, "password"),
Timeout = 20000
};
using (var mail = new MailMessage(From, To)
{
Subject = @"this is a test email.",
Body = @"this is my test email body"
})
{
client.Send(mail);
};
}