client

package
v1.2.1 Latest Latest
Warning

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

Go to latest
Published: May 1, 2022 License: MIT Imports: 15 Imported by: 339

Documentation

Overview

Package client provides an IMAP client.

It is not safe to use the same Client from multiple goroutines. In general, the IMAP protocol doesn't make it possible to send multiple independent IMAP commands on the same connection.

Index

Examples

Constants

This section is empty.

Variables

View Source
var (
	// ErrAlreadyLoggedIn is returned if Login or Authenticate is called when the
	// client is already logged in.
	ErrAlreadyLoggedIn = errors.New("Already logged in")
	// ErrTLSAlreadyEnabled is returned if StartTLS is called when TLS is already
	// enabled.
	ErrTLSAlreadyEnabled = errors.New("TLS is already enabled")
	// ErrLoginDisabled is returned if Login or Authenticate is called when the
	// server has disabled authentication. Most of the time, calling enabling TLS
	// solves the problem.
	ErrLoginDisabled = errors.New("Login is disabled in current state")
)
View Source
var (
	// ErrNoMailboxSelected is returned if a command that requires a mailbox to be
	// selected is called when there isn't.
	ErrNoMailboxSelected = errors.New("No mailbox selected")

	// ErrExtensionUnsupported is returned if a command uses a extension that
	// is not supported by the server.
	ErrExtensionUnsupported = errors.New("The required extension is not supported by the server")
)
View Source
var ErrAlreadyLoggedOut = errors.New("Already logged out")

ErrAlreadyLoggedOut is returned if Logout is called when the client is already logged out.

View Source
var ErrNotLoggedIn = errors.New("Not logged in")

ErrNotLoggedIn is returned if a function that requires the client to be logged in is called then the client isn't.

Functions

This section is empty.

Types

type Client

type Client struct {

	// A channel to which unilateral updates from the server will be sent. An
	// update can be one of: *StatusUpdate, *MailboxUpdate, *MessageUpdate,
	// *ExpungeUpdate. Note that blocking this channel blocks the whole client,
	// so it's recommended to use a separate goroutine and a buffered channel to
	// prevent deadlocks.
	Updates chan<- Update

	// ErrorLog specifies an optional logger for errors accepting connections and
	// unexpected behavior from handlers. By default, logging goes to os.Stderr
	// via the log package's standard logger. The logger must be safe to use
	// simultaneously from multiple goroutines.
	ErrorLog imap.Logger

	// Timeout specifies a maximum amount of time to wait on a command.
	//
	// A Timeout of zero means no timeout. This is the default.
	Timeout time.Duration
	// contains filtered or unexported fields
}

Client is an IMAP client.

Example
log.Println("Connecting to server...")

// Connect to server
c, err := client.DialTLS("mail.example.org:993", nil)
if err != nil {
	log.Fatal(err)
}
log.Println("Connected")

// Don't forget to logout
defer c.Logout()

// Login
if err := c.Login("username", "password"); err != nil {
	log.Fatal(err)
}
log.Println("Logged in")

// List mailboxes
mailboxes := make(chan *imap.MailboxInfo, 10)
done := make(chan error, 1)
go func() {
	done <- c.List("", "*", mailboxes)
}()

log.Println("Mailboxes:")
for m := range mailboxes {
	log.Println("* " + m.Name)
}

if err := <-done; err != nil {
	log.Fatal(err)
}

// Select INBOX
mbox, err := c.Select("INBOX", false)
if err != nil {
	log.Fatal(err)
}
log.Println("Flags for INBOX:", mbox.Flags)

// Get the last 4 messages
from := uint32(1)
to := mbox.Messages
if mbox.Messages > 3 {
	// We're using unsigned integers here, only substract if the result is > 0
	from = mbox.Messages - 3
}
seqset := new(imap.SeqSet)
seqset.AddRange(from, to)
items := []imap.FetchItem{imap.FetchEnvelope}

messages := make(chan *imap.Message, 10)
done = make(chan error, 1)
go func() {
	done <- c.Fetch(seqset, items, messages)
}()

log.Println("Last 4 messages:")
for msg := range messages {
	log.Println("* " + msg.Envelope.Subject)
}

if err := <-done; err != nil {
	log.Fatal(err)
}

log.Println("Done!")
Output:

func Dial

func Dial(addr string) (*Client, error)

Dial connects to an IMAP server using an unencrypted connection.

func DialTLS

func DialTLS(addr string, tlsConfig *tls.Config) (*Client, error)

