common

package
v0.0.0-...-90479f1 Latest Latest
Warning

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

Go to latest
Published: Jun 26, 2016 License: MIT Imports: 12 Imported by: 0

Documentation

Overview

Generic structures and functions for IMAP.

Index

Constants

View Source
const (
	Capability string = "CAPABILITY"
	Noop              = "NOOP"
	Logout            = "LOGOUT"
	StartTLS          = "STARTTLS"

	Authenticate = "AUTHENTICATE"
	Login        = "LOGIN"

	Select      = "SELECT"
	Examine     = "EXAMINE"
	Create      = "CREATE"
	Delete      = "DELETE"
	Rename      = "RENAME"
	Subscribe   = "SUBSCRIBE"
	Unsubscribe = "UNSUBSCRIBE"
	List        = "LIST"
	Lsub        = "LSUB"
	Status      = "STATUS"
	Append      = "APPEND"

	Check   = "CHECK"
	Close   = "CLOSE"
	Expunge = "EXPUNGE"
	Search  = "SEARCH"
	Fetch   = "FETCH"
	Store   = "STORE"
	Copy    = "COPY"
	Uid     = "UID"
)

IMAP4rev1 commands.

View Source
const (
	// Replace existing flags by new ones
	SetFlags FlagsOp = "FLAGS"
	// Add new flags
	AddFlags = "+FLAGS"
	// Remove existing flags
	RemoveFlags = "-FLAGS"
)
View Source
const (
	// It is not possible for any child levels of hierarchy to exist under this\
	// name; no child levels exist now and none can be created in the future.
	NoInferiorsAttr = "\\Noinferiors"
	// It is not possible to use this name as a selectable mailbox.
	NoSelectAttr = "\\Noselect"
	// The mailbox has been marked "interesting" by the server; the mailbox
	// probably contains messages that have been added since the last time the
	// mailbox was selected.
	MarkedAttr = "\\Marked"
	// The mailbox does not contain any additional messages since the last time
	// the mailbox was selected.
	UnmarkedAttr = "\\Unmarked"
)

Mailbox attributes definied in RFC 3501 section 7.2.2.

View Source
const (
	MailboxFlags          = "FLAGS"
	MailboxPermanentFlags = "PERMANENTFLAGS"
	MailboxMessages       = "MESSAGES"
	MailboxRecent         = "RECENT"
	MailboxUnseen         = "UNSEEN"
	MailboxUidNext        = "UIDNEXT"
	MailboxUidValidity    = "UIDVALIDITY"
)

Mailbox status items.

View Source
const (
	SeenFlag     = "\\Seen"
	AnsweredFlag = "\\Answered"
	FlaggedFlag  = "\\Flagged"
	DeletedFlag  = "\\Deleted"
	DraftFlag    = "\\Draft"
	RecentFlag   = "\\Recent"
)

Message flags, defined in RFC 3501 section 2.3.2.

View Source
const (
	// Refers to the entire part, including headers.
	EntireSpecifier = ""
	// Refers to the header of the part. Must include the final CRLF delimiting
	// the header and the body.
	HeaderSpecifier = "HEADER"
	// Refers to the text body of the part, omitting the header.
	TextSpecifier = "TEXT"
	// Refers to the MIME Internet Message Body header.  Must include the final
	// CRLF delimiting the header and the body.
	MimeSpecifier = "MIME"
)

Part specifiers described in RFC 3501 page 55.

