gmail-reader
Version:
A Gmail reader package for Google Workspace accounts with domain-wide delegation support
204 lines (152 loc) โข 4.46 kB
Markdown
# Workspace Gmail Reader
A TypeScript library for reading emails from Google Workspace (formerly G Suite) Gmail accounts. Supports both OAuth2 authentication and domain-wide delegation with service accounts.
## Features
- ๐ Secure authentication with OAuth2 and domain-wide delegation
- ๐ง Read emails with full content, headers, and attachments
- ๐ Advanced search and filtering capabilities
- ๐ Download email attachments
- ๐ Comprehensive TypeScript types
- โ
Production-ready with error handling
- ๐งช Well-tested with Jest
## Installation
```bash
npm install workspace-gmail-reader
```
## Prerequisites
### For OAuth2 Authentication
1. Create a Google Cloud Project
2. Enable the Gmail API
3. Create OAuth2 credentials (Client ID and Client Secret)
4. Set up OAuth consent screen
5. Obtain a refresh token
### For Domain-Wide Delegation
1. Create a Google Cloud Project
2. Enable the Gmail API
3. Create a service account
4. Download the service account key file
5. Enable domain-wide delegation in your Google Workspace admin console
6. Grant necessary OAuth scopes to the service account
## Usage
### OAuth2 Authentication
```typescript
import { createGmailClient, EmailQueryOptions } from 'workspace-gmail-reader';
// Create client configuration
const config = {
clientId: 'your-client-id',
clientSecret: 'your-client-secret',
redirectUri: 'your-redirect-uri' // Optional
};
// Create Gmail client
const gmailClient = createGmailClient(config, 'your-refresh-token');
// Authenticate and read emails
async function readEmails() {
await gmailClient.authenticate();
const options: EmailQueryOptions = {
maxResults: 10,
labelIds: ['INBOX'],
includeSpamTrash: false
};
const result = await gmailClient.getEmailsFrom('sender@example.com', options);
console.log(result.emails);
}
```
### Domain-Wide Delegation
```typescript
import { createDelegatedGmailClient } from 'workspace-gmail-reader';
// Create client configuration
const config = {
clientId: 'your-service-account-email',
clientSecret: '' // Not needed for domain-wide delegation
};
// Create Gmail client with domain-wide delegation
const gmailClient = createDelegatedGmailClient(
config,
'your-service-account-key-file-content',
'user-to-impersonate@your-domain.com',
['https://www.googleapis.com/auth/gmail.readonly'] // Optional scopes
);
// Authenticate and read emails
async function readEmails() {
await gmailClient.authenticate();
const result = await gmailClient.searchEmails('has:attachment');
console.log(result.emails);
}
```
### Working with Attachments
```typescript
// Get email with attachments
const email = await gmailClient.getEmail('email-id');
if (email.attachments) {
for (const attachment of email.attachments) {
const data = await gmailClient.getAttachment(email.id, attachment.attachmentId);
// data is a Buffer containing the attachment content
fs.writeFileSync(attachment.filename, data);
}
}
```
## API Reference
### Classes
#### `GmailClient`
The main class for interacting with Gmail.
### Factory Functions
#### `createGmailClient(config, refreshToken?, options?)`
Creates a new Gmail client for OAuth2 authentication.
#### `createDelegatedGmailClient(config, keyFile, impersonateEmail, scopes?)`
Creates a new Gmail client with domain-wide delegation.
### Interfaces
#### `GmailClientConfig`
```typescript
interface GmailClientConfig {
clientId: string;
clientSecret: string;
redirectUri?: string;
}
```
#### `EmailQueryOptions`
```typescript
interface EmailQueryOptions {
maxResults?: number;
labelIds?: string[];
includeSpamTrash?: boolean;
q?: string;
pageToken?: string;
}
```
#### `Email`
```typescript
interface Email {
id: string;
threadId?: string;
subject: string;
from: string;
to: string;
date: string;
snippet: string;
body?: {
plain?: string;
html?: string;
};
attachments?: EmailAttachment[];
labels?: string[];
}
```
## Examples
Check the `examples` directory for complete examples:
- `readFromEmail.ts`: Example using OAuth2 authentication
- `domainWideDelegation.ts`: Example using domain-wide delegation
## Development
```bash
# Install dependencies
npm install
# Build the package
npm run build
# Run tests
npm test
# Run examples
npm run example
npm run example:delegated
```
## Contributing
Contributions are welcome! Please feel free to submit a Pull Request.
## License
MIT