Integrating Gmail API for user communication in ASP.NET Core 8: OAuth and email sending

Hey everyone! I’m working on an ASP.NET Core 8 project and I need some help with the Gmail API. I want to use it for sending emails to users for stuff like account verification and updates. But I’m having a hard time figuring out how to set it up properly.

I’ve looked around for guides and tutorials, but most of them seem outdated. It’s frustrating! I tried using some Google NuGet packages (google.apis.auth and google.apis.gmail.v1), but they messed up my identity authentication cookies. Not cool!

Has anyone successfully implemented the Gmail API with OAuth in a recent ASP.NET Core project? I’d really appreciate some tips or pointers on how to get this working without breaking other parts of my app. Thanks in advance for any help!

I’ve been down that Gmail API rabbit hole too, and it’s definitely not straightforward. One approach that worked well for me was using the Google.Apis.Gmail.v1 library, but with a service account instead of OAuth. It’s a bit simpler to set up and doesn’t interfere with user authentication.

Here’s the gist: create a service account in Google Cloud Console, download the JSON key, and use that for authentication. You’ll need to enable domain-wide delegation if you’re sending on behalf of users.

The code looks something like this:

var credential = GoogleCredential.FromFile("path/to/service-account.json")
    .CreateScoped(GmailService.Scope.GmailSend);
var service = new GmailService(new BaseClientService.Initializer() {
    HttpClientInitializer = credential
});

// Then use the service to send emails

This approach has been reliable for me in recent ASP.NET Core projects. Hope it helps!

I’ve recently implemented Gmail API in an ASP.NET Core 8 project, and I can share what worked for me. Instead of using the Google NuGet packages directly, I found success with a wrapper library called MimeKit combined with MailKit. These libraries provide a more abstracted and easier-to-use interface for working with email protocols, including SMTP for Gmail.

For OAuth, I used the Microsoft.AspNetCore.Authentication.Google package. This approach keeps the OAuth flow separate from the email sending logic, which helped avoid conflicts with identity cookies.

Here’s a basic setup:

  1. Configure Google OAuth in Startup.cs
  2. Use IOptions pattern to store Gmail SMTP settings
  3. Create an EmailService that uses MimeKit to construct messages and MailKit to send them via Gmail’s SMTP

This solution has been robust and maintainable in my experience. Let me know if you’d like more details on any part of the implementation.

yo, i feel ur pain with the gmail api stuff. it can be a real headache! have u tried using mailkit instead? it’s pretty solid for sending emails in asp.net core and doesn’t mess with oauth. might be worth checkin out if u want a simpler solution. just my 2 cents!