View Source
const (
	// In the not authenticated state, the client MUST supply
	// authentication credentials before most commands will be
	// permitted.  This state is entered when a connection starts
	// unless the connection has been pre-authenticated.
	NotAuthenticatedState ConnState = 1

	// In the authenticated state, the client is authenticated and MUST
	// select a mailbox to access before commands that affect messages
	// will be permitted.  This state is entered when a
	// pre-authenticated connection starts, when acceptable
	// authentication credentials have been provided, after an error in
	// selecting a mailbox, or after a successful CLOSE command.
	AuthenticatedState = 1 << 1

	// In a selected state, a mailbox has been selected to access.
	// This state is entered when a mailbox has been successfully
	// selected.
	SelectedState = AuthenticatedState + 1<<2

	// In the logout state, the connection is being terminated. This
	// state can be entered as a result of a client request (via the
	// LOGOUT command) or by unilateral action on the part of either
	// the client or server.
	LogoutState = 0
)
View Source
const (
	// The OK response indicates an information message from the server.  When
	// tagged, it indicates successful completion of the associated command.
	// The untagged form indicates an information-only message.
	OK StatusRespType = "OK"

	// The NO response indicates an operational error message from the
	// server.  When tagged, it indicates unsuccessful completion of the
	// associated command.  The untagged form indicates a warning; the
	// command can still complete successfully.
	NO = "NO"

	// The BAD response indicates an error message from the server.  When
	// tagged, it reports a protocol-level error in the client's command;
	// the tag indicates the command that caused the error.  The untagged
	// form indicates a protocol-level error for which the associated
	// command can not be determined; it can also indicate an internal
	// server failure.
	BAD = "BAD"

	// The PREAUTH response is always untagged, and is one of three
	// possible greetings at connection startup.  It indicates that the
	// connection has already been authenticated by external means; thus
	// no LOGIN command is needed.
	PREAUTH = "PREAUTH"

	// The BYE response is always untagged, and indicates that the server
	// is about to close the connection.
	BYE = "BYE"
)
View Source
const SilentOp = ".SILENT"

Variables

This section is empty.

Functions

func FormatAddressList

func FormatAddressList(addrs []*Address) (fields []interface{})

Format an address list to fields.

func FormatDate

func FormatDate(date *time.Time) string

Format an IMAP date.

func FormatParamList

func FormatParamList(params map[string]string) []interface{}

func FormatSearchDate

func FormatSearchDate(t *time.Time) string

Format a date to the search format.

func FormatStringList

func FormatStringList(list []string) (fields []interface{})

Convert a string list to a field list.

func ParseDate

func ParseDate(date string) (*time.Time, error)

Parse an IMAP date.

func ParseNumber

func ParseNumber(input interface{}) (uint32, error)

Convert a field to a number.

func ParseParamList

func ParseParamList(fields []interface{}) (params map[string]string, err error)

func ParseSearchDate

func ParseSearchDate(s string) (*time.Time, error)

Parse a date in the search format.

func ParseStringList

func ParseStringList(fields []interface{}) ([]string, error)

Convert a field list to a string list.

func ReadResp

func ReadResp(r *Reader) (out interface{}, err error)

Read a single response from a Reader. Returns either a continuation request, a status response or a raw response.

Types

type Address

type Address struct {
	// The personal name.
	PersonalName string
	// The SMTP at-domain-list (source route).
	AtDomainList string
	// The mailbox name.
	MailboxName string
	// The host name.
	HostName string
}

An address.

func ParseAddressList

func ParseAddressList(fields []interface{}) (addrs []*Address)

Parse an address list from fields.

func (*Address) Format

func (addr *Address) Format() []interface{}

Format an address to fields.

func (*Address) Parse

func (addr *Address) Parse(fields []interface{}) error

Parse an address from fields.

func (*Address) String

func (addr *Address) String() string

type BodyPartName

type BodyPartName struct {
	// The specifier of the requested part.
	Specifier string
	// The part path. Parts indexes start at 1.
	Path []int
	// If Specifier is HEADER, contains header fields that will/won't be returned,
	// depending of the value of NotFields.
	Fields []string
	// If set to true, Fields is a blacklist of fields instead of a whitelist.
	NotFields bool
}

A body part name.

func (*BodyPartName) String

func (part *BodyPartName) String() (s string)

type BodySectionName

type BodySectionName struct {
	*BodyPartName

	// If set to true, do not implicitely set the \Seen flag.
	Peek bool
	// The substring of the section requested. The first value is the position of
	// the first desired octet and the second value is the maximum number of
	// octets desired.
	Partial []int
	// contains filtered or unexported fields
}

A body section name. See RFC 3501 page 55.

func NewBodySectionName

func NewBodySectionName(s string) (section *BodySectionName, err error)

Parse a body section name.

func (*BodySectionName) ExtractPartial

func (section *BodySectionName) ExtractPartial(b []byte) []byte

Returns a subset of the specified bytes matching the partial requested in the section name.

func (*BodySectionName) String

func (section *BodySectionName) String() (s string)

type BodyStructure

type BodyStructure struct {

	// The MIME type.
	MimeType string
	// The MIME subtype.
	MimeSubType string
	// The MIME parameters.
	Params map[string]string

	// The Content-Id header.
	Id string
	// The Content-Description header.
	Description string
	// The Content-Encoding header.
	Encoding string
	// The Content-Length header.
	Size uint32

	// The children parts, if multipart.
	Parts []*BodyStructure
	// The envelope, if message/rfc822.
	Envelope *Envelope
	// The body structure, if message/rfc822.
	BodyStructure *BodyStructure
	// The number of lines, if text or message/rfc822.
	Lines uint32

	// True if the body structure contains extension data.
	Extended bool

	// The Content-Disposition header.
	Disposition string
	// The Content-Language header, if multipart.
	Language []string
	// The content URI, if multipart.
	Location []string

	// The MD5 checksum.
	Md5 string
}

A body structure. See RFC 3501 page 74.

func (*BodyStructure) Format

func (bs *BodyStructure) Format() (fields []interface{})

func (*BodyStructure) Parse

func (bs *BodyStructure) Parse(fields []interface{}) error

type Command

type Command struct {
	// The command tag. It acts as a unique identifier for this command.
	Tag string
	// The command name.
	Name string
	// The command arguments.
	Arguments []interface{}
}

A command.

func (*Command) Command

func (cmd *Command) Command() *Command

Implements the Commander interface.

func (*Command) Parse

func (cmd *Command) Parse(fields []interface{}) error

Parse a command from fields.

func (*Command) WriteTo

func (cmd *Command) WriteTo(w *Writer) (N int64, err error)

type Commander

type Commander interface {
	Command() *Command
}

A value that can be converted to a command.

type Conn

type Conn struct {
	net.Conn
	*Reader
	*Writer
	// contains filtered or unexported fields
}

An IMAP connection.

func NewConn

func NewConn(conn net.Conn, r *Reader, w *Writer) *Conn

Create a new IMAP connection.

func (*Conn) Flush

func (c *Conn) Flush() (err error)

Write any buffered data to the underlying connection.

func (*Conn) SetDebug

func (c *Conn) SetDebug(debug bool)

Enable or disable debugging.

func (*Conn) Upgrade

func (c *Conn) Upgrade(upgrader ConnUpgrader) error

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

func (*Conn) Wait

func (c *Conn) Wait()

Wait for the connection to be ready for reads and writes.

type ConnState

type ConnState int

A connection state. See RFC 3501 section 3.

type ConnUpgrader

type ConnUpgrader func(conn net.Conn) (net.Conn, error)

A function that upgrades a connection.

This should only be used by libraries implementing an IMAP extension (e.g. COMPRESS).

type ContinuationResp

type ContinuationResp struct {
	// The info message sent with the continuation request.
	Info string
}

A continuation request.

func (*ContinuationResp) WriteTo

func (r *ContinuationResp) WriteTo(w *Writer) (err error)

type Envelope

type Envelope struct {
	// The message date.
	Date *time.Time
	// The message subject.
	Subject string
	// The From header addresses.
	From []*Address
	// The message senders.
	Sender []*Address
	// The Reply-To header addresses.
	ReplyTo []*Address
	// The To header addresses.
	To []*Address
	// The Cc header addresses.
	Cc []*Address
	// The Bcc header addresses.
	Bcc []*Address
	// The In-Reply-To header. Contains the parent Message-Id.
	InReplyTo string
	// The Message-Id header.
	MessageId string
}

A message envelope, ie. message metadata from its headers. See RFC 3501 page 77.

func (*Envelope) Format

func (e *Envelope) Format() (fields []interface{})

Format an envelope to fields.

func (*Envelope) Parse

func (e *Envelope) Parse(fields []interface{}) error

Parse an envelope from fields.

type ErrBadSeqSet

type ErrBadSeqSet string

ErrBadSeqSet is used to report problems with the format of a sequence set value.

func (ErrBadSeqSet) Error

