Click here to Skip to main content
15,868,016 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
Hello, i have an app that send emails correctly, the problem is later that day a error shows up saying "Authentication Error code:334". I think that i need to refresh the token or maybe gmail smtp have a limit for free emails.

What I have tried:

I tried to find on internet but i only find code for web apps, and mine is desktop

Here's my code


try
            {
                using (var stream = new FileStream("credential.json", FileMode.Open, FileAccess.Read))
                {
                    string credPath = "token.json";
                    credential = GoogleWebAuthorizationBroker.AuthorizeAsync(
                        GoogleClientSecrets.Load(stream).Secrets,
                        Scopes = new[] { "https://mail.google.com/" },
                        "user@gmail.com",
                        CancellationToken.None,
                        new FileDataStore(credPath, true)).Result;
                    Console.WriteLine("Credential file saved to: " + credPath);
                }
                var service = new GmailService(new BaseClientService.Initializer()
                {
                    HttpClientInitializer = credential,
                    ApplicationName = ApplicationName,
                });
                var message = new MimeKit.MimeMessage();
                message.From.Add(new MimeKit.MailboxAddress("User", "user@gmail.com"));
                message.To.Add(new MimeKit.MailboxAddress("Test", "test@gmail.com"));
                message.Subject = "Test";
                message.Body = new MimeKit.TextPart("plain")
                {
                    Text = "Test"
                };
                using (var client = new MailKit.Net.Smtp.SmtpClient())
                {
                    client.Connect("smtp.gmail.com", 587);
                    // use the access token 
                    var oauth2 = new MailKit.Security.SaslMechanismOAuth2(credential.UserId, credential.Token.AccessToken);
                    client.Authenticate(oauth2);
                    client.Send(message);
                    client.Disconnect(true);
                }
            }
            catch (Exception e)
            {
                MessageBox.Show(e.Message);
            }
Posted

1 solution

Pretty sure you asked the same thing recently .. this post Q: How do I authenticate with an OAUTH2 access token? · Issue #606 · jstedfast/MailKit · GitHub[^]

points out that
await credential.RefreshTokenAsync(CancellationToken.None);
seems to be the missing piece - have a read anyway and see if anything there helps you.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900