DialTLS connects to an IMAP server using an encrypted connection.

func DialWithDialer

func DialWithDialer(dialer Dialer, addr string) (*Client, error)

DialWithDialer connects to an IMAP server using an unencrypted connection using dialer.Dial.

Among other uses, this allows to apply a dial timeout.

func DialWithDialerTLS

func DialWithDialerTLS(dialer Dialer, addr string, tlsConfig *tls.Config) (*Client, error)

DialWithDialerTLS connects to an IMAP server using an encrypted connection using dialer.Dial.

Among other uses, this allows to apply a dial timeout.

func New

func New(conn net.Conn) (*Client, error)

New creates a new client from an existing connection.

func (*Client) Append

func (c *Client) Append(mbox string, flags []string, date time.Time, msg imap.Literal) error

Append appends the literal argument as a new message to the end of the specified destination mailbox. This argument SHOULD be in the format of an RFC 2822 message. flags and date are optional arguments and can be set to nil and the empty struct.

Example
// Let's assume c is a client
var c *client.Client

// Write the message to a buffer
var b bytes.Buffer
b.WriteString("From: <root@nsa.gov>\r\n")
b.WriteString("To: <root@gchq.gov.uk>\r\n")
b.WriteString("Subject: Hey there\r\n")
b.WriteString("\r\n")
b.WriteString("Hey <3")

// Append it to INBOX, with two flags
flags := []string{imap.FlaggedFlag, "foobar"}
if err := c.Append("INBOX", flags, time.Now(), &b); err != nil {
	log.Fatal(err)
}
Output:

func (*Client) Authenticate

func (c *Client) Authenticate(auth sasl.Client) error

Authenticate indicates a SASL authentication mechanism to the server. If the server supports the requested authentication mechanism, it performs an authentication protocol exchange to authenticate and identify the client.

func (*Client) Capability

func (c *Client) Capability() (map[string]bool, error)

Capability requests a listing of capabilities that the server supports. Capabilities are often returned by the server with the greeting or with the STARTTLS and LOGIN responses, so usually explicitly requesting capabilities isn't needed.

Most of the time, Support should be used instead.

func (*Client) Check

func (c *Client) Check() error

Check requests a checkpoint of the currently selected mailbox. A checkpoint refers to any implementation-dependent housekeeping associated with the mailbox that is not normally executed as part of each command.

func (*Client) Close

func (c *Client) Close() error

Close permanently removes all messages that have the \Deleted flag set from the currently selected mailbox, and returns to the authenticated state from the selected state.

func (*Client) Copy

func (c *Client) Copy(seqset *imap.SeqSet, dest string) error

Copy copies the specified message(s) to the end of the specified destination mailbox.

func (*Client) Create

func (c *Client) Create(name string) error

Create creates a mailbox with the given name.

func (*Client) Delete

func (c *Client) Delete(name string) error

Delete permanently removes the mailbox with the given name.

func (*Client) Enable added in v1.2.0

func (c *Client) Enable(caps []string) ([]string, error)

Enable requests the server to enable the named extensions. The extensions which were successfully enabled are returned.

See RFC 5161 section 3.1.

func (*Client) Execute

func (c *Client) Execute(cmdr imap.Commander, h responses.Handler) (*imap.StatusResp, error)

Execute executes a generic command. cmdr is a value that can be converted to a raw command and h is a response handler. The function returns when the command has completed or failed, in this case err is nil. A non-nil err value indicates a network error.

This function should not be called directly, it must only be used by libraries implementing extensions of the IMAP protocol.

func (*Client) Expunge

func (c *Client) Expunge(ch chan uint32) error

Expunge permanently removes all messages that have the \Deleted flag set from the currently selected mailbox. If ch is not nil, sends sequence IDs of each deleted message to this channel.

Example
// Let's assume c is a client
var c *client.Client

// Select INBOX
mbox, err := c.Select("INBOX", false)
if err != nil {
	log.Fatal(err)
}

// We will delete the last message
if mbox.Messages == 0 {
	log.Fatal("No message in mailbox")
}
seqset := new(imap.SeqSet)
seqset.AddNum(mbox.Messages)

// First mark the message as deleted
item := imap.FormatFlagsOp(imap.AddFlags, true)
flags := []interface{}{imap.DeletedFlag}
if err := c.Store(seqset, item, flags, nil); err != nil {
	log.Fatal(err)
}

// Then delete it
if err := c.Expunge(nil); err != nil {
	log.Fatal(err)
}

log.Println("Last message has been deleted")
Output:

func (*Client) Fetch

func (c *Client) Fetch(seqset *imap.SeqSet, items []imap.FetchItem, ch chan *imap.Message) error

Fetch retrieves data associated with a message in the mailbox. See RFC 3501 section 6.4.5 for a list of items that can be requested.

Example
// Let's assume c is a client
var c *client.Client

// Select INBOX
mbox, err := c.Select("INBOX", false)
if err != nil {
	log.Fatal(err)
}

// Get the last message
if mbox.Messages == 0 {
	log.Fatal("No message in mailbox")
}
seqset := new(imap.SeqSet)
seqset.AddRange(mbox.Messages, mbox.Messages)

// Get the whole message body
section := &imap.BodySectionName{}
items := []imap.FetchItem{section.FetchItem()}

messages := make(chan *imap.Message, 1)
done := make(chan error, 1)
go func() {
	done <- c.Fetch(seqset, items, messages)
}()

log.Println("Last message:")
msg := <-messages
r := msg.GetBody(section)
if r == nil {
	log.Fatal("Server didn't returned message body")
}

if err := <-done; err != nil {
	log.Fatal(err)
}

m, err := mail.ReadMessage(r)
if err != nil {
	log.Fatal(err)
}

header := m.Header
log.Println("Date:", header.Get("Date"))
log.Println("From:", header.Get("From"))
log.Println("To:", header.Get("To"))
log.Println("Subject:", header.Get("Subject"))

body, err := ioutil.ReadAll(m.Body)
if err != nil {
	log.Fatal(err)
}
log.Println(body)
Output:

func (*Client) Idle added in v1.2.0

func (c *Client) Idle(stop <-chan struct{}, opts *IdleOptions) error

Idle indicates to the server that the client is ready to receive unsolicited mailbox update messages. When the client wants to send commands again, it must first close stop.

If the server doesn't support IDLE, go-imap falls back to polling.

Example
package main

import (
	"log"

	"github.com/emersion/go-imap/client"
)

func main() {
	// Let's assume c is a client
	var c *client.Client

	// Select a mailbox
	if _, err := c.Select("INBOX", false); err != nil {
		log.Fatal(err)
	}

	// Create a channel to receive mailbox updates
	updates := make(chan client.Update)
	c.Updates = updates

	// Start idling
	stopped := false
	stop := make(chan struct{})
	done := make(chan error, 1)
	go func() {
		done <- c.Idle(stop, nil)
	}()

	// Listen for updates
	for {
		select {
		case update := <-updates:
			log.Println("New update:", update)
			if !stopped {
				close(stop)
				stopped = true
			}
		case err := <-done:
			if err != nil {
				log.Fatal(err)
			}
			log.Println("Not idling anymore")
			return
		}
	}
}
Output:

func (*Client) IsTLS

func (c *Client) IsTLS() bool

IsTLS checks if this client's connection has TLS enabled.

func (*Client) List

func (c *Client) List(ref, name string, ch chan *imap.MailboxInfo) error

List returns a subset of names from the complete set of all names available to the client.

An empty name argument is a special request to return the hierarchy delimiter and the root name of the name given in the reference. The character "*" is a wildcard, and matches zero or more characters at this position. The character "%" is similar to "*", but it does not match a hierarchy delimiter.

func (*Client) LoggedOut

func (c *Client) LoggedOut() <-chan struct{}

LoggedOut returns a channel which is closed when the connection to the server is closed.

func (*Client) Login

func (c *Client) Login(username, password string) error

Login identifies the client to the server and carries the plaintext password authenticating this user.

func (*Client) Logout

func (c *Client) Logout() error

Logout gracefully closes the connection.

func (*Client) Lsub

func (c *Client) Lsub(ref, name string, ch chan *imap.MailboxInfo) error

Lsub returns a subset of names from the set of names that the user has declared as being "active" or "subscribed".

func (*Client) Mailbox

func (c *Client) Mailbox() *imap.MailboxStatus

Mailbox returns the selected mailbox. It returns nil if there isn't one.

func (*Client) Move added in v1.2.0

func (c *Client) Move(seqset *imap.SeqSet, dest string) error

Move moves the specified message(s) to the end of the specified destination mailbox.

If the server doesn't support the MOVE extension defined in RFC 6851, go-imap will fallback to copy, store and expunge.

func (*Client) Noop

func (c *Client) Noop() error

Noop always succeeds and does nothing.

It can be used as a periodic poll for new messages or message status updates during a period of inactivity. It can also be used to reset any inactivity autologout timer on the server.

