10

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("myemail@gmail.com);
    msg.To.Add(new MailAddress("theiremil@email.com));
    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("myemail@gmail.com", "pass");
    sc.DeliveryMethod = SmtpDeliveryMethod.Network;
    sc.Send(msg);
    erroremail.Text = "Email has been sent successfully.";
}
catch (Exception ex)
{
    erroremail.Text = "ERROR: " + ex.Message;
}
HelloWorld
  • 1,128
  • 1
  • 7
  • 14
  • I did, and then it says `ERROR: The SMTP server requires a secure connection or the client was not authenticated.`. – HelloWorld Jul 05 '15 at 13:52
  • Alright, it wasn't a code problem but it was Gmail settings that blocked the connection. It works now! – HelloWorld Jul 05 '15 at 13:56

1 Answers1

18

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("MyMail@Gmail.com", "MyPassword")
    }.Send(new MailMessage {From = new MailAddress("MyMail@Gmail.com", "MyName"), To = {"TheirMail@Mail.com"}, Subject = "Subject", Body = "Message", BodyEncoding = Encoding.UTF8});
    erroremail.Text = "Email has been sent successfully.";
}
catch (Exception ex)
{
    erroremail.Text = "ERROR: " + ex.Message;
}
  • @Anatoly He already posted a link in his answer. Less Secure App is a google account setting which lets your app send emails on behalf of you. – Sachin Trivedi Apr 29 '16 at 07:54
  • I wonder what "modern security standards" SmtpClient is lacking and if there is a native .NET alternative that does not require setting this account option. – Slight Aug 15 '16 at 20:02
  • Hi, can you comment on how are network credentials secured in this case? Ok, I see - enabled SSL. But in my case - I'm getting a timeout... – Prokurors Aug 10 '17 at 12:39