func (err ErrBadSeqSet) Error() string

type FlagsOp

type FlagsOp string

An operation that will be applied on message flags.

type Flusher

type Flusher interface {
	// Write any buffered data to the underlying connection.
	Flush() error
}

An interface implemented by net.Conn that allows to flush buffered data to the remote.

type Literal

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

A literal.

func NewLiteral

func NewLiteral(b []byte) *Literal

Create a new literal.

func (*Literal) Bytes

func (l *Literal) Bytes() []byte

func (*Literal) Len

func (l *Literal) Len() int

func (*Literal) String

func (l *Literal) String() string

type MailboxInfo

type MailboxInfo struct {
	// The mailbox attributes.
	Attributes []string
	// The server's path separator.
	Delimiter string
	// The mailbox name.
	Name string
}

Basic mailbox info.

func (*MailboxInfo) Format

func (info *MailboxInfo) Format() []interface{}

Format mailbox info to fields.

func (*MailboxInfo) Parse

func (info *MailboxInfo) Parse(fields []interface{}) error

Parse mailbox info from fields.

type MailboxStatus

type MailboxStatus struct {
	// The mailbox name.
	Name string
	// True if the mailbox is open in read-only mode.
	ReadOnly bool
	// The mailbox items that are currently filled in.
	Items []string

	// The mailbox flags.
	Flags []string
	// The mailbox permanent flags.
	PermanentFlags []string

	// The number of messages in this mailbox.
	Messages uint32
	// The number of messages not seen since the last time the mailbox was opened.
	Recent uint32
	// The number of unread messages.
	Unseen uint32
	// The next UID.
	UidNext uint32
	// Together with a UID, it is a unique identifier for a message.
	// Must be greater than or equal to 1.
	UidValidity uint32
}

A mailbox status.

type Message

type Message struct {
	// The message sequence number. It must be greater than or equal to 1.
	SeqNum uint32
	// The message items that are currently filled in.
	Items []string
	// The message body sections.
	Body map[*BodySectionName]*Literal

	// The message envelope.
	Envelope *Envelope
	// The message body structure (either BODYSTRUCTURE or BODY).
	BodyStructure *BodyStructure
	// The message flags.
	Flags []string
	// The date the message was received by th server.
	InternalDate *time.Time
	// The message size.
	Size uint32
	// The message unique identifier. It must be greater than or equal to 1.
	Uid uint32
}

A message.

func NewMessage

func NewMessage() *Message

Create a new empty message.

func (*Message) Format

func (m *Message) Format() (fields []interface{})

func (*Message) GetBody

func (m *Message) GetBody(s string) *Literal

Get the body section with the specified name. Returns nil if it's not found.

func (*Message) Parse

func (m *Message) Parse(fields []interface{}) error

Parse a message from fields.

type Parser

type Parser interface {
	Parse(fields []interface{}) error
}

type Reader

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

An IMAP reader.

func NewReader

func NewReader(r reader) *Reader

func NewServerReader

func NewServerReader(r reader, continues chan<- bool) *Reader

func (*Reader) ReadAtom

func (r *Reader) ReadAtom() (interface{}, error)

func (*Reader) ReadCrlf

func (r *Reader) ReadCrlf() (err error)

func (*Reader) ReadFields

func (r *Reader) ReadFields() (fields []interface{}, err error)

func (*Reader) ReadInfo

func (r *Reader) ReadInfo() (info string, err error)

func (*Reader) ReadLine

func (r *Reader) ReadLine() (fields []interface{}, err error)

func (*Reader) ReadList

func (r *Reader) ReadList() (fields []interface{}, err error)

func (*Reader) ReadLiteral

func (r *Reader) ReadLiteral() (literal *Literal, err error)

func (*Reader) ReadQuotedString

func (r *Reader) ReadQuotedString() (str string, err error)

func (*Reader) ReadRespCode

func (r *Reader) ReadRespCode() (code string, fields []interface{}, err error)

func (*Reader) ReadSp

func (r *Reader) ReadSp() error

type Resp

type Resp struct {
	// The response tag. Can be either * for untagged responses, + for continuation
	// requests or a previous command's tag.
	Tag string
	// The parsed response fields.
	Fields []interface{}
}