func (*Client) Rename

func (c *Client) Rename(existingName, newName string) error

Rename changes the name of a mailbox.

func (*Client) Search

func (c *Client) Search(criteria *imap.SearchCriteria) (seqNums []uint32, err error)

Search searches the mailbox for messages that match the given searching criteria. Searching criteria consist of one or more search keys. The response contains a list of message sequence IDs corresponding to those messages that match the searching criteria. When multiple keys are specified, the result is the intersection (AND function) of all the messages that match those keys. Criteria must be UTF-8 encoded. See RFC 3501 section 6.4.4 for a list of searching criteria. When no criteria has been set, all messages in the mailbox will be searched using ALL criteria.

Example
// Let's assume c is a client
var c *client.Client

// Select INBOX
_, err := c.Select("INBOX", false)
if err != nil {
	log.Fatal(err)
}

// Set search criteria
criteria := imap.NewSearchCriteria()
criteria.WithoutFlags = []string{imap.SeenFlag}
ids, err := c.Search(criteria)
if err != nil {
	log.Fatal(err)
}
log.Println("IDs found:", ids)

if len(ids) > 0 {
	seqset := new(imap.SeqSet)
	seqset.AddNum(ids...)

	messages := make(chan *imap.Message, 10)
	done := make(chan error, 1)
	go func() {
		done <- c.Fetch(seqset, []imap.FetchItem{imap.FetchEnvelope}, messages)
	}()

	log.Println("Unseen messages:")
	for msg := range messages {
		log.Println("* " + msg.Envelope.Subject)
	}

	if err := <-done; err != nil {
		log.Fatal(err)
	}
}

log.Println("Done!")
Output:

func (*Client) Select

func (c *Client) Select(name string, readOnly bool) (*imap.MailboxStatus, error)

Select selects a mailbox so that messages in the mailbox can be accessed. Any currently selected mailbox is deselected before attempting the new selection. Even if the readOnly parameter is set to false, the server can decide to open the mailbox in read-only mode.

func (*Client) SetDebug

func (c *Client) SetDebug(w io.Writer)

SetDebug defines an io.Writer to which all network activity will be logged. If nil is provided, network activity will not be logged.

func (*Client) SetState

func (c *Client) SetState(state imap.ConnState, mailbox *imap.MailboxStatus)

SetState sets this connection's internal state.

This function should not be called directly, it must only be used by libraries implementing extensions of the IMAP protocol.

func (*Client) StartTLS

func (c *Client) StartTLS(tlsConfig *tls.Config) error

StartTLS starts TLS negotiation.

Example
package main

import (
	"crypto/tls"
	"log"

	"github.com/emersion/go-imap/client"
)

func main() {
	log.Println("Connecting to server...")

	// Connect to server
	c, err := client.Dial("mail.example.org:143")
	if err != nil {
		log.Fatal(err)
	}
	log.Println("Connected")

	// Don't forget to logout
	defer c.Logout()

	// Start a TLS session
	tlsConfig := &tls.Config{ServerName: "mail.example.org"}
	if err := c.StartTLS(tlsConfig); err != nil {
		log.Fatal(err)
	}
	log.Println("TLS started")

	// Now we can login
	if err := c.Login("username", "password"); err != nil {
		log.Fatal(err)
	}
	log.Println("Logged in")
}
Output:

func (*Client) State

func (c *Client) State() imap.ConnState

State returns the current connection state.

func (*Client) Status

func (c *Client) Status(name string, items []imap.StatusItem) (*imap.MailboxStatus, error)

Status requests the status of the indicated mailbox. It does not change the currently selected mailbox, nor does it affect the state of any messages in the queried mailbox.

See RFC 3501 section 6.3.10 for a list of items that can be requested.

func (*Client) Store

func (c *Client) Store(seqset *imap.SeqSet, item imap.StoreItem, value interface{}, ch chan *imap.Message) error

Store alters data associated with a message in the mailbox. If ch is not nil, the updated value of the data will be sent to this channel. See RFC 3501 section 6.4.6 for a list of items that can be updated.

Example
// Let's assume c is a client
var c *client.Client

// Select INBOX
_, err := c.Select("INBOX", false)
if err != nil {
	log.Fatal(err)
}

// Mark message 42 as seen
seqSet := new(imap.SeqSet)
seqSet.AddNum(42)
item := imap.FormatFlagsOp(imap.AddFlags, true)
flags := []interface{}{imap.SeenFlag}
err = c.Store(seqSet, item, flags, nil)
if err != nil {
	log.Fatal(err)
}

