Search code examples
c#.netemailsmtpgmail

Sending email in .NET through Gmail


Instead of relying on my host to send an email, I was thinking of sending the email messages using my Gmail account. The emails are personalized emails to the bands I play on my show.

Is it possible to do it?


Solution

  • Be sure to use System.Net.Mail, not the deprecated System.Web.Mail. Doing SSL with System.Web.Mail is a gross mess of hacky extensions.

    using System.Net;
    using System.Net.Mail;
    
    var fromAddress = new MailAddress("from@gmail.com", "From Name");
    var toAddress = new MailAddress("to@example.com", "To Name");
    const string fromPassword = "fromPassword";
    const string subject = "Subject";
    const string body = "Body";
    
    var smtp = new SmtpClient
    {
        Host = "smtp.gmail.com",
        Port = 587,
        EnableSsl = true,
        DeliveryMethod = SmtpDeliveryMethod.Network,
        UseDefaultCredentials = false,
        Credentials = new NetworkCredential(fromAddress.Address, fromPassword)
    };
    using (var message = new MailMessage(fromAddress, toAddress)
    {
        Subject = subject,
        Body = body
    })
    {
        smtp.Send(message);
    }
    

    Additionally go to the Google Account > Security page and look at the Signing in to Google > 2-Step Verification setting.

    • If it is enabled, then you have to generate a password allowing .NET to bypass the 2-Step Verification. To do this, click on Signing in to Google > App passwords, select app = Mail, and device = Windows Computer, and finally generate the password. Use the generated password in the fromPassword constant instead of your standard Gmail password.
    • If it is disabled, then you have to turn on Less secure app access, which is not recommended! So better enable the 2-Step verification.