KP.GmailClient

NuGet version (KP.GmailClient) Build status

KP.GmailClient

This is an alternative client for the auto generated Google.Apis.Gmail.v1 Client Library.

Prerequisites

  1. Create a new project in the Google Cloud Console (Guide)
  2. Create a OAuth consent screen (Guide)
    1. Publish the app or add any test users
  3. Create Desktop application credentials and download the client secret JSON file (Guide)
  4. Enable the Gmail API

Setup

One-time setup which opens the browser to authenticate the user.

// Define the required scopes
const GmailScopes scopes = GmailScopes.Readonly | GmailScopes.Send;

var broker = new GmailAuthenticationBroker();
var token = await broker.AuthenticateAsync("oauth_client_credentials.json", scopes);

var tokenStore = new FileTokenStore("token.json");
await tokenStore.StoreTokenAsync(token);

Usage examples

// Use the previously created files
var tokenClient = TokenClient.Create("oauth_client_credentials.json");
var tokenStore = new FileTokenStore("token.json");
using var client = new GmailClient(tokenClient, tokenStore);


// Send a plain text email
Message plainMessage = await client.Messages.SendAsync("example@gmail.com", "Subject", "Plain text body");

// Send a HTML email
Message htmlMessage = await client.Messages.SendAsync("example@gmail.com", "Subject", "<h1>HTML body</h1>", isBodyHtml: true);

// Get the users profile
Profile profile = await client.GetProfileAsync();

// Get inbox messages
IList<Message> messages = await client.Messages.ListAsync();

// Get starred messages
IList<Message> starredMessages = await client.Messages.ListByLabelAsync(Label.Starred);

// List all labels
IList<Label> labels = await client.Labels.ListAsync();

// List all drafts
IList<Draft> drafts = await client.Drafts.ListAsync();