Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using SmtpClient to send an email from Gmail

Tags:

c#

smtpclient

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;
}
like image 847
Aradmey Avatar asked Jul 05 '15 13:07

Aradmey


1 Answers

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;
}
like image 99
Fernando Bedolla Valencia Avatar answered Oct 27 '22 00:10

Fernando Bedolla Valencia