A response. See RFC 3501 section 2.2.2

func NewUntaggedResp

func NewUntaggedResp(fields []interface{}) *Resp

Create a new untagged response.

func (*Resp) WriteTo

func (r *Resp) WriteTo(w *Writer) (err error)

type RespHandler

type RespHandler chan *RespHandling

Delivers responses to handlers.

type RespHandlerFrom

type RespHandlerFrom interface {
	HandleFrom(hdlr RespHandler) error
}

Handles responses from a handler.

type RespHandling

type RespHandling struct {
	Resp    interface{}
	Accepts chan bool
}

A response that can be either accepted or rejected by a handler.

func (*RespHandling) Accept

func (h *RespHandling) Accept()

Accept this response. This means that the handler will process it.

func (*RespHandling) AcceptNamedResp

func (h *RespHandling) AcceptNamedResp(name string) (fields []interface{}, accepted bool)

Accept this response if it has the specified name. If not, reject it.

func (*RespHandling) Reject

func (h *RespHandling) Reject()

Reject this response. The handler cannot process it.

type Responser

type Responser interface {
	Response() *Resp
}

A value that can be converted to a Resp.

type SearchCriteria

type SearchCriteria struct {
	SeqSet     *SeqSet
	Answered   bool
	Bcc        string
	Before     *time.Time
	Body       string
	Cc         string
	Deleted    bool
	Draft      bool
	Flagged    bool
	From       string
	Header     [2]string
	Keyword    string
	Larger     uint32
	New        bool
	Not        *SearchCriteria
	Old        bool
	On         *time.Time
	Or         [2]*SearchCriteria
	Recent     bool
	Seen       bool
	SentBefore *time.Time
	SentOn     *time.Time
	SentSince  *time.Time
	Since      *time.Time
	Smaller    uint32
	Subject    string
	Text       string
	To         string
	Uid        *SeqSet
	Unanswered bool
	Undeleted  bool
	Undraft    bool
	Unflagged  bool
	Unkeyword  string
	Unseen     bool
}

A search criteria. See RFC 3501 section 6.4.4 for a description of each field.

func (*SearchCriteria) Format

func (c *SearchCriteria) Format() (fields []interface{})

Format search criteria to fields.

func (*SearchCriteria) Parse

func (c *SearchCriteria) Parse(fields []interface{}) error

Parse search criteria from fields.

type Seq

type Seq struct {
	Start, Stop uint32
}

Seq represents a single seq-number or seq-range value (RFC 3501 ABNF). Values may be static (e.g. "1", "2:4") or dynamic (e.g. "*", "1:*"). A seq-number is represented by setting Start = Stop. Zero is used to represent "*", which is safe because seq-number uses nz-number rule. The order of values is always Start <= Stop, except when representing "n:*", where Start = n and Stop = 0.

func (Seq) Contains

func (s Seq) Contains(q uint32) bool

Contains returns true if the seq-number q is contained in sequence value s. The dynamic value "*" contains only other "*" values, the dynamic range "n:*" contains "*" and all numbers >= n.

func (Seq) Less

func (s Seq) Less(q uint32) bool

Less returns true if s precedes and does not contain seq-number q.

func (Seq) Merge

func (s Seq) Merge(t Seq) (union Seq, ok bool)

Merge combines sequence values s and t into a single union if the two intersect or one is a superset of the other. The order of s and t does not matter. If the values cannot be merged, s is returned unmodified and ok is set to false.

func (Seq) String

func (s Seq) String() string

String returns sequence value s as a seq-number or seq-range string.

type SeqSet

type SeqSet struct {
	Set []Seq
}

SeqSet is used to represent a set of message sequence numbers or UIDs (see sequence-set ABNF rule). The zero value is an empty set.

func NewSeqSet

func NewSeqSet(set string) (s *SeqSet, err error)

NewSeqSet returns a new SeqSet instance after parsing the set string.

func (*SeqSet) Add

func (s *SeqSet) Add(set string) error

Add inserts new sequence values into the set. The string format is described by RFC 3501 sequence-set ABNF rule. If an error is encountered, all values inserted successfully prior to the error remain in the set.

