mail

package module
v0.4.1 Latest Latest
Warning

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

Go to latest
Published: Feb 14, 2024 License: MIT Imports: 28 Imported by: 50

README

go-mail - Easy to use, yet comprehensive library for sending mails with Go

GoDoc codecov Go Report Card Mentioned in Awesome Go REUSE status buy ma a coffee

go-mail logo

The main idea of this library was to provide a simple interface to sending mails for my JS-Mailer project. It quickly evolved into a full-fledged mail library.

go-mail follows idiomatic Go style and best practice. It's only dependency is the Go Standard Library. It combines a lot of functionality from the standard library to give easy and convenient access to mail and SMTP related tasks.

Parts of this library (especially some parts of msgwriter.go) have been forked/ported from the go-mail/mail respectively go-gomail/gomail which both seems to not be maintained anymore.

The smtp package of go-mail is forked from the original Go stdlib's net/smtp and then extended by the go-mail team.

Features

Some of the features of this library:

  • Only Standard Library dependant
  • Modern, idiomatic Go
  • Sane and secure defaults
  • Explicit SSL/TLS support
  • Implicit StartTLS support with different policies
  • Makes use of contexts for a better control flow and timeout/cancelation handling
  • SMTP Auth support (LOGIN, PLAIN, CRAM-MD, XOAUTH2)
  • RFC5322 compliant mail address validation
  • Support for common mail header field generation (Message-ID, Date, Bulk-Precedence, Priority, etc.)
  • Reusing the same SMTP connection to send multiple mails
  • Support for attachments and inline embeds (from file system, io.Reader or embed.FS)
  • Support for different encodings
  • Middleware support for 3rd-party libraries to alter mail messages
  • Support sending mails via a local sendmail command
  • Support for requestng MDNs (RFC 8098) and DSNs (RFC 1891)
  • DKIM signature support via go-mail-middlware
  • Message object satisfies io.WriteTo and io.Reader interfaces
  • Support for Go's html/template and text/template (as message body, alternative part or attachment/emebed)
  • Output to file support which allows storing mail messages as e. g. .eml files to disk to open them in a MUA
  • Debug logging of SMTP traffic
  • Custom error types for delivery errors
  • Custom dial-context functions for more control over the connection (proxing, DNS hooking, etc.)

go-mail works like a programatic email client and provides lots of methods and functionalities you would consider standard in a MUA.

Documentation

We aim for good GoDoc documenation in our library which gives you a full API reference. We also provide a more in-depth documentation website at go-mail.dev

Compatibility

Go is growing fast and providing great features with every new release. While we'd love to adopt the latest Go features into our code, we realize that not everybody using this package can run the latest Go versions. Therefore we try to implement alternative solutions for Go versions that do not support these features. Yet, the work needed to maintain the separate versions is not to be underestimated. For that reason, we might retire that code at some point. We guarantee that go-mail will always support the last four releases of Go. With two Go releases per year, this gives the user a timeframe of two years to update to the next or even the latest version of Go.

Support

We have a support and general discussion channel on Discord. Find us at: #go-mail

Middleware

The goal of go-mail is to keep it free from 3rd party dependencies and only focus on things a mail library should fulfill. Yet, since version v0.2.8 we've added support for middleware on the Msg object, allowing 3rd parties to alter a given mail message to their needs without relying on go-mail to support their specific need.

To get our users started with message middleware, we've created a collection of useful middlewares. It can be found in a seperate repository: go-mail-middlware.

Examples

We provide example code in both our GoDocs as well as on our official Website (see Documentation). For a quick start into go-mail check out our Getting started guide.

Authors/Contributors

go-mail was initially authored and developed by Winni Neessen.

Big thanks to the following people, for contributing to the go-mail project (either in form of code or by reviewing code, writing documenation or helping to translate the website):

Documentation

Overview

Package mail provides a simple and easy way to send mails with Go

Index

Examples

Constants

View Source
const (
	// DefaultPort is the default connection port to the SMTP server
	DefaultPort = 25

	// DefaultPortSSL is the default connection port for SSL/TLS to the SMTP server
	DefaultPortSSL = 465

	// DefaultPortTLS is the default connection port for STARTTLS to the SMTP server
	DefaultPortTLS = 587

	// DefaultTimeout is the default connection timeout
	DefaultTimeout = time.Second * 15

	// DefaultTLSPolicy is the default STARTTLS policy
	DefaultTLSPolicy = TLSMandatory

	// DefaultTLSMinVersion is the minimum TLS version required for the connection
	// Nowadays TLS1.2 should be the sane default
	DefaultTLSMinVersion = tls.VersionTLS12
)

Defaults

View Source
const (
	// DSNMailReturnHeadersOnly requests that only the headers of the message be returned.
	// See: https://www.rfc-editor.org/rfc/rfc1891#section-5.3
	DSNMailReturnHeadersOnly DSNMailReturnOption = "HDRS"

	// DSNMailReturnFull requests that the entire message be returned in any "failed"
	// delivery status notification issued for this recipient
	// See: https://www.rfc-editor.org/rfc/rfc1891#section-5.3
	DSNMailReturnFull DSNMailReturnOption = "FULL"

	// DSNRcptNotifyNever requests that a DSN not be returned to the sender under
	// any conditions.
	// See: https://www.rfc-editor.org/rfc/rfc1891#section-5.1
	DSNRcptNotifyNever DSNRcptNotifyOption = "NEVER"

	// DSNRcptNotifySuccess requests that a DSN be issued on successful delivery
	// See: https://www.rfc-editor.org/rfc/rfc1891#section-5.1
	DSNRcptNotifySuccess DSNRcptNotifyOption = "SUCCESS"

	// DSNRcptNotifyFailure requests that a DSN be issued on delivery failure
	// See: https://www.rfc-editor.org/rfc/rfc1891#section-5.1
	DSNRcptNotifyFailure DSNRcptNotifyOption = "FAILURE"

	// DSNRcptNotifyDelay indicates the sender's willingness to receive
	// "delayed" DSNs. Delayed DSNs may be issued if delivery of a message has
	// been delayed for an unusual amount of time (as determined by the MTA at
	// which the message is delayed), but the final delivery status (whether
	// successful or failure) cannot be determined. The absence of the DELAY
	// keyword in a NOTIFY parameter requests that a "delayed" DSN NOT be
	// issued under any conditions.
	// See: https://www.rfc-editor.org/rfc/rfc1891#section-5.1
	DSNRcptNotifyDelay DSNRcptNotifyOption = "DELAY"
)
View Source
const DoubleNewLine = "\r\n\r\n"

DoubleNewLine represents a double new line that can be used by the msgWriter to indicate a new segement of the mail

View Source
const ErrNoOutWriter = "no io.Writer set for Base64LineBreaker"

ErrNoOutWriter is an error message that should be used if a Base64LineBreaker has no out io.Writer set

View Source
const MaxBodyLength = 76

MaxBodyLength defines the maximum line length for the mail body RFC 2047 suggests 76 characters

View Source
const MaxHeaderLength = 76

MaxHeaderLength defines the maximum line length for a mail header RFC 2047 suggests 76 characters

View Source
const SendmailPath = "/usr/sbin/sendmail"

SendmailPath is the default system path to the sendmail binary

View Source
const SingleNewLine = "\r\n"

SingleNewLine represents a new line that can be used by the msgWriter to issue a carriage return

View Source
const VERSION = "0.4.1"

VERSION is used in the default user agent string

Variables

View Source
var (
	// ErrPlainAuthNotSupported should be used if the target server does not support the "PLAIN" schema
	ErrPlainAuthNotSupported = errors.New("server does not support SMTP AUTH type: PLAIN")

	// ErrLoginAuthNotSupported should be used if the target server does not support the "LOGIN" schema
	ErrLoginAuthNotSupported = errors.New("server does not support SMTP AUTH type: LOGIN")

	// ErrCramMD5AuthNotSupported should be used if the target server does not support the "CRAM-MD5" schema
	ErrCramMD5AuthNotSupported = errors.New("server does not support SMTP AUTH type: CRAM-MD5")

	// ErrXOauth2AuthNotSupported should be used if the target server does not support the "XOAUTH2" schema
	ErrXOauth2AuthNotSupported = errors.New("server does not support SMTP AUTH type: XOAUTH2")
)

