简体   繁体   中英

How to send GMail/GSuite email using OAuth2 without browser popup?

Followingthis github article I am able to authenticate against GMail using OAuth2 and send gmail messages programmatically uisng SMTP and IMAP (clients from MailKit). The link was kindly provided by the author (jstedfast). The problem with the method is that it opens browser popup and requires user to authenticate, at least from time to time. Maybe this is because the method uses "User Secret" and not Service Account and private/public key, but I do not know for sure.

I need to send an email from server-type application, where there is no user to manually push the process forward. So far, the app is using standard SMTP authentication but this requires GMail/GSuite accounts to have "less secure" setting enabled and the customer does not want that.

There is a very old post (also by jstedfast) that shows how to authenticate email client with OAuth2, using Service Account and public/private key. I followed that article to the letter (except that I used json-packaged certificate, instead of p12 and used GMail not GSuite email) but the results are negative. Namely, when I try to execute client.Authenticate(accessToken) the response is exception that reads {"status":"400", "schemes":"Bearer", "scope": "https://mail.google.com/"}

I have access to GSuite and would not mind using it if necessary but, I have not found definite instructions and example that works. Would anyone be able to point at C# example that authenticates with OAuth2 through private/public key encryption and does not require user interaction ?

This is possible with web app type OAuth client ID and manually created refresh token.
How to create correct OAuth client ID and get refresh token: https://stackoverflow.com/a/24123550/6075536
How to send email with MailKit then: https://stackoverflow.com/a/52413127/6075536

And keep in mind Refresh token expiration rules .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM