Documentation
¶
Overview ¶
Package imap provides a simple, pragmatic IMAP client for Go.
It focuses on the handful of operations most applications need:
- Connecting over TLS (STARTTLS not required)
- Authenticating with LOGIN or XOAUTH2 (OAuth 2.0)
- Selecting/Examining folders, searching (UID SEARCH), and fetching messages
- Moving messages, setting flags, deleting + expunging
- IMAP IDLE with callbacks for EXISTS/EXPUNGE/FETCH
- Automatic reconnect with re-authentication and folder restore
The API is intentionally small and easy to adopt without pulling in a full IMAP stack. See the README for end‑to‑end examples and guidance.
Index ¶
- Constants
- Variables
- func GetTokenName(tokenType TType) string
- func IsLiteral(b rune) bool
- func MakeIMAPLiteral(s string) string
- func SetLogger(logger Logger)
- func SetSlogLogger(logger *slog.Logger)
- type Attachment
- type Dialer
- func (d *Dialer) Authenticate(user string, accessToken string) (err error)
- func (d *Dialer) CheckType(token *Token, acceptableTypes []TType, tks []*Token, loc string, ...) (err error)
- func (d *Dialer) Clone() (d2 *Dialer, err error)
- func (d *Dialer) Close() (err error)
- func (d *Dialer) DeleteEmail(uid int) (err error)
- func (d *Dialer) ExamineFolder(folder string) (err error)
- func (d *Dialer) Exec(command string, buildResponse bool, retryCount int, ...) (response string, err error)
- func (d *Dialer) Expunge() (err error)
- func (d *Dialer) GetEmails(uids ...int) (emails map[int]*Email, err error)
- func (d *Dialer) GetFolderStats() ([]FolderStats, error)
- func (d *Dialer) GetFolderStatsExcluding(excludedFolders []string) ([]FolderStats, error)
- func (d *Dialer) GetFolderStatsStartingFrom(startFolder string) ([]FolderStats, error)
- func (d *Dialer) GetFolderStatsStartingFromExcluding(startFolder string, excludedFolders []string) ([]FolderStats, error)
- func (d *Dialer) GetFolders() (folders []string, err error)
- func (d *Dialer) GetLastNUIDs(n int) ([]int, error)
- func (d *Dialer) GetOverviews(uids ...int) (emails map[int]*Email, err error)
- func (d *Dialer) GetTotalEmailCount() (count int, err error)
- func (d *Dialer) GetTotalEmailCountExcluding(excludedFolders []string) (count int, err error)
- func (d *Dialer) GetTotalEmailCountSafe() (count int, folderErrors []error, err error)
- func (d *Dialer) GetTotalEmailCountSafeExcluding(excludedFolders []string) (count int, folderErrors []error, err error)
- func (d *Dialer) GetTotalEmailCountSafeStartingFrom(startFolder string) (count int, folderErrors []error, err error)
- func (d *Dialer) GetTotalEmailCountSafeStartingFromExcluding(startFolder string, excludedFolders []string) (count int, folderErrors []error, err error)
- func (d *Dialer) GetTotalEmailCountStartingFrom(startFolder string) (count int, err error)
- func (d *Dialer) GetTotalEmailCountStartingFromExcluding(startFolder string, excludedFolders []string) (count int, err error)
- func (d *Dialer) GetUIDs(search string) (uids []int, err error)
- func (d *Dialer) Login(username string, password string) (err error)
- func (d *Dialer) MarkSeen(uid int) (err error)
- func (d *Dialer) MoveEmail(uid int, folder string) (err error)
- func (d *Dialer) ParseFetchResponse(responseBody string) (records [][]*Token, err error)
- func (d *Dialer) Reconnect() (err error)
- func (d *Dialer) SelectFolder(folder string) (err error)
- func (d *Dialer) SetFlags(uid int, flags Flags) (err error)
- func (d *Dialer) StartIdle(handler *IdleHandler) error
- func (d *Dialer) State() int
- func (d *Dialer) StopIdle() error
- type Email
- type EmailAddresses
- type ExistsEvent
- type ExpungeEvent
- type FetchEvent
- type FlagSet
- type Flags
- type FolderStats
- type IdleHandler
- type Logger
- type TType
- type Token
Constants ¶
const ( StateDisconnected = iota StateConnected StateSelected StateIdlePending StateIdling StateStoppingIdle )
Connection state constants
const ( IdleEventExists = "EXISTS" IdleEventExpunge = "EXPUNGE" IdleEventFetch = "FETCH" )
IDLE event type constants
const ( EDate uint8 = iota ESubject EFrom ESender EReplyTo ETo ECC EBCC EInReplyTo EMessageID )
Email parsing constants
const ( EEName uint8 = iota EESR EEMailbox EEHost )
const (
TimeFormat = "_2-Jan-2006 15:04:05 -0700"
)
Variables ¶
var ( AddSlashes = strings.NewReplacer(`"`, `\"`) RemoveSlashes = strings.NewReplacer(`\"`, `"`) )
String replacers for escaping/unescaping quotes
var CommandTimeout time.Duration
CommandTimeout defines how long to wait for a command to complete. Zero means no timeout.
var DialTimeout time.Duration
DialTimeout defines how long to wait when establishing a new connection. Zero means no timeout.
var RetryCount = 10
var SkipResponses = false
SkipResponses skips printing server responses in verbose mode
var TLSSkipVerify bool
TLSSkipVerify disables certificate verification when establishing new connections. Use with caution; skipping verification exposes the connection to man-in-the-middle attacks.
var Verbose = false
Verbose outputs every command and its response with the IMAP server
Functions ¶
func GetTokenName ¶
GetTokenName returns the string name of a token type
func MakeIMAPLiteral ¶ added in v0.1.16
MakeIMAPLiteral generates IMAP literal syntax for non-ASCII strings. It returns a string in the format "{bytecount}\r\ntext" where bytecount is the number of bytes (not characters) in the input string. This is useful for search queries with non-ASCII characters. Example: MakeIMAPLiteral("тест") returns "{8}\r\nтест"
func SetLogger ¶ added in v0.1.17
func SetLogger(logger Logger)
SetLogger replaces the global logger used by the package. Passing nil restores the built-in slog logger.
func SetSlogLogger ¶ added in v0.1.17
SetSlogLogger is a convenience helper for using a *slog.Logger directly.
Types ¶
type Attachment ¶
Attachment represents an email attachment
func (Attachment) String ¶
func (a Attachment) String() string
String returns a formatted string representation of an Attachment
type Dialer ¶
type Dialer struct {
Folder string
ReadOnly bool
Username string
Password string
Host string
Port int
Connected bool
ConnNum int
// contains filtered or unexported fields
}
Dialer represents an IMAP connection
func NewWithOAuth2 ¶ added in v0.1.7
func NewWithOAuth2(username string, accessToken string, host string, port int) (d *Dialer, err error)
NewWithOAuth2 creates a new IMAP connection using OAuth2 authentication
func (*Dialer) Authenticate ¶ added in v0.1.7
Authenticate performs XOAUTH2 authentication using an access token
func (*Dialer) CheckType ¶
func (d *Dialer) CheckType(token *Token, acceptableTypes []TType, tks []*Token, loc string, v ...interface{}) (err error)
CheckType validates that a token is one of the acceptable types
func (*Dialer) DeleteEmail ¶ added in v0.1.9
DeleteEmail marks an email for deletion
func (*Dialer) ExamineFolder ¶ added in v0.1.8
ExamineFolder selects a folder in read-only mode
func (*Dialer) Exec ¶
func (d *Dialer) Exec(command string, buildResponse bool, retryCount int, processLine func(line []byte) error) (response string, err error)
Exec executes an IMAP command with retry logic and response building
func (*Dialer) GetFolderStats ¶ added in v0.1.16
func (d *Dialer) GetFolderStats() ([]FolderStats, error)
GetFolderStats returns statistics for all folders
func (*Dialer) GetFolderStatsExcluding ¶ added in v0.1.16
func (d *Dialer) GetFolderStatsExcluding(excludedFolders []string) ([]FolderStats, error)
GetFolderStatsExcluding returns statistics for folders excluding specified ones
func (*Dialer) GetFolderStatsStartingFrom ¶ added in v0.1.16
func (d *Dialer) GetFolderStatsStartingFrom(startFolder string) ([]FolderStats, error)
GetFolderStatsStartingFrom returns statistics for folders starting from a specific one
func (*Dialer) GetFolderStatsStartingFromExcluding ¶ added in v0.1.16
func (d *Dialer) GetFolderStatsStartingFromExcluding(startFolder string, excludedFolders []string) ([]FolderStats, error)
GetFolderStatsStartingFromExcluding returns detailed statistics for folders with options
func (*Dialer) GetFolders ¶
GetFolders retrieves the list of available folders
func (*Dialer) GetLastNUIDs ¶ added in v0.1.20
GetLastNUIDs returns the N messages with the highest UIDs in the selected folder. This is useful for fetching the most recent messages.
Note: This method fetches all UIDs from the server and returns the last N. For mailboxes with many thousands of messages, consider using GetUIDs with a specific UID range if you know the approximate UID values you need.
Example:
// Get the 10 most recent messages uids, err := conn.GetLastNUIDs(10)
func (*Dialer) GetOverviews ¶
GetOverviews retrieves email overview information (headers, flags, etc.)
func (*Dialer) GetTotalEmailCount ¶
GetTotalEmailCount returns the total email count across all folders
func (*Dialer) GetTotalEmailCountExcluding ¶
GetTotalEmailCountExcluding returns total email count excluding specified folders
func (*Dialer) GetTotalEmailCountSafe ¶ added in v0.1.16
GetTotalEmailCountSafe returns total email count with error handling per folder
func (*Dialer) GetTotalEmailCountSafeExcluding ¶ added in v0.1.16
func (d *Dialer) GetTotalEmailCountSafeExcluding(excludedFolders []string) (count int, folderErrors []error, err error)
GetTotalEmailCountSafeExcluding returns total email count excluding folders with error handling
func (*Dialer) GetTotalEmailCountSafeStartingFrom ¶ added in v0.1.16
func (d *Dialer) GetTotalEmailCountSafeStartingFrom(startFolder string) (count int, folderErrors []error, err error)
GetTotalEmailCountSafeStartingFrom returns total email count starting from folder with error handling
func (*Dialer) GetTotalEmailCountSafeStartingFromExcluding ¶ added in v0.1.16
func (d *Dialer) GetTotalEmailCountSafeStartingFromExcluding(startFolder string, excludedFolders []string) (count int, folderErrors []error, err error)
GetTotalEmailCountSafeStartingFromExcluding returns total email count with per-folder error handling
func (*Dialer) GetTotalEmailCountStartingFrom ¶
GetTotalEmailCountStartingFrom returns total email count starting from a specific folder
func (*Dialer) GetTotalEmailCountStartingFromExcluding ¶
func (d *Dialer) GetTotalEmailCountStartingFromExcluding(startFolder string, excludedFolders []string) (count int, err error)
GetTotalEmailCountStartingFromExcluding returns total email count with options for starting folder and exclusions
func (*Dialer) GetUIDs ¶
GetUIDs retrieves message UIDs matching a search criteria. The search parameter is passed directly to the IMAP UID SEARCH command. See RFC 3501 for search criteria syntax.
Common examples:
- "ALL" - all messages
- "UNSEEN" - unread messages
- "SEEN" - read messages
- "1:10" - UIDs 1 through 10
- "SINCE 1-Jan-2024" - messages since a date
Note: For retrieving the N most recent messages, use GetLastNUIDs instead.
func (*Dialer) ParseFetchResponse ¶
ParseFetchResponse parses a multi-line FETCH response
func (*Dialer) SelectFolder ¶
SelectFolder selects a folder in read-write mode
func (*Dialer) StartIdle ¶ added in v0.1.5
func (d *Dialer) StartIdle(handler *IdleHandler) error
StartIdle starts IDLE monitoring with automatic reconnection and timeout handling
type Email ¶
type Email struct {
Flags []string
Received time.Time
Sent time.Time
Size uint64
Subject string
UID int
MessageID string
From EmailAddresses
To EmailAddresses
ReplyTo EmailAddresses
CC EmailAddresses
BCC EmailAddresses
Text string
HTML string
Attachments []Attachment
}
Email represents an IMAP email message
type EmailAddresses ¶
EmailAddresses represents a map of email addresses to display names
func (EmailAddresses) String ¶
func (e EmailAddresses) String() string
String returns a formatted string representation of EmailAddresses
type ExistsEvent ¶ added in v0.1.5
type ExistsEvent struct {
MessageIndex int
}
ExistsEvent represents an EXISTS event from IDLE
type ExpungeEvent ¶ added in v0.1.5
type ExpungeEvent struct {
MessageIndex int
}
ExpungeEvent represents an EXPUNGE event from IDLE
type FetchEvent ¶ added in v0.1.5
FetchEvent represents a FETCH event from IDLE
type Flags ¶ added in v0.1.8
type Flags struct {
Seen FlagSet
Answered FlagSet
Flagged FlagSet
Deleted FlagSet
Draft FlagSet
Keywords map[string]bool
}
Flags represents standard IMAP message flags
type FolderStats ¶ added in v0.1.16
FolderStats represents statistics for a folder
type IdleHandler ¶ added in v0.1.5
type IdleHandler struct {
OnExists func(event ExistsEvent)
OnExpunge func(event ExpungeEvent)
OnFetch func(event FetchEvent)
}
IdleHandler provides callbacks for IDLE events
type Logger ¶ added in v0.1.17
type Logger interface {
Debug(msg string, args ...any)
Info(msg string, args ...any)
Warn(msg string, args ...any)
Error(msg string, args ...any)
WithAttrs(args ...any) Logger
}
Logger defines the minimal logging interface used by the IMAP client.
Implementations must be safe for concurrent use.
func SlogLogger ¶ added in v0.1.17
SlogLogger adapts a *slog.Logger to the Logger interface.
Source Files
¶
Directories
¶
| Path | Synopsis |
|---|---|
|
examples
|
|
|
basic_connection
command
|
|
|
complete_example
command
|
|
|
email_operations
command
|
|
|
error_handling
command
|
|
|
fetch_emails
command
|
|
|
folders
command
|
|
|
idle_monitoring
command
|
|
|
literal_search
command
|
|
|
oauth2_connection
command
|
|
|
search
command
|