gmail

package
v0.0.166 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Jun 20, 2026 License: BSD-3-Clause Imports: 17 Imported by: 0

Documentation

Overview

Package gmail provides a client for interacting with the Gmail API.

This package offers comprehensive Gmail functionality including:

  • Thread management (list, archive, iterate)
  • Email operations (send, reply, forward)
  • Attachment handling
  • Contact search across personal, directory, and other contacts
  • Gmail filters and classification
  • Unsubscribe link detection
  • Google Docs link extraction from emails

The client supports multi-account authentication using the Google OAuth2 flow and can manage emails across multiple Google accounts. It integrates with both the Gmail API (for email operations) and the People API (for contact management).

Authentication: This package uses the unified Google OAuth token from the google package. For HTTP/SSE transports: OAuth is handled automatically by the MCP client. For STDIO transport: Tokens are loaded from the file system (~/.cache/inboxfewer/).

Example usage:

ctx := context.Background()
client, err := gmail.NewClient(ctx)
if err != nil {
    log.Fatal(err)
}

// List threads matching a query
threads, err := client.ListThreads("in:inbox", 10)
if err != nil {
    log.Fatal(err)
}

// Send an email
msg := &gmail.EmailMessage{
    To:      []string{"recipient@example.com"},
    Subject: "Hello",
    Body:    "This is a test email",
    IsHTML:  false,
}
msgID, err := client.SendEmail(msg)
if err != nil {
    log.Fatal(err)
}

// Search contacts
contacts, err := client.SearchContacts("search query", 10)
if err != nil {
    log.Fatal(err)
}

Index

Constants

View Source
const (
	// MaxAttachmentSize defines the maximum attachment size in bytes (25MB)
	MaxAttachmentSize = 25 * 1024 * 1024
)

Variables

This section is empty.

Functions

func HasToken added in v0.0.5

func HasToken() bool

HasToken checks if a valid OAuth token exists for the default account

func HasTokenForAccount added in v0.0.8

func HasTokenForAccount(account string) bool

HasTokenForAccount checks if a valid OAuth token exists for the specified account Uses the default file-based token provider

func HasTokenForAccountWithProvider added in v0.0.27

func HasTokenForAccountWithProvider(account string, provider google.TokenProvider) bool

HasTokenForAccount checks if a valid OAuth token exists for the specified account Uses the provided token provider

func HeaderValue

func HeaderValue(m *gmail.Message, header string) string

HeaderValue extracts a header value from a Gmail message

func ParseDocumentID added in v0.0.5

func ParseDocumentID(urlStr string) (string, error)

ParseDocumentID extracts the document ID from a Google Docs URL

func SanitizeFilename added in v0.0.4

func SanitizeFilename(filename string) string

SanitizeFilename sanitizes a filename to prevent path traversal attacks

func ValidateDocumentID added in v0.0.5

func ValidateDocumentID(docID string) bool

ValidateDocumentID checks if a document ID has a valid format

func ValidateMimeType added in v0.0.4

func ValidateMimeType(mimeType string, allowedTypes []string) bool

ValidateMimeType checks if a MIME type is in the allowed list

Types

type AttachmentInfo added in v0.0.4

type AttachmentInfo struct {
	MessageID    string
	PartID       string
	AttachmentID string
	Filename     string
	MimeType     string
	Size         int64
}

AttachmentInfo represents an attachment's metadata

type Client

type Client struct {
	// contains filtered or unexported fields
}

Client wraps the Gmail Users service and People service

func NewClient

func NewClient(ctx context.Context) (*Client, error)

NewClient creates a new Gmail client with OAuth2 authentication for the default account For CLI usage, it will prompt for auth code via stdin if no token exists For MCP usage, it will return an error if no token exists

func NewClientForAccount added in v0.0.8

func NewClientForAccount(ctx context.Context, account string) (*Client, error)

NewClientForAccount creates a new Gmail client with OAuth2 authentication for a specific account Uses the default file-based token provider for backward compatibility

func NewClientForAccountWithProvider added in v0.0.27

func NewClientForAccountWithProvider(ctx context.Context, account string, tokenProvider google.TokenProvider) (*Client, error)

NewClientForAccountWithProvider creates a new Gmail client with OAuth2 authentication for a specific account The OAuth token is retrieved from the provided token provider

func NewClientWithProvider added in v0.0.27

func NewClientWithProvider(ctx context.Context, provider google.TokenProvider) (*Client, error)

NewClientWithProvider creates a new Gmail client with OAuth2 authentication for the default account using the provided token provider

func (*Client) Account added in v0.0.8