SMTP Auth related static errors

View Source
var (
	// ErrInvalidPort should be used if a port is specified that is not valid
	ErrInvalidPort = errors.New("invalid port number")

	// ErrInvalidTimeout should be used if a timeout is set that is zero or negative
	ErrInvalidTimeout = errors.New("timeout cannot be zero or negative")

	// ErrInvalidHELO should be used if an empty HELO sting is provided
	ErrInvalidHELO = errors.New("invalid HELO/EHLO value - must not be empty")

	// ErrInvalidTLSConfig should be used if an empty tls.Config is provided
	ErrInvalidTLSConfig = errors.New("invalid TLS config")

	// ErrNoHostname should be used if a Client has no hostname set
	ErrNoHostname = errors.New("hostname for client cannot be empty")

	// ErrDeadlineExtendFailed should be used if the extension of the connection deadline fails
	ErrDeadlineExtendFailed = errors.New("connection deadline extension failed")

	// ErrNoActiveConnection should be used when a method is used that requies a server connection
	// but is not yet connected
	ErrNoActiveConnection = errors.New("not connected to SMTP server")

	// ErrServerNoUnencoded should be used when 8BIT encoding is selected for a message, but
	// the server does not offer 8BITMIME mode
	ErrServerNoUnencoded = errors.New("message is 8bit unencoded, but server does not support 8BITMIME")

	// ErrInvalidDSNMailReturnOption should be used when an invalid option is provided for the
	// DSNMailReturnOption in WithDSN
	ErrInvalidDSNMailReturnOption = errors.New("DSN mail return option can only be HDRS or FULL")

	// ErrInvalidDSNRcptNotifyOption should be used when an invalid option is provided for the
	// DSNRcptNotifyOption in WithDSN
	ErrInvalidDSNRcptNotifyOption = errors.New("DSN rcpt notify option can only be: NEVER, " +
		"SUCCESS, FAILURE or DELAY")

	// ErrInvalidDSNRcptNotifyCombination should be used when an invalid option is provided for the
	// DSNRcptNotifyOption in WithDSN
	ErrInvalidDSNRcptNotifyCombination = errors.New("DSN rcpt notify option NEVER cannot be " +
		"combined with any of SUCCESS, FAILURE or DELAY")
)
View Source
var (
	// ErrNoFromAddress should be used when a FROM address is requrested but not set
	ErrNoFromAddress = errors.New("no FROM address set")

	// ErrNoRcptAddresses should be used when the list of RCPTs is empty
	ErrNoRcptAddresses = errors.New("no recipient addresses set")
)

Functions

This section is empty.

Types

type AddrHeader

type AddrHeader string

AddrHeader represents a address related mail Header field name

const (
	// HeaderBcc is the "Blind Carbon Copy" header field
	HeaderBcc AddrHeader = "Bcc"

	// HeaderCc is the "Carbon Copy" header field
	HeaderCc AddrHeader = "Cc"

	// HeaderEnvelopeFrom is the envelope FROM header field
	// It's not included in the mail body but only used by the Client for the envelope
	HeaderEnvelopeFrom AddrHeader = "EnvelopeFrom"

	// HeaderFrom is the "From" header field
	HeaderFrom AddrHeader = "From"

	// HeaderTo is the "Receipient" header field
	HeaderTo AddrHeader = "To"
)

List of common address header field names

func (AddrHeader) String added in v0.1.4

func (a AddrHeader) String() string

String returns the address header string based on the given AddrHeader

type Base64LineBreaker added in v0.2.6

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

Base64LineBreaker is a io.WriteCloser that writes Base64 encoded data streams with line breaks at a given line length

func (*Base64LineBreaker) Close added in v0.2.6

func (l *Base64LineBreaker) Close() (err error)

Close closes the Base64LineBreaker and writes any access data that is still unwritten in memory

func (*Base64LineBreaker) Write added in v0.2.6

func (l *Base64LineBreaker) Write(b []byte) (n int, err error)

Write writes the data stream and inserts a SingleNewLine when the maximum line length is reached

type Charset

type Charset string

Charset represents a character set for the encoding

const (
	// CharsetUTF7 represents the "UTF-7" charset
	CharsetUTF7 Charset = "UTF-7"

	// CharsetUTF8 represents the "UTF-8" charset
	CharsetUTF8 Charset = "UTF-8"

	// CharsetASCII represents the "US-ASCII" charset
	CharsetASCII Charset = "US-ASCII"

	// CharsetISO88591 represents the "ISO-8859-1" charset
	CharsetISO88591 Charset = "ISO-8859-1"

	// CharsetISO88592 represents the "ISO-8859-2" charset
	CharsetISO88592 Charset = "ISO-8859-2"

	// CharsetISO88593 represents the "ISO-8859-3" charset
	CharsetISO88593 Charset = "ISO-8859-3"

	// CharsetISO88594 represents the "ISO-8859-4" charset
	CharsetISO88594 Charset = "ISO-8859-4"

	// CharsetISO88595 represents the "ISO-8859-5" charset
	CharsetISO88595 Charset = "ISO-8859-5"

	// CharsetISO88596 represents the "ISO-8859-6" charset
	CharsetISO88596 Charset = "ISO-8859-6"

	// CharsetISO88597 represents the "ISO-8859-7" charset
	CharsetISO88597 Charset = "ISO-8859-7"

	// CharsetISO88599 represents the "ISO-8859-9" charset
	CharsetISO88599 Charset = "ISO-8859-9"

	// CharsetISO885913 represents the "ISO-8859-13" charset
	CharsetISO885913 Charset = "ISO-8859-13"

	// CharsetISO885914 represents the "ISO-8859-14" charset
	CharsetISO885914 Charset = "ISO-8859-14"

	// CharsetISO885915 represents the "ISO-8859-15" charset
	CharsetISO885915 Charset = "ISO-8859-15"

	// CharsetISO885916 represents the "ISO-8859-16" charset
	CharsetISO885916 Charset = "ISO-8859-16"

	// CharsetISO2022JP represents the "ISO-2022-JP" charset
	CharsetISO2022JP Charset = "ISO-2022-JP"

	// CharsetISO2022KR represents the "ISO-2022-KR" charset
	CharsetISO2022KR Charset = "ISO-2022-KR"

	// CharsetWindows1250 represents the "windows-1250" charset
	CharsetWindows1250 Charset = "windows-1250"

	// CharsetWindows1251 represents the "windows-1251" charset
	CharsetWindows1251 Charset = "windows-1251"

	// CharsetWindows1252 represents the "windows-1252" charset
	CharsetWindows1252 Charset = "windows-1252"

	// CharsetWindows1255 represents the "windows-1255" charset
	CharsetWindows1255 Charset = "windows-1255"

	// CharsetWindows1256 represents the "windows-1256" charset
	CharsetWindows1256 Charset = "windows-1256"

	// CharsetKOI8R represents the "KOI8-R" charset
	CharsetKOI8R Charset = "KOI8-R"

	// CharsetKOI8U represents the "KOI8-U" charset
	CharsetKOI8U Charset = "KOI8-U"

	// CharsetBig5 represents the "Big5" charset
	CharsetBig5 Charset = "Big5"

	// CharsetGB18030 represents the "GB18030" charset
	CharsetGB18030 Charset = "GB18030"

	// CharsetGB2312 represents the "GB2312" charset
	CharsetGB2312 Charset = "GB2312"

	// CharsetTIS620 represents the "TIS-620" charset
	CharsetTIS620 Charset = "TIS-620"

	// CharsetEUCKR represents the "EUC-KR" charset
	CharsetEUCKR Charset = "EUC-KR"

	// CharsetShiftJIS represents the "Shift_JIS" charset
	CharsetShiftJIS Charset = "Shift_JIS"

	// CharsetUnknown represents the "Unknown" charset
	CharsetUnknown Charset = "Unknown"

	// CharsetGBK represents the "GBK" charset
	CharsetGBK Charset = "GBK"
)

List of common charsets

func (Charset) String

func (c Charset) String() string

String is a standard method to convert an Charset into a printable format

type Client

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

Client is the SMTP client struct

func NewClient

func NewClient(h string, o ...Option) (*Client, error)

NewClient returns a new Session client object

Example

Code example for the NewClient method

