Send email using System.Net.Mail through gmail

Set

smtp.UseDefaultCredentials = false 

and use

smtp.Credentials = new NetworkCredential(gMailAccount, password);

This have worked for me:

        MailMessage message = new MailMessage("[email protected]", toemail, subjectEmail, comments);
        message.IsBodyHtml = true;

        try {
            SmtpClient client = new SmtpClient("smtp.gmail.com", 587);
            client.Timeout = 2000;
            client.EnableSsl = true;
            client.DeliveryMethod = SmtpDeliveryMethod.Network;
            //client.Credentials = CredentialCache.DefaultNetworkCredentials;
            client.UseDefaultCredentials = false;
            client.Credentials = new System.Net.NetworkCredential("[email protected]", "mypassord");
            client.Send(message);

            message.Dispose();
            client.Dispose();
        }
        catch (Exception ex) {
            Debug.WriteLine(ex.Message);
        }

BUT (as of the time of this writing - Oct 2017)

You need to ENABLE "Allow less secure apps" inside the option "apps with account access" at the "My account" google security/privacy settings (https://myaccount.google.com)


MailMessage mail = new MailMessage();
mail.From = new System.Net.Mail.MailAddress("[email protected]");

// The important part -- configuring the SMTP client
SmtpClient smtp = new SmtpClient();
smtp.Port = 587;   // [1] You can try with 465 also, I always used 587 and got success
smtp.EnableSsl = true;
smtp.DeliveryMethod = SmtpDeliveryMethod.Network; // [2] Added this
smtp.UseDefaultCredentials = false; // [3] Changed this
smtp.Credentials = new NetworkCredential(mail.From,  "password_here");  // [4] Added this. Note, first parameter is NOT string.
smtp.Host = "smtp.gmail.com";            

//recipient address
mail.To.Add(new MailAddress("[email protected]"));

//Formatted mail body
mail.IsBodyHtml = true;
string st = "Test";

mail.Body = st;
smtp.Send(mail);

I tried the above C# code to send mail from Gmail to my Corporate ID. While executing the application the control stopped indefinitely at the statement smtp.Send(mail);

While Googling, I came across a similar code, that worked for me. I am posting that code here.

class GMail
{
    public void SendMail()
    {  
        string pGmailEmail = "[email protected]";
        string pGmailPassword = "GmailPassword";
        string pTo = "ToAddress"; //[email protected]
        string pSubject = "Test From Gmail";
        string pBody = "Body"; //Body
        MailFormat pFormat = MailFormat.Text; //Text Message
        string pAttachmentPath = string.Empty; //No Attachments

        System.Web.Mail.MailMessage myMail = new System.Web.Mail.MailMessage();
        myMail.Fields.Add
            ("http://schemas.microsoft.com/cdo/configuration/smtpserver",
                          "smtp.gmail.com");
        myMail.Fields.Add
            ("http://schemas.microsoft.com/cdo/configuration/smtpserverport",
                          "465");
        myMail.Fields.Add
            ("http://schemas.microsoft.com/cdo/configuration/sendusing",
                          "2");
        //sendusing: cdoSendUsingPort, value 2, for sending the message using 
        //the network.

        //smtpauthenticate: Specifies the mechanism used when authenticating 
        //to an SMTP 
        //service over the network. Possible values are:
        //- cdoAnonymous, value 0. Do not authenticate.
        //- cdoBasic, value 1. Use basic clear-text authentication. 
        //When using this option you have to provide the user name and password 
        //through the sendusername and sendpassword fields.
        //- cdoNTLM, value 2. The current process security context is used to 
        // authenticate with the service.
        myMail.Fields.Add
        ("http://schemas.microsoft.com/cdo/configuration/smtpauthenticate", "1");
        //Use 0 for anonymous
        myMail.Fields.Add
        ("http://schemas.microsoft.com/cdo/configuration/sendusername",
            pGmailEmail);
        myMail.Fields.Add
        ("http://schemas.microsoft.com/cdo/configuration/sendpassword",
             pGmailPassword);
        myMail.Fields.Add
        ("http://schemas.microsoft.com/cdo/configuration/smtpusessl",
             "true");
        myMail.From = pGmailEmail;
        myMail.To = pTo;
        myMail.Subject = pSubject;
        myMail.BodyFormat = pFormat;
        myMail.Body = pBody;
        if (pAttachmentPath.Trim() != "")
        {
            MailAttachment MyAttachment =
                    new MailAttachment(pAttachmentPath);
            myMail.Attachments.Add(MyAttachment);
            myMail.Priority = System.Web.Mail.MailPriority.High;
        }

        SmtpMail.SmtpServer = "smtp.gmail.com:465";
        SmtpMail.Send(myMail);
    }
}

Tags:

C#

.Net

Email