How to send an e-mail with C# through Gmail

Just Go here : Less secure apps , Log on using your Email and Password which use for sending mail in your c# code , and choose Turn On.

Also please go to this link and click on Continue Allow access to your Google account

also I edit it little bit :

public string sendit(string ReciverMail)
{
    MailMessage msg = new MailMessage();

    msg.From = new MailAddress("[email protected]");
    msg.To.Add(ReciverMail);
    msg.Subject = "Hello world! " + DateTime.Now.ToString();
    msg.Body = "hi to you ... :)";
    SmtpClient client = new SmtpClient();
    client.UseDefaultCredentials = true;
    client.Host = "smtp.gmail.com";
    client.Port = 587;
    client.EnableSsl = true;
    client.DeliveryMethod = SmtpDeliveryMethod.Network;
    client.Credentials = new NetworkCredential("[email protected]", "YourPassword");
    client.Timeout = 20000;
    try
    {
       client.Send(msg);
        return "Mail has been successfully sent!";
    }
    catch (Exception ex)
    {
        return "Fail Has error" + ex.Message;
    }
    finally
    {
       msg.Dispose();
    }
}

If the above code don’t work , try to change it like the following code :

    SmtpClient client = new SmtpClient();
    client.Host = "smtp.gmail.com";
    client.Port = 587;
    client.EnableSsl = true;
    client.DeliveryMethod = SmtpDeliveryMethod.Network;
    client.UseDefaultCredentials = false;
    client.Credentials = new NetworkCredential("[email protected]", "YourPassword");

Leave a Comment