osswmi
osswmi

Reputation: 89

GMail API / OAUTH2 - How To Send Emails With Traditional C# SMTP Method Being Deprecated?

As per notice from Google's Less Secure App Deprecation Notice, on May 30, 2022 the ability access Google accounts through 'less secure apps' is being deprecated. The C# code below is how I have been sending emails from my own personal GMail account. I only send emails from my app. I do not do anything else (read emails, create drafts, etc...) from this account, only sending. Basically, it is the equivalent of sending "no-reply" emails.

// C# code
using (SmtpClient smtpClient = new SmtpClient(SmtpDomain, SmtpPortNumber))
{
    smtpClient.DeliveryMethod = SmtpDeliveryMethod;
    smtpClient.UseDefaultCredentials = UseDefaultCredentials;
    smtpClient.EnableSsl = true;
    smtpClient.Credentials = new NetworkCredential(SmtpUsername, SmtpPassword);

    MailMessage mailMessage = new MailMessage { /* ... */ };
    
    smtpClient.Send(mailMessage);
}

I've started looking at Google's API and OAuth documentation but I feel like I am going down a dark rabbit hole here since I am not wanting to access other users data, just only send emails from my own account. I assume from research that OAuth2 is the preferred way to do things when at all possible but I can't find a clear cut of example of "if you are doing it this way now", "then start doing this way". Can someone point me to the absolute starting point of the path I need to take to update my code so that I can continue sending emails from my own personal account/app?

Upvotes: 3

Views: 7131

Answers (1)

Linda Lawton - DaImTo
Linda Lawton - DaImTo

Reputation: 116948

Go to your google account and create an apps password once this is created just use that instead of the actual password for your gmail account.

Security

enter image description here

// C# code
using (SmtpClient smtpClient = new SmtpClient(SmtpDomain, SmtpPortNumber))
{
    smtpClient.DeliveryMethod = SmtpDeliveryMethod;
    smtpClient.UseDefaultCredentials = UseDefaultCredentials;
    smtpClient.EnableSsl = true;
    smtpClient.Credentials = new NetworkCredential(SmtpUsername, appsPasswrod);

    MailMessage mailMessage = new MailMessage { /* ... */ };
    
    smtpClient.Send(mailMessage);
}

Upvotes: 6

Related Questions