I'm trying to connect to my Gmail account through SmtpClient
but it seems to not work as should. I specify port 465, enable SSL and define everything, but it takes like 2 minutes and then just shows some error that the message wasn't sent.
What am I doing wrong here?
try
{
MailMessage msg = new MailMessage();
msg.From = new MailAddress("[email protected]);
msg.To.Add(new MailAddress("[email protected]));
msg.Subject = "This is the subject";
msg.Body = "This is the body";
SmtpClient sc = new SmtpClient("smtp.gmail.com", 465);
sc.EnableSsl = true;
sc.UseDefaultCredentials = false;
sc.Credentials = new NetworkCredential("[email protected]", "pass");
sc.DeliveryMethod = SmtpDeliveryMethod.Network;
sc.Send(msg);
erroremail.Text = "Email has been sent successfully.";
}
catch (Exception ex)
{
erroremail.Text = "ERROR: " + ex.Message;
}
You need to allow "less secure apps":
https://support.google.com/accounts/answer/6010255
Code:
try
{
new SmtpClient
{
Host = "Smtp.Gmail.com",
Port = 587,
EnableSsl = true,
Timeout = 10000,
DeliveryMethod = SmtpDeliveryMethod.Network,
UseDefaultCredentials = false,
Credentials = new NetworkCredential("[email protected]", "MyPassword")
}.Send(new MailMessage {From = new MailAddress("[email protected]", "MyName"), To = {"[email protected]"}, Subject = "Subject", Body = "Message", BodyEncoding = Encoding.UTF8});
erroremail.Text = "Email has been sent successfully.";
}
catch (Exception ex)
{
erroremail.Text = "ERROR: " + ex.Message;
}