c, err := mail.NewClient("mail.example.com")
if err != nil {
	panic(err)
}
_ = c
Output:

func (*Client) Close

func (c *Client) Close() error

Close closes the Client connection

func (*Client) DialAndSend

func (c *Client) DialAndSend(ml ...*Msg) error

DialAndSend establishes a connection to the SMTP server with a default context.Background and sends the mail

Example

Code example for the Client.DialAndSend method

from := "Toni Tester <toni@example.com>"
to := "Alice <alice@example.com>"
server := "mail.example.com"

m := mail.NewMsg()
if err := m.From(from); err != nil {
	fmt.Printf("failed to set FROM address: %s", err)
	os.Exit(1)
}
if err := m.To(to); err != nil {
	fmt.Printf("failed to set TO address: %s", err)
	os.Exit(1)
}
m.Subject("This is a great subject")

c, err := mail.NewClient(server)
if err != nil {
	fmt.Printf("failed to create mail client: %s", err)
	os.Exit(1)
}
if err := c.DialAndSend(m); err != nil {
	fmt.Printf("failed to send mail: %s", err)
	os.Exit(1)
}
Output:

func (*Client) DialAndSendWithContext added in v0.2.8

func (c *Client) DialAndSendWithContext(ctx context.Context, ml ...*Msg) error

DialAndSendWithContext establishes a connection to the SMTP server with a custom context and sends the mail

func (*Client) DialWithContext

func (c *Client) DialWithContext(pc context.Context) error

DialWithContext establishes a connection cto the SMTP server with a given context.Context

func (*Client) Reset

func (c *Client) Reset() error

Reset sends the RSET command to the SMTP client

func (*Client) Send

func (c *Client) Send(ml ...*Msg) (rerr error)

Send sends out the mail message

func (*Client) ServerAddr

func (c *Client) ServerAddr() string

ServerAddr returns the currently set combination of hostname and port

func (*Client) SetDebugLog added in v0.3.9

func (c *Client) SetDebugLog(v bool)

SetDebugLog tells the Client whether debug logging is enabled or not

func (*Client) SetLogger added in v0.3.9

func (c *Client) SetLogger(l log.Logger)

SetLogger tells the Client which log.Logger to use

func (*Client) SetPassword

func (c *Client) SetPassword(p string)

SetPassword overrides the current password string with the given value

func (*Client) SetSMTPAuth

func (c *Client) SetSMTPAuth(a SMTPAuthType)

SetSMTPAuth overrides the current SMTP AUTH type setting with the given value

func (*Client) SetSMTPAuthCustom

func (c *Client) SetSMTPAuthCustom(sa smtp.Auth)

SetSMTPAuthCustom overrides the current SMTP AUTH setting with the given custom smtp.Auth

func (*Client) SetSSL added in v0.1.4

func (c *Client) SetSSL(s bool)

SetSSL tells the Client wether to use SSL or not

func (*Client) SetSSLPort added in v0.4.1

func (c *Client) SetSSLPort(ssl bool, fb bool)

SetSSLPort tells the Client wether or not to use SSL and fallback. The correct port is automatically set.

Port 465 is used when SSL set (true). Port 25 is used when SSL is unset (false). When the SSL connection fails and fb is set to true, the client will attempt to connect on port 25 using plaintext.

func (*Client) SetTLSConfig

func (c *Client) SetTLSConfig(co *tls.Config) error

SetTLSConfig overrides the current *tls.Config with the given *tls.Config value

func (*Client) SetTLSPolicy

func (c *Client) SetTLSPolicy(p TLSPolicy)

SetTLSPolicy overrides the current TLSPolicy with the given TLSPolicy value

Example

Code example for the Client.SetTLSPolicy method

c, err := mail.NewClient("mail.example.com")
if err != nil {
	panic(err)
}
c.SetTLSPolicy(mail.TLSMandatory)
fmt.Println(c.TLSPolicy())
Output:

TLSMandatory

func (*Client) SetTLSPortPolicy added in v0.4.1

func (c *Client) SetTLSPortPolicy(p TLSPolicy)

SetTLSPortPolicy overrides the current TLSPolicy with the given TLSPolicy value. The correct port is automatically set.

Port 587 is used for TLSMandatory and TLSOpportunistic. If the connection fails with TLSOpportunistic, a plaintext connection is attempted on port 25 as a fallback. NoTLS will allways use port 25.

func (*Client) SetUsername

func (c *Client) SetUsername(u string)

SetUsername overrides the current username string with the given value

func (*Client) TLSPolicy

func (c *Client) TLSPolicy() string

TLSPolicy returns the currently set TLSPolicy as string

type ContentType

type ContentType string

ContentType represents a content type for the Msg

const (
	TypeTextPlain      ContentType = "text/plain"
	TypeTextHTML       ContentType = "text/html"
	TypeAppOctetStream ContentType = "application/octet-stream"
	TypePGPSignature   ContentType = "application/pgp-signature"
	TypePGPEncrypted   ContentType = "application/pgp-encrypted"
)

List of common content types

type DSNMailReturnOption added in v0.2.7

type DSNMailReturnOption string

DSNMailReturnOption is a type to define which MAIL RET option is used when a DSN is requested

type DSNRcptNotifyOption added in v0.2.7

type DSNRcptNotifyOption string

DSNRcptNotifyOption is a type to define which RCPT NOTIFY option is used when a DSN is requested

type DialContextFunc added in v0.4.0

type DialContextFunc func(ctx context.Context, network, address string) (net.Conn, error)

DialContextFunc is a type to define custom DialContext function.

type Encoding

type Encoding string

Encoding represents a MIME encoding scheme like quoted-printable or Base64.

const (
	// EncodingB64 represents the Base64 encoding as specified in RFC 2045.
	EncodingB64 Encoding = "base64"

	// EncodingQP represents the "quoted-printable" encoding as specified in RFC 2045.
	EncodingQP Encoding = "quoted-printable"

	// NoEncoding avoids any character encoding (except of the mail headers)
	NoEncoding Encoding = "8bit"
)

List of supported encodings

func (Encoding) String

func (e Encoding) String() string

String is a standard method to convert an Encoding into a printable format

type File added in v0.1.1

type File struct {
	ContentType ContentType
	Desc        string
	Enc         Encoding
	Header      textproto.MIMEHeader
	Name        string
	Writer      func(w io.Writer) (int64, error)
}

File is an attachment or embedded file of the Msg

type FileOption added in v0.1.1

type FileOption func(*File)

FileOption returns a function that can be used for grouping File options

func WithFileContentType added in v0.3.9

func WithFileContentType(t ContentType) FileOption

WithFileContentType sets the content type of the File. By default go-mail will try to guess the file type and its corresponding content type and fall back to application/octet-stream if the file type could not be guessed. In some cases, however, it might be needed to force this to a specific type. For such situations this override method can be used

func WithFileDescription added in v0.3.9

func WithFileDescription(d string) FileOption

WithFileDescription sets an optional file description of the File that will be added as Content-Description part

func WithFileEncoding added in v0.3.9

func WithFileEncoding(e Encoding) FileOption

WithFileEncoding sets the encoding of the File. By default we should always use Base64 encoding but there might be exceptions, where this might come handy. Please note that quoted-printable should never be used for attachments/embeds. If this is provided as argument, the function will automatically override back to Base64

func WithFileName added in v0.1.1

func WithFileName(n string) FileOption

WithFileName sets the filename of the File

type Header string

Header represents a generic mail header field name

