No se puede autenticar en Gmail smtp a través de MailMessage y smtpClient

I cannot figure out for the life of my why this isn't working

SmtpClient smtp = new SmtpClient
{
    Host = "smtp.gmail.com",
    Port = 587,
    UseDefaultCredentials = false,
    DeliveryMethod = SmtpDeliveryMethod.Network,
    Credentials = new NetworkCredential("myemail@gmail.com", "myGmailPasswordHere"),
    EnableSsl = true,
    Timeout = 10000
};


smtp.Send(mail);

Yo obtengo:

El servidor SMTP requiere una conexión segura o el cliente no fue autenticado. La respuesta del servidor fue: 5.5.1 Se requiere autenticación.

I just specified EnableSsl to true so that shouldn't be the issue in terms of secure connection.

I'm running this from localhost. And yes, my username and password I'm entering to auth (my gmail account credentials) is 100% right.

preguntado el 01 de febrero de 12 a las 22:02

Have you declared it in web.config? -

no, for now just hard coding it. Should not matter for testing, web.config or not. -

I have edited my answer let me know if it works? -

@CoffeeAddict please check answers and provide an accepted one, if there is one. -

11 Respuestas

I know this is an old topic, BUT... Google has changed something on their security settings.

Was struggling with all the answers until I checked my email with a mail from Google stating that "we've recently blocked a sign-in attempt on your Google account".

That led me to this page: Google Account Security

Under the "Access for less secure apps" section, you can enable access to your account from other devices/applications... like your C# application.

Note, there is no longer an "application specific" section.

Hope this helps someone... I just lost 30 minutes of my life...

Respondido 21 ago 14, 00:08

this answer should get more votes.. sometimes we should try less voted answers too.. I tried all articles and really gave up after I tried solution marked as answer in stackoverflow.com/questions/32260/… I mean I had no idea what am doing wrong.. Thanks Tiny.. your solution worked for me.. - Plata

This really helped me. I don't understand why this information isn't easier to find. - Pastel de pescado

So what do I need to change in my code if I don't want to allow "less secure apps" in my gmail account? - user5515846

if you use your own domain, you need to use admin.google.com para establecer Verificación en dos pasos o permitiendo aplicaciones menos seguras - itsho

I turned on allowing less secure app access and still having intermittent issues. I don't follow what this reply is suggesting to do exactly. - emirhosseini

If login info is 100% right, you need to set UseDefaultCredentials = false primeras and then set the credentials you want to use Credentials = new NetworkCredential("myemail@gmail.com", "myGmailPasswordHere").

If you set the credentials first, when you set UseDefaultCredentials = false esto hará que el Credentials propiedad a null.

This is wired, but it happened to me.

Debug your code and check if the Credentials property is null before you call smtp.Send(message);. If so, then try inverting the order. It seems you have it in the right order, but if it's null, don't use the inline initialization.

Espero eso ayude.

EDIT: If you are using two-step verification, be sure you are using an App Specific password

Respondido 25 Jul 15, 14:07

Indeed this really works. Had same problem and this fixed mine out. - radu florescu

I spent 3 hours on this today... can't believe this fixed it. - MrZander

OMG... spent half of the day trying nearly everything. THANKS for the answer! - okieh

this did not work for me but i did consider it.. plz try stackoverflow.com/a/25414099/2649883 if still facing problem - Plata

incredible but in this order is work correctly SmtpClient smtpClient = new SmtpClient(); smtpClient.UseDefaultCredentials = false; smtpClient.Credentials = new NetworkCredential(senderAddress,senderPassword); smtpClient.DeliveryMethod = SmtpDeliveryMethod.Network; smtpClient.Host = host; smtpClient.Port = port; smtpClient.EnableSsl = useSsl; return smtpClient; - inkubpl

It looks like Gmail requires Application-specific password(not your main password).

Please, look into this: http://support.google.com/mail/bin/answer.py?hl=en&answer=1173270

I had the same problem recently.

Respondido 02 Feb 12, 18:02

Much thx, that did the trick for me. Using the code base from aquí, Siguiendo este consejo along with my application generated Verificación de 2-step Google password (no my regular Gmail password), I was able to send email from a C# test client. I was doing development/testing on my local desktop using my personal Gmail account and forgot I had enabled Gmail's Verificación de 2-step...so that is 2 hours of my life I'll never get back! :) - Al Dass

stackoverflow.com/a/25414099/2649883 works fine. there is no application specific section in gmail anymore - Plata

This worked just fine for me

