gmail

package module
v1.0.0 Latest Latest
Warning

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

Go to latest
Published: Mar 29, 2026 License: MIT Imports: 18 Imported by: 0

README

go-gmail 📧

Go Reference Go Report Card

A robust, fluent, and rate-limited Go wrapper for the official Google Gmail API (google.golang.org/api/gmail/v1).

Standard Go email packages force you to manually construct MIME boundaries and handle raw Base64 encoding. go-gmail abstracts the complexity away, providing a clean, chainable builder pattern while actively protecting your Google account from rate-limit bans.

✨ Features

  • Fluent Builder API: Construct complex emails (HTML, CC, Attachments) in a single readable chain.
  • Account Protection: Built-in rate limiting and graceful degradation to prevent your account from being flagged by Google for spamming or hitting API quotas.
  • Smart Attachments: Seamlessly attach files from a local path or directly from an io.Reader (perfect for cloud storage microservices).
  • Context-Aware: Full context.Context support for modern, timeout-safe network calls.
  • Zero MIME Headaches: Automatically handles RFC 2822 formatting and Base64URL encoding under the hood.

📦 Installation

go get [github.com/gowriprasathdev/go-gmail](https://github.com/gowriprasathdev/go-gmail)

Documentation

Overview

Package gmail provides a robust and fluent builder API for sending emails via the official Google Gmail v1 API.

Package gmail provides a fluent builder API for sending emails via the Gmail v1 API.

Example
ctx := context.Background()

// 1. Load your credentials.
credsJSON, err := os.ReadFile("path/to/credentials.json")
if err != nil {
	log.Fatalf("Failed to read credentials: %v", err)
}

// 2. Initialize the client with AutoRetry enabled.
// This will cause .Send() to block and wait when rate limits are hit.
client, err := gmail.NewClient(ctx, credsJSON, gmail.WithAutoRetry())
if err != nil {
	log.Fatalf("Failed to create client: %v", err)
}

// 3. Use the fluent builder API with inline images and attachments.
msg := client.NewMessage().
	To("user@example.com").
	Subject("Daily Report").
	HTMLBody("<h1>Report</h1><p>See below:</p><img src=\"cid:report-img\">").
	EmbedFile("charts/daily.png", "report-img"). // Inline image
	AttachFile("reports/full_data.pdf")          // Regular attachment

// 4. Send the message. Since WithAutoRetry is enabled, we don't
// need to manually catch ErrRateLimitExceeded for minor pauses.
err = msg.Send(ctx)
if err != nil {
	if errors.Is(err, gmail.ErrQuotaReached) {
		fmt.Println("Daily API Quota Reached.")
		return
	}
	log.Fatalf("Failed to send email: %v", err)
}

fmt.Println("Email sent successfully!")

Index

Examples

Constants

View Source
const DefaultSendBurst int = 2

DefaultSendBurst is the default maximum burst size.

View Source
const DefaultSendRate rate.Limit = 2.0

DefaultSendRate is the default number of emails allowed per second per user. We set this conservatively to 2 emails per second to avoid quota bans.

View Source
const (
	// MaxMessageSize is the maximum size of a Gmail message (25MB).
	MaxMessageSize = 25 * 1024 * 1024
)

Variables

View Source
var (
	ErrClientNil        = errors.New("gmail client is nil")
	ErrMissingRecipient = errors.New("message must have at least one recipient (To, Cc, or Bcc)")
	ErrMissingBody      = errors.New("message must have a text or HTML body")
	ErrQuotaReached     = errors.New("gmail API daily quota reached")
)

Common validation errors.

Functions

This section is empty.

Types

type Attachment

type Attachment struct {
	Filename  string
	Data      []byte
	IsInline  bool
	ContentID string
}

Attachment represents a file to be attached to the email.

type Client

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

Client is a safe, concurrent Gmail API client configured with strict rate limiting to protect the user's account from quota bans.

func NewClient

func NewClient(ctx context.Context, credentialsJSON []byte, opts ...ClientOption) (*Client, error)

NewClient initializes a new Gmail client using standard Google OAuth2 JSON credentials (either User OAuth client credentials or a Service Account JSON).

func (*Client) NewMessage

func (c *Client) NewMessage() *Message

NewMessage starts the fluent builder pattern for composing a new email.

type ClientOption

type ClientOption func(*Client)

ClientOption defines an option for customizing the Client.

func WithAutoRetry

func WithAutoRetry() ClientOption

WithAutoRetry enables automatic waiting when rate limits (internal or 429) are hit.

func WithRateLimiter

func WithRateLimiter(rl *RateLimiter) ClientOption

WithRateLimiter allows overriding the default rate limiter.

type ErrRateLimitExceeded

type ErrRateLimitExceeded struct {
	// RetryAfter specifies the absolute time when the caller may retry sending.
	RetryAfter time.Time

	// Message holds the underlying reason for the rate limit.
	Message string
}

ErrRateLimitExceeded is returned when a sending request is rejected due to exceeding either internal rate limits or Gmail API limits (HTTP 429).

func (*ErrRateLimitExceeded) Error

func (e *ErrRateLimitExceeded) Error() string

Error implements the error interface.

type Message

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

Message represents an email being built.

func (*Message) Attach

func (m *Message) Attach(filename string, r io.Reader) *Message

Attach adds an attachment from an io.Reader.

func (*Message) AttachFile

func (m *Message) AttachFile(path string) *Message

AttachFile adds an attachment by reading from the local file system.

func (*Message) BCC

func (m *Message) BCC(addresses ...string) *Message

BCC adds a Blind Carbon Copy recipient.

func (*Message) CC

func (m *Message) CC(addresses ...string) *Message

CC adds a Carbon Copy recipient.

func (*Message) EmbedFile

func (m *Message) EmbedFile(path string, cid string) *Message

EmbedFile adds an inline attachment (e.g., image) with a Content-ID (CID). This allows referencing the image in HTMLBody via <img src="cid:YOUR_CID">.

func (*Message) HTMLBody

func (m *Message) HTMLBody(body string) *Message

HTMLBody sets the HTML body of the email.

func (*Message) Send

func (m *Message) Send(ctx context.Context) error

Send finalizes the message, constructs the MIME payload, applies rate-limiting, and dispatches the email via the Gmail API.

func (*Message) Subject

func (m *Message) Subject(sub string) *Message

Subject sets the email subject.

func (*Message) TextBody

func (m *Message) TextBody(body string) *Message

TextBody sets the plain text body of the email.

func (*Message) To

func (m *Message) To(addresses ...string) *Message

To adds a primary recipient. Can be chained.

type RateLimiter

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

RateLimiter wraps the standard library rate.Limiter to provide custom wait logic and error returns as required by the library's safety guarantees.

func DefaultRateLimiter

func DefaultRateLimiter() *RateLimiter

DefaultRateLimiter returns a RateLimiter configured with sensible conservative defaults designed to prevent the associated Gmail account from being blocked.

func NewRateLimiter

func NewRateLimiter(r rate.Limit, b int) *RateLimiter

NewRateLimiter creates a new custom RateLimiter with the specified rate and burst.

func (*RateLimiter) RequestToken

func (rl *RateLimiter) RequestToken(ctx context.Context) error

RequestToken evaluates whether a request can be executed immediately. If a delay is required, it returns ErrRateLimitExceeded containing the RetryAfter time.

type Sender

type Sender interface {
	NewMessage() *Message
}

Sender defines the interface for sending email messages. This allows for easier mocking in tests.

Jump to

Keyboard shortcuts

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