const (
	// HeaderContentDescription is the "Content-Description" header
	HeaderContentDescription Header = "Content-Description"

	// HeaderContentDisposition is the "Content-Disposition" header
	HeaderContentDisposition Header = "Content-Disposition"

	// HeaderContentID is the "Content-ID" header
	HeaderContentID Header = "Content-ID"

	// HeaderContentLang is the "Content-Language" header
	HeaderContentLang Header = "Content-Language"

	// HeaderContentLocation is the "Content-Location" header (RFC 2110)
	HeaderContentLocation Header = "Content-Location"

	// HeaderContentTransferEnc is the "Content-Transfer-Encoding" header
	HeaderContentTransferEnc Header = "Content-Transfer-Encoding"

	// HeaderContentType is the "Content-Type" header
	HeaderContentType Header = "Content-Type"

	// HeaderDate represents the "Date" field
	// See: https://www.rfc-editor.org/rfc/rfc822#section-5.1
	HeaderDate Header = "Date"

	// HeaderDispositionNotificationTo is the MDN header as described in RFC8098
	// See: https://www.rfc-editor.org/rfc/rfc8098.html#section-2.1
	HeaderDispositionNotificationTo Header = "Disposition-Notification-To"

	// HeaderImportance represents the "Importance" field
	HeaderImportance Header = "Importance"

	// HeaderInReplyTo represents the "In-Reply-To" field
	HeaderInReplyTo Header = "In-Reply-To"

	// HeaderListUnsubscribe is the "List-Unsubscribe" header field
	HeaderListUnsubscribe Header = "List-Unsubscribe"

	// HeaderListUnsubscribePost is the "List-Unsubscribe-Post" header field
	HeaderListUnsubscribePost Header = "List-Unsubscribe-Post"

	// HeaderMessageID represents the "Message-ID" field for message identification
	// See: https://www.rfc-editor.org/rfc/rfc1036#section-2.1.5
	HeaderMessageID Header = "Message-ID"

	// HeaderMIMEVersion represents the "MIME-Version" field as per RFC 2045
	// See: https://datatracker.ietf.org/doc/html/rfc2045#section-4
	HeaderMIMEVersion Header = "MIME-Version"

	// HeaderOrganization is the "Organization" header field
	HeaderOrganization Header = "Organization"

	// HeaderPrecedence is the "Precedence" header field
	HeaderPrecedence Header = "Precedence"

	// HeaderPriority represents the "Priority" field
	HeaderPriority Header = "Priority"

	// HeaderReplyTo is the "Reply-To" header field
	HeaderReplyTo Header = "Reply-To"

	// HeaderSubject is the "Subject" header field
	HeaderSubject Header = "Subject"

	// HeaderUserAgent is the "User-Agent" header field
	HeaderUserAgent Header = "User-Agent"

	// HeaderXAutoResponseSuppress is the "X-Auto-Response-Suppress" header field
	HeaderXAutoResponseSuppress Header = "X-Auto-Response-Suppress"

	// HeaderXMailer is the "X-Mailer" header field
	HeaderXMailer Header = "X-Mailer"

	// HeaderXMSMailPriority is the "X-MSMail-Priority" header field
	HeaderXMSMailPriority Header = "X-MSMail-Priority"

	// HeaderXPriority is the "X-Priority" header field
	HeaderXPriority Header = "X-Priority"
)

List of common generic header field names

func (Header) String added in v0.1.4

func (h Header) String() string

String returns the header string based on the given Header

type Importance

type Importance int

Importance represents a Importance/Priority value string

const (
	ImportanceLow Importance = iota
	ImportanceNormal
	ImportanceHigh
	ImportanceNonUrgent
	ImportanceUrgent
)

List of Importance values

func (Importance) NumString

func (i Importance) NumString() string

NumString returns the importance number string based on the Importance

func (Importance) String

func (i Importance) String() string

String returns the importance string based on the Importance

func (Importance) XPrioString

func (i Importance) XPrioString() string

XPrioString returns the X-Priority number string based on the Importance

type MIMEType

type MIMEType string

MIMEType represents the MIME type for the mail

const (
	MIMEAlternative MIMEType = "alternative"
	MIMEMixed       MIMEType = "mixed"
	MIMERelated     MIMEType = "related"
)

List of MIMETypes

type MIMEVersion

type MIMEVersion string

MIMEVersion represents the MIME version for the mail

const (
	// Mime10 is the MIME Version 1.0
	Mime10 MIMEVersion = "1.0"
)

List of MIME versions

type Middleware added in v0.2.8

type Middleware interface {
	Handle(*Msg) *Msg
	Type() MiddlewareType
}

Middleware is an interface to define a function to apply to Msg before sending

type MiddlewareType added in v0.3.3

type MiddlewareType string

MiddlewareType is the type description of the Middleware and needs to be returned in the Middleware interface by the Type method

type Msg

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

Msg is the mail message struct

func NewMsg

func NewMsg(o ...MsgOption) *Msg

NewMsg returns a new Msg pointer

Example

Code example for the NewMsg method

m := mail.NewMsg(mail.WithEncoding(mail.EncodingQP), mail.WithCharset(mail.CharsetASCII))
fmt.Printf("%s // %s\n", m.Encoding(), m.Charset())
Output:

quoted-printable // US-ASCII

func (*Msg) AddAlternativeHTMLTemplate added in v0.2.2

func (m *Msg) AddAlternativeHTMLTemplate(t *ht.Template, d interface{}, o ...PartOption) error

AddAlternativeHTMLTemplate sets the alternative body of the message to a html/template.Template output The content type will be set to text/html automatically

func (*Msg) AddAlternativeString

func (m *Msg) AddAlternativeString(ct ContentType, b string, o ...PartOption)

AddAlternativeString sets the alternative body of the message.

func (*Msg) AddAlternativeTextTemplate added in v0.2.2

func (m *Msg) AddAlternativeTextTemplate(t *tt.Template, d interface{}, o ...PartOption) error

AddAlternativeTextTemplate sets the alternative body of the message to a text/template.Template output The content type will be set to text/plain automatically

func (*Msg) AddAlternativeWriter

func (m *Msg) AddAlternativeWriter(ct ContentType, w func(io.Writer) (int64, error), o ...PartOption)

AddAlternativeWriter sets the body of the message.

func (*Msg) AddBcc

func (m *Msg) AddBcc(t string) error

AddBcc adds an additional address to the Bcc address header field

func (*Msg) AddBccFormat

func (m *Msg) AddBccFormat(n, a string) error

AddBccFormat takes a name and address, formats them RFC5322 compliant and stores them as as additional Bcc address header field

func (*Msg) AddCc

func (m *Msg) AddCc(t string) error

AddCc adds an additional address to the Cc address header field

func (*Msg) AddCcFormat

func (m *Msg) AddCcFormat(n, a string) error

AddCcFormat takes a name and address, formats them RFC5322 compliant and stores them as as additional Cc address header field

func (*Msg) AddTo

func (m *Msg) AddTo(t string) error

AddTo adds an additional address to the To address header field

func (*Msg) AddToFormat

func (m *Msg) AddToFormat(n, a string) error

AddToFormat takes a name and address, formats them RFC5322 compliant and stores them as as additional To address header field

func (*Msg) AttachFile added in v0.1.1

func (m *Msg) AttachFile(n string, o ...FileOption)

AttachFile adds an attachment File to the Msg

func (*Msg) AttachFromEmbedFS added in v0.2.5

func (m *Msg) AttachFromEmbedFS(n string, f *embed.FS, o ...FileOption) error

AttachFromEmbedFS adds an attachment File from an embed.FS to the Msg

func (*Msg) AttachHTMLTemplate added in v0.2.2

func (m *Msg) AttachHTMLTemplate(n string, t *ht.Template, d interface{}, o ...FileOption) error

AttachHTMLTemplate adds the output of a html/template.Template pointer as File attachment to the Msg

func (*Msg) AttachReadSeeker added in v0.3.9

func (m *Msg) AttachReadSeeker(n string, r io.ReadSeeker, o ...FileOption)

AttachReadSeeker adds an attachment File via io.ReadSeeker to the Msg

func (*Msg) AttachReader added in v0.1.1

func (m *Msg) AttachReader(n string, r io.Reader, o ...FileOption) error

AttachReader adds an attachment File via io.Reader to the Msg

CAVEAT: For AttachReader to work it has to read all data of the io.Reader into memory first, so it can seek through it. Using larger amounts of data on the io.Reader should be avoided. For such, it is recommended to either use AttachFile or AttachReadSeeker instead

func (*Msg) AttachTextTemplate added in v0.2.2

func (m *Msg) AttachTextTemplate(n string, t *tt.Template, d interface{}, o ...FileOption) error

AttachTextTemplate adds the output of a text/template.Template pointer as File attachment to the Msg

func (*Msg) Bcc

func (m *Msg) Bcc(b ...string) error

Bcc takes and validates a given mail address list sets the Bcc: addresses of the Msg

func (*Msg) BccFromString added in v0.4.1

func (m *Msg) BccFromString(v string) error