SmtpClient smtp = new SmtpClient
    {
        Host = "smtp.gmail.com",
        Port = 587,
        UseDefaultCredentials = false,
        DeliveryMethod = SmtpDeliveryMethod.Network,
        Credentials = new NetworkCredential("myid@gmail.com", "mypassword"),
        EnableSsl = true,
        Timeout = 10000
    };

    MailMessage message = new MailMessage();
    message.Body = "hello there";
    message.Subject = "hi!!";
    message.To.Add("myid@gmail.com");
    message.From = new MailAddress("myid@gmail.com");
    smtp.Send(message);

Respondido 02 Feb 12, 09:02

I had this problem before and fixed it by following these steps:

  1. Ir a Mi Cuenta"configuración.
  2. Haga clic en "Inicio de sesión y seguridad"categoría.
  3. Desplácese hacia abajo hasta "Aplicaciones y sitios conectados" sección.
  4. turn off the "Permitir aplicaciones menos seguras" opción.

I just turned this option off and my code ran successfully.

Respondido 25 Feb 16, 13:02

For me the solution required 2 "steps":

  • planificadas UseDefaultCredentials = false first, then set the credentials I want to use Credentials = new NetworkCredential("myemail@gmail.com", "myGmailPasswordHere"). Setting the credentials first, when I set UseDefaultCredentials = false will make the Credentials property null.
  • Allow less secure apps on my Google profile.

Respondido 20 Abr '17, 02:04

Have a callback as follows. Tell System.Net to ignore the error!

Agregue esto antes de llamar a Send()

ServicePointManager.ServerCertificateValidationCallback = 
    delegate(object s, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors) 
    { return true; };

smtp.Send(mail);

Respondido 02 Feb 12, 03:02

Well don't eat then... handle the enum. Do tell us what you got. - ukhardy

<mailSettings>
            <smtp from="youremail@gmail.com">
                <network host="smtp.gmail.com" password="yourpassword" port="587" userName="username"/>
            </smtp>
</mailSettings>

Edit: try adding this line smtp.Credentials = Credentials después de este

Credentials = new NetworkCredential("myemail@gmail.com", "myGmailPasswordHere"),

Respondido 02 Feb 12, 03:02

yea I know you can do this but this doesn't explain why the hard coded magic strings of mine above (only for testing) isn't working. - PositiveGuy

why? I already set that in the object initializer for smtpClient Credentials = new NetworkCredential("myemail@gmail.com", "myGmailPasswordHere") - PositiveGuy

Had the same issue accessing smtp.gmail.com from an ASP.NET application running on Amazon AWS hosting. It turned out that my configuration was right - it was also working fine from another computer - but gmail would deny my login attempt, because I try logging in from an unusual location. I logged on to gmail over the web interface (www.gmail.com), and had to answer a captcha. After that it worked.

respondido 02 mar '13, 22:03

My problem was that the domain-owner for our gmail-account had disabled both "Access for less secure apps" and two step authentication. There was no way to enable it, I couldn't even see the setting. So I tested with my personal account instead, and it worked fine.

Respondido el 10 de Septiembre de 14 a las 17:09

Very simple just follow this for C# WPF Application:

       private void SendByGmail(string subject, string body, string recepientEmail, string MailMsgFrom, string MailMsgPass)
        {
            using (MailMessage mailMessage = new MailMessage())
            {
                mailMessage.From = new MailAddress(MailMsgFrom);
                mailMessage.Subject = subject;
                mailMessage.Body = body;
                mailMessage.IsBodyHtml = true;
                mailMessage.To.Add(new MailAddress(recepientEmail));
                mailMessage.Priority = System.Net.Mail.MailPriority.High;
                SmtpClient smtp = new SmtpClient();
                smtp.Host = "smtp.gmail.com";
                smtp.EnableSsl = true;
                smtp.Timeout = 200000;
                System.Net.NetworkCredential NetworkCred = new System.Net.NetworkCredential();
                NetworkCred.UserName = MailMsgFrom;
                NetworkCred.Password = MailMsgPass;
                smtp.UseDefaultCredentials = true;
                smtp.Credentials = NetworkCred;
                smtp.Port = 587;
                smtp.Send(mailMessage);

            }
        }

After that you should get like this Error

smtpException   {"The SMTP server requires a secure connection or the client was not authenticated. The server response was: 5.5.1 Authentication Required. Learn more at"}   System.Net.Mail.SmtpException

To Solve this problem, at first login your email account to your google account in web browser. Then just follow this link Google Account Activity. Then you'll get recent Devices & activity by your account. If show block your current activity from your current device. Just Unblock this. Then try again to send email.
Muchas Gracias

Respondido 13 Abr '15, 23:04

No es la respuesta que estás buscando? Examinar otras preguntas etiquetadas or haz tu propia pregunta.