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
- func HasToken() bool
- func HasTokenForAccount(account string) bool
- func HasTokenForAccountWithProvider(account string, provider google.TokenProvider) bool
- func HeaderValue(m *gmail.Message, header string) string
- func ParseDocumentID(urlStr string) (string, error)
- func SanitizeFilename(filename string) string
- func ValidateDocumentID(docID string) bool
- func ValidateMimeType(mimeType string, allowedTypes []string) bool
- type AttachmentInfo
- type Client
- func NewClient(ctx context.Context) (*Client, error)
- func NewClientForAccount(ctx context.Context, account string) (*Client, error)
- func NewClientForAccountWithProvider(ctx context.Context, account string, tokenProvider google.TokenProvider) (*Client, error)
- func NewClientWithProvider(ctx context.Context, provider google.TokenProvider) (*Client, error)
- func (c *Client) Account() string
- func (c *Client) ArchiveThread(tid string) error
- func (c *Client) CreateFilter(criteria FilterCriteria, action FilterAction) (*FilterInfo, error)
- func (c *Client) DeleteFilter(filterID string) error
- func (c *Client) ForeachThread(q string, fn func(*gmail.Thread) error) error
- func (c *Client) ForwardEmail(messageID string, to, cc, bcc []string, additionalBody string, isHTML bool) (string, error)
- func (c *Client) GetAttachment(messageID, attachmentID string) ([]byte, error)
- func (c *Client) GetAttachmentAsString(messageID, attachmentID string) (string, error)
- func (c *Client) GetFilter(filterID string) (*FilterInfo, error)
- func (c *Client) GetMessage(messageID string) (*gmail.Message, error)
- func (c *Client) GetMessageBody(messageID string, format string) (string, error)
- func (c *Client) GetProfile(ctx context.Context) (*gmail.Profile, error)
- func (c *Client) GetSignature() (string, error)
- func (c *Client) GetThread(threadID string) (*gmail.Thread, error)
- func (c *Client) GetThreadMessageBodies(threadID string, format string) (string, error)
- func (c *Client) GetUnsubscribeInfo(messageID string) (*UnsubscribeInfo, error)
- func (c *Client) GetVacationSettings(ctx context.Context) (*gmail.VacationSettings, error)
- func (c *Client) ListAttachments(messageID string) ([]*AttachmentInfo, error)
- func (c *Client) ListFilters() ([]*FilterInfo, error)
- func (c *Client) ListLabels() ([]*gmail.Label, error)
- func (c *Client) ListThreads(q string, maxResults int64) ([]*gmail.Thread, error)
- func (c *Client) MarkThreadAsSpam(tid string) error
- func (c *Client) PopulateThread(t *gmail.Thread) error
- func (c *Client) ReplyToEmail(messageID, threadID, body string, cc, bcc []string, isHTML bool) (string, error)
- func (c *Client) SearchContacts(query string, pageSize int) ([]*Contact, error)
- func (c *Client) SendEmail(msg *EmailMessage) (string, error)
- func (c *Client) UnarchiveThread(tid string) error
- func (c *Client) UnmarkThreadAsSpam(tid string) error
- func (c *Client) UnsubscribeViaHTTP(url string) error
- type Contact
- type DocLink
- type EmailMessage
- type FilterAction
- type FilterCriteria
- type FilterInfo
- type GitHubIssue
- type GitHubPull
- type ThreadType
- type UnsubscribeInfo
- type UnsubscribeMethod
Constants ¶
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
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 ¶
HeaderValue extracts a header value from a Gmail message
func ParseDocumentID ¶ added in v0.0.5
ParseDocumentID extracts the document ID from a Google Docs URL
func SanitizeFilename ¶ added in v0.0.4
SanitizeFilename sanitizes a filename to prevent path traversal attacks
func ValidateDocumentID ¶ added in v0.0.5
ValidateDocumentID checks if a document ID has a valid format
func ValidateMimeType ¶ added in v0.0.4
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 ¶
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
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
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
Account returns the account name this client is associated with
func (*Client) ArchiveThread ¶
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
DeleteFilter deletes a filter by ID
func (*Client) ForeachThread ¶
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
GetAttachment retrieves the content of an attachment (returns []byte)
func (*Client) GetAttachmentAsString ¶ added in v0.0.4
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
GetMessage retrieves a full Gmail message
func (*Client) GetMessageBody ¶ added in v0.0.4
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
GetProfile returns the Gmail user profile
func (*Client) GetSignature ¶ added in v0.0.12
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
GetThread retrieves a full Gmail thread with all its messages
func (*Client) GetThreadMessageBodies ¶ added in v0.0.23
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
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
ListLabels lists all Gmail labels for the user This is useful for getting label IDs to use in filters
func (*Client) ListThreads ¶
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
MarkThreadAsSpam marks a thread as spam by adding the SPAM label and removing the INBOX label
func (*Client) PopulateThread ¶
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
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
UnarchiveThread moves a thread back to inbox by adding the INBOX label
func (*Client) UnmarkThreadAsSpam ¶ added in v0.0.22
UnmarkThreadAsSpam removes the spam label from a thread, moving it back to inbox
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 ¶ added in v0.0.5
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 ¶ added in v0.0.5
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 ¶
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
UnsubscribeMethod represents a single unsubscribe method