BccFromString takes and validates a given string of comma separted mail address and sets them as Bcc: addresses of the Msg

func (*Msg) BccIgnoreInvalid

func (m *Msg) BccIgnoreInvalid(b ...string)

BccIgnoreInvalid takes and validates a given mail address list sets the Bcc: addresses of the Msg Any provided address that is not RFC5322 compliant, will be ignored

func (*Msg) Cc

func (m *Msg) Cc(c ...string) error

Cc takes and validates a given mail address list sets the Cc: addresses of the Msg

func (*Msg) CcFromString added in v0.4.1

func (m *Msg) CcFromString(v string) error

CcFromString takes and validates a given string of comma separted mail address and sets them as Cc: addresses of the Msg

func (*Msg) CcIgnoreInvalid

func (m *Msg) CcIgnoreInvalid(c ...string)

CcIgnoreInvalid takes and validates a given mail address list sets the Cc: addresses of the Msg Any provided address that is not RFC5322 compliant, will be ignored

func (*Msg) Charset

func (m *Msg) Charset() string

Charset returns the currently set charset of the Msg

func (*Msg) EmbedFile added in v0.1.1

func (m *Msg) EmbedFile(n string, o ...FileOption)

EmbedFile adds an embedded File to the Msg

func (*Msg) EmbedFromEmbedFS added in v0.2.5

func (m *Msg) EmbedFromEmbedFS(n string, f *embed.FS, o ...FileOption) error

EmbedFromEmbedFS adds an embedded File from an embed.FS to the Msg

func (*Msg) EmbedHTMLTemplate added in v0.2.2

func (m *Msg) EmbedHTMLTemplate(n string, t *ht.Template, d interface{}, o ...FileOption) error

EmbedHTMLTemplate adds the output of a html/template.Template pointer as embedded File to the Msg

func (*Msg) EmbedReadSeeker added in v0.3.9

func (m *Msg) EmbedReadSeeker(n string, r io.ReadSeeker, o ...FileOption)

EmbedReadSeeker adds an embedded File from an io.ReadSeeker to the Msg

func (*Msg) EmbedReader added in v0.1.1

func (m *Msg) EmbedReader(n string, r io.Reader, o ...FileOption) error

EmbedReader adds an embedded File from an io.Reader to the Msg

CAVEAT: For EmbedReader to work it has to read all data of the io.Reader into memory first, so it can seek through it. Using larger amounts of data on the io.Reader should be avoided. For such, it is recommended to either use EmbedFile or EmbedReadSeeker instead

func (*Msg) EmbedTextTemplate added in v0.2.2

func (m *Msg) EmbedTextTemplate(n string, t *tt.Template, d interface{}, o ...FileOption) error

EmbedTextTemplate adds the output of a text/template.Template pointer as embedded File to the Msg

func (*Msg) Encoding

func (m *Msg) Encoding() string

Encoding returns the currently set encoding of the Msg

func (*Msg) EnvelopeFrom added in v0.2.4

func (m *Msg) EnvelopeFrom(f string) error

EnvelopeFrom takes and validates a given mail address and sets it as envelope "FROM" addrHeader of the Msg

func (*Msg) EnvelopeFromFormat added in v0.2.4

func (m *Msg) EnvelopeFromFormat(n, a string) error

EnvelopeFromFormat takes a name and address, formats them RFC5322 compliant and stores them as the envelope FROM address header field

func (*Msg) From

func (m *Msg) From(f string) error

From takes and validates a given mail address and sets it as "From" genHeader of the Msg

func (*Msg) FromFormat

func (m *Msg) FromFormat(n, a string) error

FromFormat takes a name and address, formats them RFC5322 compliant and stores them as the From address header field

func (*Msg) GetAddrHeader added in v0.3.5

func (m *Msg) GetAddrHeader(h AddrHeader) []*mail.Address

GetAddrHeader returns the content of the requested address header of the Msg

func (*Msg) GetAddrHeaderString added in v0.3.5

func (m *Msg) GetAddrHeaderString(h AddrHeader) []string

GetAddrHeaderString returns the address string of the requested address header of the Msg

func (*Msg) GetAttachments added in v0.3.1

func (m *Msg) GetAttachments() []*File

GetAttachments returns the attachments of the Msg

func (*Msg) GetBcc added in v0.3.5

func (m *Msg) GetBcc() []*mail.Address

GetBcc returns the content of the Bcc address header of the Msg

func (*Msg) GetBccString added in v0.3.5

func (m *Msg) GetBccString() []string

GetBccString returns the content of the Bcc address header of the Msg as string slice

func (*Msg) GetCc added in v0.3.5

func (m *Msg) GetCc() []*mail.Address

GetCc returns the content of the Cc address header of the Msg

func (*Msg) GetCcString added in v0.3.5

func (m *Msg) GetCcString() []string

GetCcString returns the content of the Cc address header of the Msg as string slice

func (*Msg) GetEmbeds added in v0.3.9

func (m *Msg) GetEmbeds() []*File

GetEmbeds returns the embeds of the Msg

func (*Msg) GetFrom added in v0.3.5

func (m *Msg) GetFrom() []*mail.Address

GetFrom returns the content of the From address header of the Msg

func (*Msg) GetFromString added in v0.3.5

func (m *Msg) GetFromString() []string

GetFromString returns the content of the From address header of the Msg as string slice

func (*Msg) GetGenHeader added in v0.2.9

func (m *Msg) GetGenHeader(h Header) []string

GetGenHeader returns the content of the requested generic header of the Msg

func (*Msg) GetParts added in v0.3.0

func (m *Msg) GetParts() []*Part

GetParts returns the message parts of the Msg

func (*Msg) GetRecipients

func (m *Msg) GetRecipients() ([]string, error)

GetRecipients returns a list of the currently set TO/CC/BCC addresses.

func (*Msg) GetSender

func (m *Msg) GetSender(ff bool) (string, error)

GetSender returns the currently set envelope FROM address. If no envelope FROM is set it will use the first mail body FROM address. If ff is true, it will return the full address string including the address name, if set

func (*Msg) GetTo added in v0.3.5

func (m *Msg) GetTo() []*mail.Address

GetTo returns the content of the To address header of the Msg

func (*Msg) GetToString added in v0.3.5

func (m *Msg) GetToString() []string

GetToString returns the content of the To address header of the Msg as string slice

func (*Msg) HasSendError added in v0.3.7

func (m *Msg) HasSendError() bool

HasSendError returns true if the Msg experienced an error during the message delivery and the sendError field of the Msg is not nil

func (*Msg) IsDelivered added in v0.4.1

func (m *Msg) IsDelivered() bool

IsDelivered will return true if the Msg has been successfully delivered

func (*Msg) NewReader added in v0.3.2

func (m *Msg) NewReader() *Reader

NewReader returns a Reader type that satisfies the io.Reader interface.

IMPORTANT: when creating a new Reader, the current state of the Msg is taken, as basis for the Reader. If you perform changes on Msg after creating the Reader, these changes will not be reflected in the Reader. You will have to use Msg.UpdateReader first to update the Reader's buffer with the current Msg content

func (*Msg) ReplyTo

func (m *Msg) ReplyTo(r string) error

ReplyTo takes and validates a given mail address and sets it as "Reply-To" addrHeader of the Msg

func (*Msg) ReplyToFormat

func (m *Msg) ReplyToFormat(n, a string) error

ReplyToFormat takes a name and address, formats them RFC5322 compliant and stores them as the Reply-To header field

func (*Msg) RequestMDNAddTo added in v0.2.7

func (m *Msg) RequestMDNAddTo(t string) error

RequestMDNAddTo adds an additional recipient to the recipient list of the MDN

func (*Msg) RequestMDNAddToFormat added in v0.2.7

func (m *Msg) RequestMDNAddToFormat(n, a string) error

RequestMDNAddToFormat adds an additional formated recipient to the recipient list of the MDN

func (*Msg) RequestMDNTo added in v0.2.7

func (m *Msg) RequestMDNTo(t ...string) error

RequestMDNTo adds the Disposition-Notification-To header to request a MDN from the receiving end as described in RFC8098. It allows to provide a list recipient addresses. Address validation is performed See: https://www.rfc-editor.org/rfc/rfc8098.html

func (*Msg) RequestMDNToFormat added in v0.2.7

