Search code examples
c#.netsmtpgmail

google SMTP settings stopped working after 'less secure apps' option is disabled by google


I have a working code for sending emails from my application. This was on production and working good. Sometime in the last 2 weeks, google disabled the "Less Secure Apps" option. The emails were not going through since then. Is there any workaround for this?

SmtpServer.Credentials = new System.Net.NetworkCredential("email.com", "password");
        SmtpServer.Port = 587; //587
        SmtpServer.Host = "smtp.gmail.com";
        SmtpServer.EnableSsl = true;
 

Thanks


Solution

  • There are two work arounds.

    Apps Password

    The first involves using an apps password in place of the users password to their google account. This option requires that you have 2fa enabled though in order to create the apps password.

     using (var client = new SmtpClient())
        {
            client.Connect("smtp.gmail.com", 465, true);
            client.Authenticate(message.From, "AppsPassword");
            client.Send(message.GetMessage());
            client.Disconnect(true);
        }
    

    XOauth2.

    The second option involves using xOauth2 authorize the request rather then using a password.

    This code requires that you create installed app credentials.

    using Google.Apis.Auth.OAuth2;
    using Google.Apis.Util.Store;
    using MailKit.Net.Smtp;
    using MailKit.Security;
    using MimeKit;
    
    var to = "[email protected]";
    var from = "[email protected]";
    
    var path = @"C:\YouTube\dev\credentials.json";
    var scopes = new[] { "https://mail.google.com/" };
    
    
    var credential = GoogleWebAuthorizationBroker.AuthorizeAsync(GoogleClientSecrets.FromFile(path).Secrets,
        scopes,
        "GmalSmtpUser",
        CancellationToken.None,
        new FileDataStore(Directory.GetCurrentDirectory(), true)).Result;
    
    
    
    var message = new EmailMessage()
    {
        From = from,
        To = to,
        MessageText = "This is a test message using https://developers.google.com/gmail/imap/xoauth2-protocol",
        Subject = "Testing GmailSMTP with XOauth2"
    };
    
    try
    {
        using (var client = new SmtpClient())
        {
            client.Connect("smtp.gmail.com", 465, true);
            
            var oauth2 = new SaslMechanismOAuth2 (message.From, credential.Token.AccessToken);
            await client.AuthenticateAsync (oauth2, CancellationToken.None);
            
            client.Send(message.GetMessage());
            client.Disconnect(true);
        }
    
       
    }
    catch (Exception ex)
    {
       Console.WriteLine(ex.Message);
    }
    
    
    public class EmailMessage
    {
        public string To { get; set; }
        public string From { get; set; }
        public string Subject { get; set; }
        public string MessageText { get; set; }
    
        public MimeMessage GetMessage()
        {
            var body = MessageText;
            var message = new MimeMessage();
            message.From.Add(new MailboxAddress("From a user", From));
            message.To.Add(new MailboxAddress("To a user", To));
            message.Subject = Subject;
            message.Body = new TextPart("plain") { Text = body };
            return message;
        }
    }
    

    The refresh token will expire after seven days until you set the project to production in the oauth2 consent screen.