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 ¶
- Constants
- Variables
- type Attachment
- type Client
- type ClientOption
- type ErrRateLimitExceeded
- type Message
- func (m *Message) Attach(filename string, r io.Reader) *Message
- func (m *Message) AttachFile(path string) *Message
- func (m *Message) BCC(addresses ...string) *Message
- func (m *Message) CC(addresses ...string) *Message
- func (m *Message) EmbedFile(path string, cid string) *Message
- func (m *Message) HTMLBody(body string) *Message
- func (m *Message) Send(ctx context.Context) error
- func (m *Message) Subject(sub string) *Message
- func (m *Message) TextBody(body string) *Message
- func (m *Message) To(addresses ...string) *Message
- type RateLimiter
- type Sender
Examples ¶
Constants ¶
const DefaultSendBurst int = 2
DefaultSendBurst is the default maximum burst size.
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.
const (
// MaxMessageSize is the maximum size of a Gmail message (25MB).
MaxMessageSize = 25 * 1024 * 1024
)
Variables ¶
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 ¶
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 ¶
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 ¶
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) AttachFile ¶
AttachFile adds an attachment by reading from the local file system.
func (*Message) EmbedFile ¶
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) Send ¶
Send finalizes the message, constructs the MIME payload, applies rate-limiting, and dispatches the email via the Gmail API.
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.