Search code examples
c#asp.netemailgmail

How to send email using ASP.NET, C# and GMail


I have attempted to send an email using the GMail SMTP, and followed the guides on various other questions but I still cannot get emails to send from my GMail account.

This is the code I'm using:

protected void emailSend_Click(object sender, EventArgs e)
        {
            var fromAddress = new MailAddress(inputEmail.Text, inputName.Text);
            var toAddress = new MailAddress("[email protected]", "Liane Stevenson");
            const string fromPassword = "*********";
            const string subject = "Web Dev Wolf Message";
            var body = inputMessage.Text;

            var smtp = new SmtpClient
            {
                Host = "smtp.gmail.com",
                Port = 587,
                EnableSsl = true,
                DeliveryMethod = SmtpDeliveryMethod.Network,
                Credentials = new NetworkCredential("[email protected]", fromPassword),
                Timeout = 20000
            };
            using (var message = new MailMessage(fromAddress, toAddress)
            {
                Subject = subject,
                Body = body
            })
            {
                smtp.Send(message);
            }
        }

These are the things I've checked so far:

  1. Turning on less secure apps on GMail
  2. Checked the Gmail Username and Password are correct
  3. Debugged and checked that all text fields have values and are loaded into variables
  4. Check other port numbers suggested by Gmail help
  5. Turned on POP/IMAP functionality on Gmail

Is there anything else I could be missing?


Solution

  • Before calling SmtpClient.Send(), add:

    smtp.UseDefaultCredentials = false;
    

    According to the MSDN SmtpClient page, UseDefaultCredentials is set to false by default, but there seems to be a bug somewhere that is setting it to true. Explicitly set it to false before sending the message and it should be all set.