func (m *Msg) RequestMDNToFormat(n, a string) error

RequestMDNToFormat adds the Disposition-Notification-To header to request a MDN from the receiving end as described in RFC8098. It allows to provide a recipient address with name and address and will format accordingly. Address validation is performed See: https://www.rfc-editor.org/rfc/rfc8098.html

func (*Msg) Reset added in v0.1.2

func (m *Msg) Reset()

Reset resets all headers, body parts and attachments/embeds of the Msg It leaves already set encodings, charsets, boundaries, etc. as is

func (*Msg) SendError added in v0.3.7

func (m *Msg) SendError() error

SendError returns the sendError field of the Msg

func (*Msg) SendErrorIsTemp added in v0.3.7

func (m *Msg) SendErrorIsTemp() bool

SendErrorIsTemp returns true if the Msg experienced an error during the message delivery and the corresponding error was of temporary nature and should be retried later

func (*Msg) SetAddrHeader

func (m *Msg) SetAddrHeader(h AddrHeader, v ...string) error

SetAddrHeader sets an address related header field of the Msg

func (*Msg) SetAddrHeaderIgnoreInvalid

func (m *Msg) SetAddrHeaderIgnoreInvalid(h AddrHeader, v ...string)

SetAddrHeaderIgnoreInvalid sets an address related header field of the Msg and ignores invalid address in the validation process

func (*Msg) SetAttachements added in v0.3.1

func (m *Msg) SetAttachements(ff []*File)

SetAttachements sets the attachements of the message.

func (*Msg) SetBodyHTMLTemplate added in v0.2.2

func (m *Msg) SetBodyHTMLTemplate(t *ht.Template, d interface{}, o ...PartOption) error

SetBodyHTMLTemplate sets the body of the message from a given html/template.Template pointer The content type will be set to text/html automatically

func (*Msg) SetBodyString

func (m *Msg) SetBodyString(ct ContentType, b string, o ...PartOption)

SetBodyString sets the body of the message.

Example (DifferentTypes)

This code example shows how to use Msg.SetBodyString to set a string as message body with different content types

m := mail.NewMsg()
m.SetBodyString(mail.TypeTextPlain, "This is a mail body that with content type: text/plain")
m.SetBodyString(mail.TypeTextHTML, "<p>This is a mail body that with content type: text/html</p>")
Output:

Example (WithPartOption)

This code example shows how to use Msg.SetBodyString to set a string as message body a PartOption to override the default encoding

m := mail.NewMsg(mail.WithEncoding(mail.EncodingB64))
m.SetBodyString(mail.TypeTextPlain, "This is a mail body that with content type: text/plain",
	mail.WithPartEncoding(mail.EncodingQP))
Output:

func (*Msg) SetBodyTextTemplate added in v0.2.2

func (m *Msg) SetBodyTextTemplate(t *tt.Template, d interface{}, o ...PartOption) error

SetBodyTextTemplate sets the body of the message from a given text/template.Template pointer The content type will be set to text/plain automatically

Example

This code example shows how to use a text/template as message Body. Msg.SetBodyHTMLTemplate works anolog to this just with html/template instead

type MyStruct struct {
	Placeholder string
}
data := MyStruct{Placeholder: "Teststring"}
tpl, err := template.New("test").Parse("This is a {{.Placeholder}}")
if err != nil {
	panic(err)
}

m := mail.NewMsg()
if err := m.SetBodyTextTemplate(tpl, data); err != nil {
	panic(err)
}
Output:

func (*Msg) SetBodyWriter

func (m *Msg) SetBodyWriter(ct ContentType, w func(io.Writer) (int64, error), o ...PartOption)

SetBodyWriter sets the body of the message.

func (*Msg) SetBoundary

func (m *Msg) SetBoundary(b string)

SetBoundary sets the boundary of the Msg

func (*Msg) SetBulk

func (m *Msg) SetBulk()

SetBulk sets the "Precedence: bulk" and "X-Auto-Response-Suppress: All" genHeaders which are recommended for automated mails like OOO replies See: https://www.rfc-editor.org/rfc/rfc2076#section-3.9 See also: https://learn.microsoft.com/en-us/openspecs/exchange_server_protocols/ms-oxcmail/ced68690-498a-4567-9d14-5c01f974d8b1#Appendix_A_Target_51

func (*Msg) SetCharset

func (m *Msg) SetCharset(c Charset)

SetCharset sets the encoding charset of the Msg

func (*Msg) SetDate

func (m *Msg) SetDate()

SetDate sets the Date genHeader field to the current time in a valid format

func (*Msg) SetDateWithValue added in v0.1.2

func (m *Msg) SetDateWithValue(t time.Time)

SetDateWithValue sets the Date genHeader field to the provided time in a valid format

func (*Msg) SetEmbeds added in v0.3.9

func (m *Msg) SetEmbeds(ff []*File)

SetEmbeds sets the embeds of the message.

func (*Msg) SetEncoding

func (m *Msg) SetEncoding(e Encoding)

SetEncoding sets the encoding of the Msg

func (*Msg) SetGenHeader added in v0.3.5

func (m *Msg) SetGenHeader(h Header, v ...string)

SetGenHeader sets a generic header field of the Msg For adding address headers like "To:" or "From", see SetAddrHeader

func (*Msg) SetGenHeaderPreformatted added in v0.3.5

func (m *Msg) SetGenHeaderPreformatted(h Header, v string)

SetGenHeaderPreformatted sets a generic header field of the Msg which content is already preformated.

This method does not take a slice of values but only a single value. This is due to the fact, that we do not perform any content alteration and expect the user has already done so

**Please note:** This method should be used only as a last resort. Since the user is respondible for the formating of the message header, go-mail cannot guarantee the fully compliance with the RFC 2822. It is recommended to use SetGenHeader instead.

func (*Msg) SetHeader deprecated

func (m *Msg) SetHeader(h Header, v ...string)

SetHeader sets a generic header field of the Msg For adding address headers like "To:" or "From", see SetAddrHeader

Deprecated: This method only exists for compatibility reason. Please use SetGenHeader instead

func (*Msg) SetHeaderPreformatted deprecated added in v0.3.4

func (m *Msg) SetHeaderPreformatted(h Header, v string)

SetHeaderPreformatted sets a generic header field of the Msg which content is already preformated.

Deprecated: This method only exists for compatibility reason. Please use SetGenHeaderPreformatted instead

func (*Msg) SetImportance

func (m *Msg) SetImportance(i Importance)

SetImportance sets the Msg Importance/Priority header to given Importance

func (*Msg) SetMIMEVersion

func (m *Msg) SetMIMEVersion(mv MIMEVersion)

SetMIMEVersion sets the MIME version of the Msg

func (*Msg) SetMessageID

func (m *Msg) SetMessageID()

SetMessageID generates a random message id for the mail

func (*Msg) SetMessageIDWithValue

func (m *Msg) SetMessageIDWithValue(v string)

SetMessageIDWithValue sets the message id for the mail

func (*Msg) SetOrganization added in v0.1.3

func (m *Msg) SetOrganization(o string)

SetOrganization sets the provided string as Organization header for the Msg

func (*Msg) SetPGPType added in v0.3.9

func (m *Msg) SetPGPType(t PGPType)

SetPGPType sets the PGPType of the Msg

func (*Msg) SetUserAgent added in v0.1.3

func (m *Msg) SetUserAgent(a string)

SetUserAgent sets the User-Agent/X-Mailer header for the Msg

func (*Msg) Subject

func (m *Msg) Subject(s string)

Subject sets the "Subject" header field of the Msg

func (*Msg) To

func (m *Msg) To(t ...string) error

To takes and validates a given mail address list sets the To: addresses of the Msg

func (*Msg) ToFromString added in v0.4.1

func (m *Msg) ToFromString(v string) error

ToFromString takes and validates a given string of comma separted mail address and sets them as To: addresses of the Msg

func (*Msg) ToIgnoreInvalid

func (m *Msg) ToIgnoreInvalid(t ...string)

ToIgnoreInvalid takes and validates a given mail address list sets the To: addresses of the Msg Any provided address that is not RFC5322 compliant, will be ignored

func (*Msg) UnsetAllAttachments added in v0.4.1

func (m *Msg) UnsetAllAttachments()

UnsetAllAttachments unset the attachments of the message.