log.Println("Message has been marked as seen")
Output:

func (*Client) Subscribe

func (c *Client) Subscribe(name string) error

Subscribe adds the specified mailbox name to the server's set of "active" or "subscribed" mailboxes.

func (*Client) Support

func (c *Client) Support(cap string) (bool, error)

Support checks if cap is a capability supported by the server. If the server hasn't sent its capabilities yet, Support requests them.

func (*Client) SupportAuth

func (c *Client) SupportAuth(mech string) (bool, error)

SupportAuth checks if the server supports a given authentication mechanism.

func (*Client) SupportStartTLS

func (c *Client) SupportStartTLS() (bool, error)

SupportStartTLS checks if the server supports STARTTLS.

func (*Client) Terminate

func (c *Client) Terminate() error

Terminate closes the tcp connection

func (*Client) UidCopy

func (c *Client) UidCopy(seqset *imap.SeqSet, dest string) error

UidCopy is identical to Copy, but seqset is interpreted as containing unique identifiers instead of message sequence numbers.

func (*Client) UidFetch

func (c *Client) UidFetch(seqset *imap.SeqSet, items []imap.FetchItem, ch chan *imap.Message) error

UidFetch is identical to Fetch, but seqset is interpreted as containing unique identifiers instead of message sequence numbers.

func (*Client) UidMove added in v1.2.0

func (c *Client) UidMove(seqset *imap.SeqSet, dest string) error

UidMove is identical to Move, but seqset is interpreted as containing unique identifiers instead of message sequence numbers.

func (*Client) UidSearch

func (c *Client) UidSearch(criteria *imap.SearchCriteria) (uids []uint32, err error)

UidSearch is identical to Search, but UIDs are returned instead of message sequence numbers.

func (*Client) UidStore

func (c *Client) UidStore(seqset *imap.SeqSet, item imap.StoreItem, value interface{}, ch chan *imap.Message) error

UidStore is identical to Store, but seqset is interpreted as containing unique identifiers instead of message sequence numbers.

func (*Client) Unselect added in v1.2.0

func (c *Client) Unselect() error

Unselect frees server's resources associated with the selected mailbox and returns the server to the authenticated state. This command performs the same actions as Close, except that no messages are permanently removed from the currently selected mailbox.

If client does not support the UNSELECT extension, ErrExtensionUnsupported is returned.

func (*Client) Unsubscribe

func (c *Client) Unsubscribe(name string) error

Unsubscribe removes the specified mailbox name from the server's set of "active" or "subscribed" mailboxes.

func (*Client) Upgrade

func (c *Client) Upgrade(upgrader imap.ConnUpgrader) error

Upgrade a connection, e.g. wrap an unencrypted connection with an encrypted tunnel.

This function should not be called directly, it must only be used by libraries implementing extensions of the IMAP protocol.

func (*Client) Writer

func (c *Client) Writer() *imap.Writer

Writer returns the imap.Writer for this client's connection.

This function should not be called directly, it must only be used by libraries implementing extensions of the IMAP protocol.

type Dialer

type Dialer interface {
	// Dial connects to the given address.
	Dial(network, addr string) (net.Conn, error)
}

type ExpungeUpdate

type ExpungeUpdate struct {
	SeqNum uint32
}

ExpungeUpdate is delivered when a message is deleted.

type IdleOptions added in v1.2.0

type IdleOptions struct {
	// LogoutTimeout is used to avoid being logged out by the server when
	// idling. Each LogoutTimeout, the IDLE command is restarted. If set to
	// zero, a default is used. If negative, this behavior is disabled.
	LogoutTimeout time.Duration
	// Poll interval when the server doesn't support IDLE. If zero, a default
	// is used. If negative, polling is always disabled.
	PollInterval time.Duration
}

IdleOptions holds options for Client.Idle.

type MailboxUpdate

type MailboxUpdate struct {
	Mailbox *imap.MailboxStatus
}

MailboxUpdate is delivered when a mailbox status changes.

type MessageUpdate

type MessageUpdate struct {
	Message *imap.Message
}

MessageUpdate is delivered when a message attribute changes.

type StatusUpdate

type StatusUpdate struct {
	Status *imap.StatusResp
}

StatusUpdate is delivered when a status update is received.

type Update

type Update interface {
	// contains filtered or unexported methods
}

Update is an unilateral server update.

Jump to

Keyboard shortcuts

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