func (*SeqSet) AddNum

func (s *SeqSet) AddNum(q ...uint32)

AddNum inserts new sequence numbers into the set. The value 0 represents "*".

func (*SeqSet) AddRange

func (s *SeqSet) AddRange(Start, Stop uint32)

AddRange inserts a new sequence range into the set.

func (*SeqSet) AddSet

func (s *SeqSet) AddSet(t *SeqSet)

AddSet inserts all values from t into s.

func (*SeqSet) Clear

func (s *SeqSet) Clear()

Clear removes all values from the set.

func (SeqSet) Contains

func (s SeqSet) Contains(q uint32) bool

Contains returns true if the non-zero sequence number or UID q is contained in the set. The dynamic range "n:*" contains all q >= n. It is the caller's responsibility to handle the special case where q is the maximum UID in the mailbox and q < n (i.e. the set cannot match UIDs against "*:n" or "*" since it doesn't know what the maximum value is).

func (SeqSet) Dynamic

func (s SeqSet) Dynamic() bool

Dynamic returns true if the set contains "*" or "n:*" values.

func (SeqSet) Empty

func (s SeqSet) Empty() bool

Empty returns true if the sequence set does not contain any values.

func (SeqSet) String

func (s SeqSet) String() string

String returns a sorted representation of all contained sequence values.

type StatusResp

type StatusResp struct {
	// The response tag.
	Tag string

	// The status type.
	Type StatusRespType

	// The status code.
	// See https://www.iana.org/assignments/imap-response-codes/imap-response-codes.xhtml
	Code string

	// Arguments provided with the status code.
	Arguments []interface{}

	// The status info.
	Info string
}

A status response. See RFC 3501 section 7.1

func (*StatusResp) Err

func (r *StatusResp) Err() error

If this status is NO or BAD, returns an error with the status info. Otherwise, returns nil.

func (*StatusResp) WriteTo

func (r *StatusResp) WriteTo(w *Writer) (err error)

type StatusRespType

type StatusRespType string

A status response type.

type StringReader

type StringReader interface {
	// ReadString reads until the first occurrence of delim in the input,
	// returning a string containing the data up to and including the delimiter.
	// See https://golang.org/pkg/bufio/#Reader.ReadString
	ReadString(delim byte) (line string, err error)
}

A string reader.

type StringWriter

type StringWriter interface {
	// WriteString writes a string. It returns the number of bytes written. If the
	// count is less than len(s), it also returns an error explaining why the
	// write is short.
	// See https://golang.org/pkg/bufio/#writeString
	WriteString(s string) (int, error)
}

A string writer.

type Writer

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

An IMAP writer.

func NewClientWriter

func NewClientWriter(w writer, continues <-chan bool) *Writer

func NewWriter

func NewWriter(w writer) *Writer

func (*Writer) Flush

func (w *Writer) Flush() (err error)

func (*Writer) WriteCrlf

func (w *Writer) WriteCrlf() (int, error)

Write a CRLF.

func (*Writer) WriteDate

func (w *Writer) WriteDate(date *time.Time) (int, error)

func (*Writer) WriteFields

func (w *Writer) WriteFields(fields []interface{}) (N int, err error)

func (*Writer) WriteInfo

func (w *Writer) WriteInfo(info string) (N int, err error)

func (*Writer) WriteList

func (w *Writer) WriteList(fields []interface{}) (N int, err error)

func (*Writer) WriteLiteral

func (w *Writer) WriteLiteral(literal *Literal) (N int, err error)

func (*Writer) WriteNil

func (w *Writer) WriteNil() (int, error)

Write NIL.

func (*Writer) WriteNumber

func (w *Writer) WriteNumber(num uint32) (int, error)

func (*Writer) WriteRespCode

func (w *Writer) WriteRespCode(code string, args []interface{}) (N int, err error)

func (*Writer) WriteSp

func (w *Writer) WriteSp() (int, error)

Write a separator.

func (*Writer) WriteString

func (w *Writer) WriteString(s string) (int, error)

type WriterTo

type WriterTo interface {
	WriteTo(w *Writer) error
}

Jump to

Keyboard shortcuts

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