func (*Msg) UnsetAllEmbeds added in v0.4.1

func (m *Msg) UnsetAllEmbeds()

UnsetAllEmbeds unset the embeds of the message.

func (*Msg) UnsetAllParts added in v0.4.1

func (m *Msg) UnsetAllParts()

UnsetAllParts unset the embeds and attachments of the message.

func (*Msg) UpdateReader added in v0.3.2

func (m *Msg) UpdateReader(r *Reader)

UpdateReader will update a Reader with the content of the given Msg and reset the Reader position to the start

func (*Msg) Write

func (m *Msg) Write(w io.Writer) (int64, error)

Write is an alias method to WriteTo due to compatibility reasons

func (*Msg) WriteTo added in v0.1.9

func (m *Msg) WriteTo(w io.Writer) (int64, error)

WriteTo writes the formated Msg into a give io.Writer and satisfies the io.WriteTo interface

func (*Msg) WriteToFile added in v0.2.3

func (m *Msg) WriteToFile(n string) error

WriteToFile stores the Msg as file on disk. It will try to create the given filename Already existing files will be overwritten

func (*Msg) WriteToSendmail added in v0.1.2

func (m *Msg) WriteToSendmail() error

WriteToSendmail returns WriteToSendmailWithCommand with a default sendmail path

Example

This code example shows how to utilize the Msg.WriteToSendmail method to send generated mails using a local sendmail installation

m := mail.NewMsg()
m.SetBodyString(mail.TypeTextPlain, "This is the mail body string")
if err := m.FromFormat("Toni Tester", "toni.tester@example.com"); err != nil {
	panic(err)
}
if err := m.To("gandalf.tester@example.com"); err != nil {
	panic(err)
}
if err := m.WriteToSendmail(); err != nil {
	panic(err)
}
Output:

func (*Msg) WriteToSendmailWithCommand added in v0.1.5

func (m *Msg) WriteToSendmailWithCommand(sp string) error

WriteToSendmailWithCommand returns WriteToSendmailWithContext with a default timeout of 5 seconds and a given sendmail path

func (*Msg) WriteToSendmailWithContext added in v0.1.2

func (m *Msg) WriteToSendmailWithContext(ctx context.Context, sp string, a ...string) error

WriteToSendmailWithContext opens an pipe to the local sendmail binary and tries to send the mail though that. It takes a context.Context, the path to the sendmail binary and additional arguments for the sendmail binary as parameters

Example

This code example shows how to send generated mails using a custom context and sendmail-compatbile command using the Msg.WriteToSendmailWithContext method

sendmailPath := "/opt/sendmail/sbin/sendmail"
ctx, cancel := context.WithTimeout(context.Background(), time.Second*5)
defer cancel()

m := mail.NewMsg()
m.SetBodyString(mail.TypeTextPlain, "This is the mail body string")
if err := m.FromFormat("Toni Tester", "toni.tester@example.com"); err != nil {
	panic(err)
}
if err := m.To("gandalf.tester@example.com"); err != nil {
	panic(err)
}
if err := m.WriteToSendmailWithContext(ctx, sendmailPath); err != nil {
	panic(err)
}
Output:

func (*Msg) WriteToSkipMiddleware added in v0.3.3

func (m *Msg) WriteToSkipMiddleware(w io.Writer, mt MiddlewareType) (int64, error)

WriteToSkipMiddleware writes the formated Msg into a give io.Writer and satisfies the io.WriteTo interface but will skip the given Middleware

func (*Msg) WriteToTempFile added in v0.2.3

func (m *Msg) WriteToTempFile() (string, error)

WriteToTempFile will create a temporary file and output the Msg to this file The method will return the filename of the temporary file

type MsgOption

type MsgOption func(*Msg)

MsgOption returns a function that can be used for grouping Msg options

func WithBoundary added in v0.1.4

func WithBoundary(b string) MsgOption

WithBoundary overrides the default MIME boundary

func WithCharset

func WithCharset(c Charset) MsgOption

WithCharset overrides the default message charset

func WithEncoding

func WithEncoding(e Encoding) MsgOption

WithEncoding overrides the default message encoding

func WithMIMEVersion

func WithMIMEVersion(mv MIMEVersion) MsgOption

WithMIMEVersion overrides the default MIME version

func WithMiddleware added in v0.2.8

func WithMiddleware(mw Middleware) MsgOption

WithMiddleware add the given middleware in the end of the list of the client middlewares

func WithPGPType added in v0.3.9

func WithPGPType(t PGPType) MsgOption

WithPGPType overrides the default PGPType of the message

type Option

type Option func(*Client) error

Option returns a function that can be used for grouping Client options

func WithDSN added in v0.2.7

func WithDSN() Option

WithDSN enables the Client to request DSNs (if the server supports it) as described in the RFC 1891 and set defaults for DSNMailReturnOption to DSNMailReturnFull and DSNRcptNotifyOption to DSNRcptNotifySuccess and DSNRcptNotifyFailure

func WithDSNMailReturnType added in v0.2.7

func WithDSNMailReturnType(mro DSNMailReturnOption) Option

WithDSNMailReturnType enables the Client to request DSNs (if the server supports it) as described in the RFC 1891 and set the MAIL FROM Return option type to the given DSNMailReturnOption See: https://www.rfc-editor.org/rfc/rfc1891

func WithDSNRcptNotifyType added in v0.2.7

func WithDSNRcptNotifyType(rno ...DSNRcptNotifyOption) Option

WithDSNRcptNotifyType enables the Client to request DSNs as described in the RFC 1891 and sets the RCPT TO notify options to the given list of DSNRcptNotifyOption See: https://www.rfc-editor.org/rfc/rfc1891

func WithDebugLog added in v0.3.9

func WithDebugLog() Option

WithDebugLog tells the client to log incoming and outgoing messages of the SMTP client to StdErr

func WithDialContextFunc added in v0.4.0

func WithDialContextFunc(f DialContextFunc) Option

WithDialContextFunc overrides the default DialContext for connecting SMTP server

func WithHELO

func WithHELO(h string) Option

WithHELO tells the client to use the provided string as HELO/EHLO greeting host

func WithLogger added in v0.3.9

func WithLogger(l log.Logger) Option

WithLogger overrides the default log.Logger that is used for debug logging

func WithPassword

func WithPassword(p string) Option

WithPassword tells the client to use the provided string as password/secret for authentication

func WithPort

func WithPort(p int) Option

WithPort overrides the default connection port

func WithSMTPAuth

func WithSMTPAuth(t SMTPAuthType) Option

WithSMTPAuth tells the client to use the provided SMTPAuthType for authentication

func WithSMTPAuthCustom

func WithSMTPAuthCustom(a smtp.Auth) Option

WithSMTPAuthCustom tells the client to use the provided smtp.Auth for SMTP authentication

func WithSSL deprecated

func WithSSL() Option

WithSSL tells the client to use a SSL/TLS connection

Deprecated: use WithSSLPort instead.

func WithSSLPort added in v0.4.1

func WithSSLPort(fb bool) Option

WithSSLPort tells the client to use a SSL/TLS connection. It automatically sets the port to 465.

When the SSL connection fails and fallback is set to true, the client will attempt to connect on port 25 using plaintext.

func WithTLSConfig

func WithTLSConfig(co *tls.Config) Option

WithTLSConfig tells the client to use the provided *tls.Config

func WithTLSPolicy deprecated

func WithTLSPolicy(p TLSPolicy) Option

WithTLSPolicy tells the client to use the provided TLSPolicy

Deprecated: use WithTLSPortPolicy instead.

func WithTLSPortPolicy added in v0.4.1

func WithTLSPortPolicy(p TLSPolicy) Option

WithTLSPortPolicy tells the client to use the provided TLSPolicy, The correct port is automatically set.

Port 587 is used for TLSMandatory and TLSOpportunistic. If the connection fails with TLSOpportunistic, a plaintext connection is attempted on port 25 as a fallback. NoTLS will allways use port 25.

func WithTimeout

func WithTimeout(t time.Duration) Option

WithTimeout overrides the default connection timeout

func WithUsername

func WithUsername(u string) Option

WithUsername tells the client to use the provided string as username for authentication

func WithoutNoop added in v0.3.6

func WithoutNoop() Option