func (c *Client) Account() string

Account returns the account name this client is associated with

func (*Client) ArchiveThread

func (c *Client) ArchiveThread(tid string) error

ArchiveThread archives a thread by removing the INBOX label

func (*Client) CreateFilter added in v0.0.13

func (c *Client) CreateFilter(criteria FilterCriteria, action FilterAction) (*FilterInfo, error)

CreateFilter creates a new Gmail filter

func (*Client) DeleteFilter added in v0.0.13

func (c *Client) DeleteFilter(filterID string) error

DeleteFilter deletes a filter by ID

func (*Client) ForeachThread

func (c *Client) ForeachThread(q string, fn func(*gmail.Thread) error) error

ForeachThread iterates over all threads matching the query

func (*Client) ForwardEmail added in v0.0.12

func (c *Client) ForwardEmail(messageID string, to, cc, bcc []string, additionalBody string, isHTML bool) (string, error)

ForwardEmail forwards an existing email message to new recipients

func (*Client) GetAttachment added in v0.0.4

func (c *Client) GetAttachment(messageID, attachmentID string) ([]byte, error)

GetAttachment retrieves the content of an attachment (returns []byte)

func (*Client) GetAttachmentAsString added in v0.0.4

func (c *Client) GetAttachmentAsString(messageID, attachmentID string) (string, error)

GetAttachmentAsString retrieves attachment content as string (for text files)

func (*Client) GetFilter added in v0.0.13

func (c *Client) GetFilter(filterID string) (*FilterInfo, error)

GetFilter retrieves a specific filter by ID

func (*Client) GetMessage added in v0.0.4

func (c *Client) GetMessage(messageID string) (*gmail.Message, error)

GetMessage retrieves a full Gmail message

func (*Client) GetMessageBody added in v0.0.4

func (c *Client) GetMessageBody(messageID string, format string) (string, error)

GetMessageBody extracts text/HTML body from a message or thread. It accepts both Message IDs and Thread IDs for convenience. When format is "text" and no text body is found, it automatically falls back to HTML.

func (*Client) GetProfile added in v0.0.27

func (c *Client) GetProfile(ctx context.Context) (*gmail.Profile, error)

GetProfile returns the Gmail user profile

func (*Client) GetSignature added in v0.0.12

func (c *Client) GetSignature() (string, error)

GetSignature fetches the user's Gmail signature (primary send-as address) The signature is cached after the first fetch

func (*Client) GetThread added in v0.0.23

func (c *Client) GetThread(threadID string) (*gmail.Thread, error)

GetThread retrieves a full Gmail thread with all its messages

func (*Client) GetThreadMessageBodies added in v0.0.23

func (c *Client) GetThreadMessageBodies(threadID string, format string) (string, error)

GetThreadMessageBodies extracts bodies from all messages in a thread

func (*Client) GetUnsubscribeInfo added in v0.0.13

func (c *Client) GetUnsubscribeInfo(messageID string) (*UnsubscribeInfo, error)

GetUnsubscribeInfo extracts List-Unsubscribe information from a message

func (*Client) GetVacationSettings added in v0.0.27

func (c *Client) GetVacationSettings(ctx context.Context) (*gmail.VacationSettings, error)

GetVacationSettings returns the vacation/auto-reply settings

func (*Client) ListAttachments added in v0.0.4

func (c *Client) ListAttachments(messageID string) ([]*AttachmentInfo, error)

ListAttachments extracts all attachments from a message

func (*Client) ListFilters added in v0.0.13

func (c *Client) ListFilters() ([]*FilterInfo, error)

ListFilters lists all Gmail filters for the user

func (*Client) ListLabels added in v0.0.13

func (c *Client) ListLabels() ([]*gmail.Label, error)

ListLabels lists all Gmail labels for the user This is useful for getting label IDs to use in filters

func (*Client) ListThreads

func (c *Client) ListThreads(q string, maxResults int64) ([]*gmail.Thread, error)

ListThreads lists threads matching the query with pagination It will fetch up to maxResults threads, making multiple API calls if necessary

func (*Client) MarkThreadAsSpam added in v0.0.22

func (c *Client) MarkThreadAsSpam(tid string) error

MarkThreadAsSpam marks a thread as spam by adding the SPAM label and removing the INBOX label

func (*Client) PopulateThread

func (c *Client) PopulateThread(t *gmail.Thread) error

PopulateThread populates t with its full data. t.Id must be set initially.

func (*Client) ReplyToEmail added in v0.0.12

func (c *Client) ReplyToEmail(messageID, threadID, body string, cc, bcc []string, isHTML bool) (string, error)