WithoutNoop disables the Client Noop check during connections. This is primarily for servers which delay responses to SMTP commands that are not the AUTH command. For example Microsoft Exchange's Tarpit.

type PGPType added in v0.3.9

type PGPType int

PGPType is a type alias for a int representing a type of PGP encryption or signature

const (
	// NoPGP indicates that a message should not be treated as PGP encrypted
	// or signed and is the default value for a message
	NoPGP PGPType = iota
	// PGPEncrypt indicates that a message should be treated as PGP encrypted
	// This works closely together with the corresponding go-mail-middleware
	PGPEncrypt
	// PGPSignature indicates that a message should be treated as PGP signed
	// This works closely together with the corresponding go-mail-middleware
	PGPSignature
)

type Part

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

Part is a part of the Msg

func (*Part) Delete added in v0.3.9

func (p *Part) Delete()

Delete removes the current part from the parts list of the Msg by setting the del flag to true. The msgWriter will skip it then

func (*Part) GetCharset added in v0.4.1

func (p *Part) GetCharset() Charset

GetCharset returns the currently set Charset of the Part

func (*Part) GetContent added in v0.3.0

func (p *Part) GetContent() ([]byte, error)

GetContent executes the WriteFunc of the Part and returns the content as byte slice

func (*Part) GetContentType added in v0.3.0

func (p *Part) GetContentType() ContentType

GetContentType returns the currently set ContentType of the Part

func (*Part) GetDescription added in v0.3.9

func (p *Part) GetDescription() string

GetDescription returns the currently set Content-Description of the Part

func (*Part) GetEncoding added in v0.3.0

func (p *Part) GetEncoding() Encoding

GetEncoding returns the currently set Encoding of the Part

func (*Part) GetWriteFunc added in v0.3.0

func (p *Part) GetWriteFunc() func(io.Writer) (int64, error)

GetWriteFunc returns the currently set WriterFunc of the Part

func (*Part) SetCharset added in v0.4.1

func (p *Part) SetCharset(c Charset)

SetCharset overrides the Charset of the Part

func (*Part) SetContent added in v0.3.0

func (p *Part) SetContent(c string)

SetContent overrides the content of the Part with the given string

func (*Part) SetContentType added in v0.3.0

func (p *Part) SetContentType(c ContentType)

SetContentType overrides the ContentType of the Part

func (*Part) SetDescription added in v0.3.9

func (p *Part) SetDescription(d string)

SetDescription overrides the Content-Description of the Part

func (*Part) SetEncoding

func (p *Part) SetEncoding(e Encoding)

SetEncoding creates a new mime.WordEncoder based on the encoding setting of the message

func (*Part) SetWriteFunc added in v0.3.0

func (p *Part) SetWriteFunc(w func(io.Writer) (int64, error))

SetWriteFunc overrides the WriteFunc of the Part

type PartOption

type PartOption func(*Part)

PartOption returns a function that can be used for grouping Part options

func WithPartCharset added in v0.4.1

func WithPartCharset(c Charset) PartOption

WithPartCharset overrides the default Part charset

func WithPartContentDescription added in v0.3.9

func WithPartContentDescription(d string) PartOption

WithPartContentDescription overrides the default Part Content-Description

func WithPartEncoding

func WithPartEncoding(e Encoding) PartOption

WithPartEncoding overrides the default Part encoding

type Reader added in v0.3.2

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

Reader is a type that implements the io.Reader interface for a Msg

func (*Reader) Error added in v0.3.2

func (r *Reader) Error() error

Error returns an error if the Reader err field is not nil

func (*Reader) Read added in v0.3.2

func (r *Reader) Read(p []byte) (n int, err error)

Read reads the length of p of the Msg buffer to satisfy the io.Reader interface

func (*Reader) Reset added in v0.3.2

func (r *Reader) Reset()

Reset resets the Reader buffer to be empty, but it retains the underlying storage for use by future writes.

type SMTPAuthType

type SMTPAuthType string

SMTPAuthType represents a string to any SMTP AUTH type

const (
	// SMTPAuthLogin is the "LOGIN" SASL authentication mechanism
	SMTPAuthLogin SMTPAuthType = "LOGIN"

	// SMTPAuthPlain is the "PLAIN" authentication mechanism as described in RFC 4616
	SMTPAuthPlain SMTPAuthType = "PLAIN"

	// SMTPAuthCramMD5 is the "CRAM-MD5" SASL authentication mechanism as described in RFC 4954
	SMTPAuthCramMD5 SMTPAuthType = "CRAM-MD5"

	// SMTPAuthXOAUTH2 is the "XOAUTH2" SASL authentication mechanism.
	// https://developers.google.com/gmail/imap/xoauth2-protocol
	SMTPAuthXOAUTH2 SMTPAuthType = "XOAUTH2"
)

Supported SMTP AUTH types

type SendErrReason added in v0.3.7

type SendErrReason int

SendErrReason represents a comparable reason on why the delivery failed

const (
	// ErrGetSender is returned if the Msg.GetSender method fails during a Client.Send
	ErrGetSender SendErrReason = iota

	// ErrGetRcpts is returned if the Msg.GetRecipients method fails during a Client.Send
	ErrGetRcpts

	// ErrSMTPMailFrom is returned if the Msg delivery failed when sending the MAIL FROM command
	// to the sending SMTP server
	ErrSMTPMailFrom

	// ErrSMTPRcptTo is returned if the Msg delivery failed when sending the RCPT TO command
	// to the sending SMTP server
	ErrSMTPRcptTo

	// ErrSMTPData is returned if the Msg delivery failed when sending the DATA command
	// to the sending SMTP server
	ErrSMTPData

	// ErrSMTPDataClose is returned if the Msg delivery failed when trying to close the
	// Client data writer
	ErrSMTPDataClose

	// ErrSMTPReset is returned if the Msg delivery failed when sending the RSET command
	// to the sending SMTP server
	ErrSMTPReset

	// ErrWriteContent is returned if the Msg delivery failed when sending Msg content
	// to the Client writer
	ErrWriteContent

	// ErrConnCheck is returned if the Msg delivery failed when checking if the SMTP
	// server connection is still working
	ErrConnCheck

	// ErrNoUnencoded is returned if the Msg delivery failed when the Msg is configured for
	// unencoded delivery but the server does not support this
	ErrNoUnencoded

	// ErrAmbiguous is a generalized delivery error for the SendError type that is
	// returned if the exact reason for the delivery failure is ambiguous
	ErrAmbiguous
)

List of SendError reasons

func (SendErrReason) String added in v0.3.7

func (r SendErrReason) String() string

String implements the Stringer interface for the SendErrReason

type SendError added in v0.3.7

type SendError struct {
	Reason SendErrReason
	// contains filtered or unexported fields
}

SendError is an error wrapper for delivery errors of the Msg

func (*SendError) Error added in v0.3.7

func (e *SendError) Error() string

Error implements the error interface for the SendError type

func (*SendError) Is added in v0.3.7

func (e *SendError) Is(et error) bool

Is implements the errors.Is functionality and compares the SendErrReason

func (*SendError) IsTemp added in v0.3.7

func (e *SendError) IsTemp() bool

IsTemp returns true if the delivery error is of temporary nature and can be retried

type TLSPolicy

type TLSPolicy int

TLSPolicy type describes a int alias for the different TLS policies we allow

const (
	// TLSMandatory requires that the connection cto the server is
	// encrypting using STARTTLS. If the server does not support STARTTLS
	// the connection will be terminated with an error
	TLSMandatory TLSPolicy = iota

	// TLSOpportunistic tries cto establish an encrypted connection via the
	// STARTTLS protocol. If the server does not support this, it will fall
	// back cto non-encrypted plaintext transmission
	TLSOpportunistic

	// NoTLS forces the transaction cto be not encrypted
	NoTLS
)

func (TLSPolicy) String

func (p TLSPolicy) String() string

String is a standard method to convert a TLSPolicy into a printable format

Directories

Path Synopsis
Package log implements a logger interface that can be used within the go-mail package
Package log implements a logger interface that can be used within the go-mail package
Package smtp implements the Simple Mail Transfer Protocol as defined in RFC 5321.
Package smtp implements the Simple Mail Transfer Protocol as defined in RFC 5321.

Jump to

Keyboard shortcuts

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