ReplyToEmail sends a reply to an existing email message

func (*Client) SearchContacts added in v0.0.7

func (c *Client) SearchContacts(query string, pageSize int) ([]*Contact, error)

SearchContacts searches for contacts across all sources (personal, directory, and other contacts) using the query string to filter results

func (*Client) SendEmail added in v0.0.7

func (c *Client) SendEmail(msg *EmailMessage) (string, error)

SendEmail sends an email through Gmail API

func (*Client) UnarchiveThread added in v0.0.21

func (c *Client) UnarchiveThread(tid string) error

UnarchiveThread moves a thread back to inbox by adding the INBOX label

func (*Client) UnmarkThreadAsSpam added in v0.0.22

func (c *Client) UnmarkThreadAsSpam(tid string) error

UnmarkThreadAsSpam removes the spam label from a thread, moving it back to inbox

func (*Client) UnsubscribeViaHTTP added in v0.0.13

func (c *Client) UnsubscribeViaHTTP(url string) error

UnsubscribeViaHTTP performs an HTTP GET request to the unsubscribe URL This follows the RFC 2369 List-Unsubscribe specification

type Contact added in v0.0.7

type Contact struct {
	ResourceName string
	DisplayName  string
	EmailAddress string
	PhoneNumber  string
}

Contact represents a simplified contact entry

type DocLink struct {
	URL        string `json:"url"`
	DocumentID string `json:"documentId"`
	Type       string `json:"type"` // "document", "spreadsheet", "presentation", "drive"
}

DocLink represents a Google Docs/Drive link found in an email

func ExtractDocLinks(text string) []*DocLink

ExtractDocLinks parses Google Docs/Drive URLs from text

type EmailMessage added in v0.0.7

type EmailMessage struct {
	To      []string
	Cc      []string
	Bcc     []string
	Subject string
	Body    string
	IsHTML  bool
}

EmailMessage represents an email to be sent

type FilterAction added in v0.0.13

type FilterAction struct {
	AddLabelIDs    []string // Label IDs to add
	RemoveLabelIDs []string // Label IDs to remove
	Forward        string   // Email address to forward to
	Archive        bool     // Remove from inbox (remove INBOX label)
	MarkAsRead     bool     // Mark as read
	Star           bool     // Add star
	MarkAsSpam     bool     // Mark as spam
	Delete         bool     // Send to trash
}

FilterAction represents the actions to take when a filter matches

type FilterCriteria added in v0.0.13

type FilterCriteria struct {
	From           string // Email addresses to filter from
	To             string // Email addresses to filter to
	Subject        string // Words in the subject line
	Query          string // Gmail search query
	HasAttachment  bool   // Whether the message has attachments
	Size           int64  // Message size in bytes (use with SizeComparison)
	SizeComparison string // "larger" or "smaller"
}

FilterCriteria represents the criteria for a Gmail filter

type FilterInfo added in v0.0.13

type FilterInfo struct {
	ID       string
	Criteria FilterCriteria
	Action   FilterAction
}

FilterInfo represents a Gmail filter with its criteria and actions

type GitHubIssue

type GitHubIssue struct {
	Repo        string // "golang/go"
	Number      string // "123"
	GithubUser  string
	GithubToken string
}

GitHubIssue represents a GitHub issue referenced in Gmail

func (*GitHubIssue) IsStale

func (id *GitHubIssue) IsStale() (bool, error)

IsStale checks if the GitHub issue is closed or doesn't exist

type GitHubPull

type GitHubPull struct {
	Repo        string // "golang/go"
	Number      string // "123"
	GithubUser  string
	GithubToken string
}

GitHubPull represents a GitHub pull request referenced in Gmail

func (*GitHubPull) IsStale

func (id *GitHubPull) IsStale() (bool, error)

IsStale checks if the GitHub pull request is closed or doesn't exist

type ThreadType

type ThreadType interface {
	IsStale() (bool, error)
}

ThreadType represents a classified thread type

func ClassifyThread

func ClassifyThread(t *gmail.Thread, githubUser, githubToken string) ThreadType

ClassifyThread classifies a Gmail thread based on its message headers

type UnsubscribeInfo added in v0.0.13

type UnsubscribeInfo struct {
	MessageID      string
	HasUnsubscribe bool
	Methods        []UnsubscribeMethod
}

UnsubscribeInfo contains information about how to unsubscribe from a sender

type UnsubscribeMethod added in v0.0.13

type UnsubscribeMethod struct {
	Type string // "mailto" or "http"
	URL  string
}

UnsubscribeMethod represents a single unsubscribe method

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL