Documentation ¶
Overview ¶
Package mail provides a simple and easy way to send mails with Go
Index ¶
- Constants
- Variables
- type AddrHeader
- type Base64LineBreaker
- type Charset
- type Client
- func (c *Client) Close() error
- func (c *Client) DialAndSend(messages ...*Msg) error
- func (c *Client) DialAndSendWithContext(ctx context.Context, messages ...*Msg) error
- func (c *Client) DialWithContext(dialCtx context.Context) error
- func (c *Client) Reset() error
- func (c *Client) Send(messages ...*Msg) (returnErr error)
- func (c *Client) ServerAddr() string
- func (c *Client) SetDebugLog(val bool)
- func (c *Client) SetLogger(logger log.Logger)
- func (c *Client) SetPassword(password string)
- func (c *Client) SetSMTPAuth(authtype SMTPAuthType)
- func (c *Client) SetSMTPAuthCustom(smtpAuth smtp.Auth)
- func (c *Client) SetSSL(ssl bool)
- func (c *Client) SetSSLPort(ssl bool, fallback bool)
- func (c *Client) SetTLSConfig(tlsconfig *tls.Config) error
- func (c *Client) SetTLSPolicy(policy TLSPolicy)
- func (c *Client) SetTLSPortPolicy(policy TLSPolicy)
- func (c *Client) SetUsername(username string)
- func (c *Client) TLSPolicy() string
- type ContentType
- type DSNMailReturnOption
- type DSNRcptNotifyOption
- type DialContextFunc
- type Encoding
- type File
- type FileOption
- type Header
- type Importance
- type MIMEType
- type MIMEVersion
- type Middleware
- type MiddlewareType
- type Msg
- func (m *Msg) AddAlternativeHTMLTemplate(tpl *ht.Template, data interface{}, opts ...PartOption) error
- func (m *Msg) AddAlternativeString(contentType ContentType, content string, opts ...PartOption)
- func (m *Msg) AddAlternativeTextTemplate(tpl *tt.Template, data interface{}, opts ...PartOption) error
- func (m *Msg) AddAlternativeWriter(contentType ContentType, writeFunc func(io.Writer) (int64, error), ...)
- func (m *Msg) AddBcc(rcpt string) error
- func (m *Msg) AddBccFormat(name, addr string) error
- func (m *Msg) AddCc(rcpt string) error
- func (m *Msg) AddCcFormat(name, addr string) error
- func (m *Msg) AddTo(rcpt string) error
- func (m *Msg) AddToFormat(name, addr string) error
- func (m *Msg) AttachFile(name string, opts ...FileOption)
- func (m *Msg) AttachFromEmbedFS(name string, fs *embed.FS, opts ...FileOption) error
- func (m *Msg) AttachHTMLTemplate(name string, tpl *ht.Template, data interface{}, opts ...FileOption) error
- func (m *Msg) AttachReadSeeker(name string, reader io.ReadSeeker, opts ...FileOption)
- func (m *Msg) AttachReader(name string, reader io.Reader, opts ...FileOption) error
- func (m *Msg) AttachTextTemplate(name string, tpl *tt.Template, data interface{}, opts ...FileOption) error
- func (m *Msg) Bcc(rcpts ...string) error
- func (m *Msg) BccFromString(rcpts string) error
- func (m *Msg) BccIgnoreInvalid(rcpts ...string)
- func (m *Msg) Cc(rcpts ...string) error
- func (m *Msg) CcFromString(rcpts string) error
- func (m *Msg) CcIgnoreInvalid(rcpts ...string)
- func (m *Msg) Charset() string
- func (m *Msg) EmbedFile(name string, opts ...FileOption)
- func (m *Msg) EmbedFromEmbedFS(name string, fs *embed.FS, opts ...FileOption) error
- func (m *Msg) EmbedHTMLTemplate(name string, tpl *ht.Template, data interface{}, opts ...FileOption) error
- func (m *Msg) EmbedReadSeeker(name string, reader io.ReadSeeker, opts ...FileOption)
- func (m *Msg) EmbedReader(name string, reader io.Reader, opts ...FileOption) error
- func (m *Msg) EmbedTextTemplate(name string, tpl *tt.Template, data interface{}, opts ...FileOption) error
- func (m *Msg) Encoding() string
- func (m *Msg) EnvelopeFrom(from string) error
- func (m *Msg) EnvelopeFromFormat(name, addr string) error
- func (m *Msg) From(from string) error
- func (m *Msg) FromFormat(name, addr string) error
- func (m *Msg) GetAddrHeader(header AddrHeader) []*mail.Address
- func (m *Msg) GetAddrHeaderString(header AddrHeader) []string
- func (m *Msg) GetAttachments() []*File
- func (m *Msg) GetBcc() []*mail.Address
- func (m *Msg) GetBccString() []string
- func (m *Msg) GetBoundary() string
- func (m *Msg) GetCc() []*mail.Address
- func (m *Msg) GetCcString() []string
- func (m *Msg) GetEmbeds() []*File
- func (m *Msg) GetFrom() []*mail.Address
- func (m *Msg) GetFromString() []string
- func (m *Msg) GetGenHeader(header Header) []string
- func (m *Msg) GetParts() []*Part
- func (m *Msg) GetRecipients() ([]string, error)
- func (m *Msg) GetSender(useFullAddr bool) (string, error)
- func (m *Msg) GetTo() []*mail.Address
- func (m *Msg) GetToString() []string
- func (m *Msg) HasSendError() bool
- func (m *Msg) IsDelivered() bool
- func (m *Msg) NewReader() *Reader
- func (m *Msg) ReplyTo(addr string) error
- func (m *Msg) ReplyToFormat(name, addr string) error
- func (m *Msg) RequestMDNAddTo(rcpt string) error
- func (m *Msg) RequestMDNAddToFormat(name, addr string) error
- func (m *Msg) RequestMDNTo(rcpts ...string) error
- func (m *Msg) RequestMDNToFormat(name, addr string) error
- func (m *Msg) Reset()
- func (m *Msg) SendError() error
- func (m *Msg) SendErrorIsTemp() bool
- func (m *Msg) SetAddrHeader(header AddrHeader, values ...string) error
- func (m *Msg) SetAddrHeaderIgnoreInvalid(header AddrHeader, values ...string)
- func (m *Msg) SetAttachements(files []*File)deprecated
- func (m *Msg) SetAttachments(files []*File)
- func (m *Msg) SetBodyHTMLTemplate(tpl *ht.Template, data interface{}, opts ...PartOption) error
- func (m *Msg) SetBodyString(contentType ContentType, content string, opts ...PartOption)
- func (m *Msg) SetBodyTextTemplate(tpl *tt.Template, data interface{}, opts ...PartOption) error
- func (m *Msg) SetBodyWriter(contentType ContentType, writeFunc func(io.Writer) (int64, error), ...)
- func (m *Msg) SetBoundary(b string)
- func (m *Msg) SetBulk()
- func (m *Msg) SetCharset(c Charset)
- func (m *Msg) SetDate()
- func (m *Msg) SetDateWithValue(timeVal time.Time)
- func (m *Msg) SetEmbeds(files []*File)
- func (m *Msg) SetEncoding(e Encoding)
- func (m *Msg) SetGenHeader(header Header, values ...string)
- func (m *Msg) SetGenHeaderPreformatted(header Header, value string)
- func (m *Msg) SetHeader(header Header, values ...string)deprecated
- func (m *Msg) SetHeaderPreformatted(header Header, value string)deprecated
- func (m *Msg) SetImportance(importance Importance)
- func (m *Msg) SetMIMEVersion(mv MIMEVersion)
- func (m *Msg) SetMessageID()
- func (m *Msg) SetMessageIDWithValue(messageID string)
- func (m *Msg) SetOrganization(org string)
- func (m *Msg) SetPGPType(t PGPType)
- func (m *Msg) SetUserAgent(userAgent string)
- func (m *Msg) Subject(subj string)
- func (m *Msg) To(rcpts ...string) error
- func (m *Msg) ToFromString(rcpts string) error
- func (m *Msg) ToIgnoreInvalid(rcpts ...string)
- func (m *Msg) UnsetAllAttachments()
- func (m *Msg) UnsetAllEmbeds()
- func (m *Msg) UnsetAllParts()
- func (m *Msg) UpdateReader(reader *Reader)
- func (m *Msg) Write(writer io.Writer) (int64, error)
- func (m *Msg) WriteTo(writer io.Writer) (int64, error)
- func (m *Msg) WriteToFile(name string) error
- func (m *Msg) WriteToSendmail() error
- func (m *Msg) WriteToSendmailWithCommand(sendmailPath string) error
- func (m *Msg) WriteToSendmailWithContext(ctx context.Context, sendmailPath string, args ...string) error
- func (m *Msg) WriteToSkipMiddleware(writer io.Writer, middleWareType MiddlewareType) (int64, error)
- func (m *Msg) WriteToTempFile() (string, error)
- type MsgOption
- type Option
- func WithDSN() Option
- func WithDSNMailReturnType(option DSNMailReturnOption) Option
- func WithDSNRcptNotifyType(opts ...DSNRcptNotifyOption) Option
- func WithDebugLog() Option
- func WithDialContextFunc(dialCtxFunc DialContextFunc) Option
- func WithHELO(helo string) Option
- func WithLogger(logger log.Logger) Option
- func WithPassword(password string) Option
- func WithPort(port int) Option
- func WithSMTPAuth(authtype SMTPAuthType) Option
- func WithSMTPAuthCustom(smtpAuth smtp.Auth) Option
- func WithSSL() Option
- func WithSSLPort(fallback bool) Option
- func WithTLSConfig(tlsconfig *tls.Config) Option
- func WithTLSPolicy(policy TLSPolicy) Option
- func WithTLSPortPolicy(policy TLSPolicy) Option
- func WithTimeout(timeout time.Duration) Option
- func WithUsername(username string) Option
- func WithoutNoop() Option
- type PGPType
- type Part
- func (p *Part) Delete()
- func (p *Part) GetCharset() Charset
- func (p *Part) GetContent() ([]byte, error)
- func (p *Part) GetContentType() ContentType
- func (p *Part) GetDescription() string
- func (p *Part) GetEncoding() Encoding
- func (p *Part) GetWriteFunc() func(io.Writer) (int64, error)
- func (p *Part) SetCharset(charset Charset)
- func (p *Part) SetContent(content string)
- func (p *Part) SetContentType(contentType ContentType)
- func (p *Part) SetDescription(description string)
- func (p *Part) SetEncoding(encoding Encoding)
- func (p *Part) SetWriteFunc(writeFunc func(io.Writer) (int64, error))
- type PartOption
- type Reader
- type SMTPAuthType
- type SendErrReason
- type SendError
- type TLSPolicy
Examples ¶
Constants ¶
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
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" )
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
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
const MaxBodyLength = 76
MaxBodyLength defines the maximum line length for the mail body RFC 2047 suggests 76 characters
const MaxHeaderLength = 76
MaxHeaderLength defines the maximum line length for a mail header RFC 2047 suggests 76 characters
const SendmailPath = "/usr/sbin/sendmail"
SendmailPath is the default system path to the sendmail binary
const SingleNewLine = "\r\n"
SingleNewLine represents a new line that can be used by the msgWriter to issue a carriage return
const VERSION = "0.4.4"
VERSION is used in the default user agent string
Variables ¶
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
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") )
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
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
type Client ¶
type Client struct {
// contains filtered or unexported fields
}
Client is the SMTP client struct
func NewClient ¶
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) DialAndSend ¶
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
DialAndSendWithContext establishes a connection to the SMTP server with a custom context and sends the mail
func (*Client) DialWithContext ¶
DialWithContext establishes a connection to the SMTP server with a given context.Context
func (*Client) ServerAddr ¶
ServerAddr returns the currently set combination of hostname and port
func (*Client) SetDebugLog ¶ added in v0.3.9
SetDebugLog tells the Client whether debug logging is enabled or not
func (*Client) SetPassword ¶
SetPassword overrides the current password string with the given value
func (*Client) SetSMTPAuth ¶
func (c *Client) SetSMTPAuth(authtype SMTPAuthType)
SetSMTPAuth overrides the current SMTP AUTH type setting with the given value
func (*Client) SetSMTPAuthCustom ¶
SetSMTPAuthCustom overrides the current SMTP AUTH setting with the given custom smtp.Auth
func (*Client) SetSSLPort ¶ added in v0.4.1
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.
Note: If a different port has already been set otherwise, the port-choosing and fallback automatism will be skipped.
func (*Client) SetTLSConfig ¶
SetTLSConfig overrides the current *tls.Config with the given *tls.Config value
func (*Client) SetTLSPolicy ¶
SetTLSPolicy overrides the current TLSPolicy with the given TLSPolicy value
Note: To follow best-practices for SMTP TLS connections, it is recommended to use SetTLSPortPolicy instead.
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
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.
Note: If a different port has already been set otherwise, the port-choosing and fallback automatism will be skipped.
func (*Client) SetUsername ¶
SetUsername overrides the current username string with the given value
type ContentType ¶
type ContentType string
ContentType represents a content type for the Msg
const ( TypeAppOctetStream ContentType = "application/octet-stream" TypeMultipartAlternative ContentType = "multipart/alternative" TypeMultipartMixed ContentType = "multipart/mixed" TypeMultipartRelated ContentType = "multipart/related" TypePGPSignature ContentType = "application/pgp-signature" TypePGPEncrypted ContentType = "application/pgp-encrypted" TypeTextHTML ContentType = "text/html" TypeTextPlain ContentType = "text/plain" )
List of common content types
func (ContentType) String ¶ added in v0.4.2
func (c ContentType) String() string
String is a standard method to convert an ContentType into a printable format
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
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" // EncodingUSASCII represents encoding with only US-ASCII characters (aka 7Bit) EncodingUSASCII Encoding = "7bit" // NoEncoding avoids any character encoding (except of the mail headers) NoEncoding Encoding = "8bit" )
List of supported encodings
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 WithFileContentID ¶ added in v0.4.2
func WithFileContentID(id string) FileOption
WithFileContentID sets the Content-ID header for the File
func WithFileContentType ¶ added in v0.3.9
func WithFileContentType(contentType 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(description 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(encoding 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(name string) FileOption
WithFileName sets the filename of the File
type Header ¶
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" // HeaderReferences is the "References" header field HeaderReferences Header = "References" // 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
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 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 EMLToMsgFromFile ¶ added in v0.4.2
EMLToMsgFromFile will open and parse a .eml file at a provided file path and returns a pre-filled Msg pointer
func EMLToMsgFromReader ¶ added in v0.4.2
EMLToMsgFromReader will parse a reader that holds EML content and returns a pre-filled Msg pointer
func EMLToMsgFromString ¶ added in v0.4.2
EMLToMsgFromString will parse a given EML string and returns a pre-filled Msg pointer
func NewMsg ¶
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(tpl *ht.Template, data interface{}, opts ...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(contentType ContentType, content string, opts ...PartOption)
AddAlternativeString sets the alternative body of the message.
func (*Msg) AddAlternativeTextTemplate ¶ added in v0.2.2
func (m *Msg) AddAlternativeTextTemplate(tpl *tt.Template, data interface{}, opts ...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( contentType ContentType, writeFunc func(io.Writer) (int64, error), opts ...PartOption, )
AddAlternativeWriter sets the body of the message.
func (*Msg) AddBccFormat ¶
AddBccFormat takes a name and address, formats them RFC5322 compliant and stores them as as additional Bcc address header field
func (*Msg) AddCcFormat ¶
AddCcFormat takes a name and address, formats them RFC5322 compliant and stores them as as additional Cc address header field
func (*Msg) AddToFormat ¶
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(name string, opts ...FileOption)
AttachFile adds an attachment File to the Msg
func (*Msg) AttachFromEmbedFS ¶ added in v0.2.5
AttachFromEmbedFS adds an attachment File from an embed.FS to the Msg
func (*Msg) AttachHTMLTemplate ¶ added in v0.2.2
func (m *Msg) AttachHTMLTemplate( name string, tpl *ht.Template, data interface{}, opts ...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(name string, reader io.ReadSeeker, opts ...FileOption)
AttachReadSeeker adds an attachment File via io.ReadSeeker to the Msg
func (*Msg) AttachReader ¶ added in v0.1.1
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( name string, tpl *tt.Template, data interface{}, opts ...FileOption, ) error
AttachTextTemplate adds the output of a text/template.Template pointer as File attachment to the Msg
func (*Msg) Bcc ¶
Bcc takes and validates a given mail address list sets the Bcc: addresses of the Msg
func (*Msg) BccFromString ¶ added in v0.4.1
BccFromString takes and validates a given string of comma separted mail address and sets them as Bcc: addresses of the Msg
func (*Msg) BccIgnoreInvalid ¶
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) CcFromString ¶ added in v0.4.1
CcFromString takes and validates a given string of comma separted mail address and sets them as Cc: addresses of the Msg
func (*Msg) CcIgnoreInvalid ¶
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) EmbedFile ¶ added in v0.1.1
func (m *Msg) EmbedFile(name string, opts ...FileOption)
EmbedFile adds an embedded File to the Msg
func (*Msg) EmbedFromEmbedFS ¶ added in v0.2.5
EmbedFromEmbedFS adds an embedded File from an embed.FS to the Msg
func (*Msg) EmbedHTMLTemplate ¶ added in v0.2.2
func (m *Msg) EmbedHTMLTemplate( name string, tpl *ht.Template, data interface{}, opts ...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(name string, reader io.ReadSeeker, opts ...FileOption)
EmbedReadSeeker adds an embedded File from an io.ReadSeeker to the Msg
func (*Msg) EmbedReader ¶ added in v0.1.1
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( name string, tpl *tt.Template, data interface{}, opts ...FileOption, ) error
EmbedTextTemplate adds the output of a text/template.Template pointer as embedded File to the Msg
func (*Msg) EnvelopeFrom ¶ added in v0.2.4
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
EnvelopeFromFormat takes a name and address, formats them RFC5322 compliant and stores them as the envelope FROM address header field
func (*Msg) From ¶
From takes and validates a given mail address and sets it as "From" genHeader of the Msg
func (*Msg) FromFormat ¶
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(header 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(header AddrHeader) []string
GetAddrHeaderString returns the address string of the requested address header of the Msg
func (*Msg) GetAttachments ¶ added in v0.3.1
GetAttachments returns the attachments of the Msg
func (*Msg) GetBcc ¶ added in v0.3.5
GetBcc returns the content of the Bcc address header of the Msg
func (*Msg) GetBccString ¶ added in v0.3.5
GetBccString returns the content of the Bcc address header of the Msg as string slice
func (*Msg) GetBoundary ¶ added in v0.4.3
GetBoundary returns the boundary of the Msg
func (*Msg) GetCcString ¶ added in v0.3.5
GetCcString returns the content of the Cc address header of the Msg as string slice
func (*Msg) GetFrom ¶ added in v0.3.5
GetFrom returns the content of the From address header of the Msg
func (*Msg) GetFromString ¶ added in v0.3.5
GetFromString returns the content of the From address header of the Msg as string slice
func (*Msg) GetGenHeader ¶ added in v0.2.9
GetGenHeader returns the content of the requested generic header of the Msg
func (*Msg) GetRecipients ¶
GetRecipients returns a list of the currently set TO/CC/BCC addresses.
func (*Msg) GetSender ¶
GetSender returns the currently set envelope FROM address. If no envelope FROM is set it will use the first mail body FROM address. If useFullAddr is true, it will return the full address string including the address name, if set
func (*Msg) GetToString ¶ added in v0.3.5
GetToString returns the content of the To address header of the Msg as string slice
func (*Msg) HasSendError ¶ added in v0.3.7
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
IsDelivered will return true if the Msg has been successfully delivered
func (*Msg) NewReader ¶ added in v0.3.2
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 ¶
ReplyTo takes and validates a given mail address and sets it as "Reply-To" addrHeader of the Msg
func (*Msg) ReplyToFormat ¶
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
RequestMDNAddTo adds an additional recipient to the recipient list of the MDN
func (*Msg) RequestMDNAddToFormat ¶ added in v0.2.7
RequestMDNAddToFormat adds an additional formated recipient to the recipient list of the MDN
func (*Msg) RequestMDNTo ¶ added in v0.2.7
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
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) SendErrorIsTemp ¶ added in v0.3.7
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(header AddrHeader, values ...string) error
SetAddrHeader sets an address related header field of the Msg
func (*Msg) SetAddrHeaderIgnoreInvalid ¶
func (m *Msg) SetAddrHeaderIgnoreInvalid(header AddrHeader, values ...string)
SetAddrHeaderIgnoreInvalid sets an address related header field of the Msg and ignores invalid address in the validation process
func (*Msg) SetAttachements
deprecated
added in
v0.3.1
func (*Msg) SetAttachments ¶ added in v0.4.3
SetAttachments sets the attachments of the message.
func (*Msg) SetBodyHTMLTemplate ¶ added in v0.2.2
func (m *Msg) SetBodyHTMLTemplate(tpl *ht.Template, data interface{}, opts ...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(contentType ContentType, content string, opts ...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(tpl *tt.Template, data interface{}, opts ...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( contentType ContentType, writeFunc func(io.Writer) (int64, error), opts ...PartOption, )
SetBodyWriter sets the body of the message.
func (*Msg) SetBoundary ¶
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 ¶
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
SetDateWithValue sets the Date genHeader field to the provided time in a valid format
func (*Msg) SetEncoding ¶
SetEncoding sets the encoding of the Msg
func (*Msg) SetGenHeader ¶ added in v0.3.5
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
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) SetHeaderPreformatted
deprecated
added in
v0.3.4
func (*Msg) SetImportance ¶
func (m *Msg) SetImportance(importance 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 ¶
SetMessageIDWithValue sets the message id for the mail
func (*Msg) SetOrganization ¶ added in v0.1.3
SetOrganization sets the provided string as Organization header for the Msg
func (*Msg) SetPGPType ¶ added in v0.3.9
SetPGPType sets the PGPType of the Msg
func (*Msg) SetUserAgent ¶ added in v0.1.3
SetUserAgent sets the User-Agent/X-Mailer header for the Msg
func (*Msg) ToFromString ¶ added in v0.4.1
ToFromString takes and validates a given string of comma separted mail address and sets them as To: addresses of the Msg
func (*Msg) ToIgnoreInvalid ¶
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
UpdateReader will update a Reader with the content of the given Msg and reset the Reader position to the start
func (*Msg) WriteTo ¶ added in v0.1.9
WriteTo writes the formated Msg into a give io.Writer and satisfies the io.WriteTo interface
func (*Msg) WriteToFile ¶ added in v0.2.3
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
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
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, sendmailPath string, args ...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
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
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
WithBoundary overrides the default MIME boundary
func WithCharset ¶
WithCharset overrides the default message charset
func WithEncoding ¶
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 WithNoDefaultUserAgent ¶ added in v0.4.2
func WithNoDefaultUserAgent() MsgOption
WithNoDefaultUserAgent configures the Msg to not use the default User Agent
func WithPGPType ¶ added in v0.3.9
WithPGPType overrides the default PGPType of the message
type Option ¶
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(option 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(opts ...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(dialCtxFunc DialContextFunc) Option
WithDialContextFunc overrides the default DialContext for connecting SMTP server
func WithLogger ¶ added in v0.3.9
WithLogger overrides the default log.Logger that is used for debug logging
func WithPassword ¶
WithPassword tells the client to use the provided string as password/secret for authentication
func WithSMTPAuth ¶
func WithSMTPAuth(authtype SMTPAuthType) Option
WithSMTPAuth tells the client to use the provided SMTPAuthType for authentication
func WithSMTPAuthCustom ¶
WithSMTPAuthCustom tells the client to use the provided smtp.Auth for SMTP authentication
func WithSSLPort ¶ added in v0.4.1
WithSSLPort 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.
Note: If a different port has already been set otherwise, the port-choosing and fallback automatism will be skipped.
func WithTLSConfig ¶
WithTLSConfig tells the client to use the provided *tls.Config
func WithTLSPolicy ¶
WithTLSPolicy tells the client to use the provided TLSPolicy
Note: To follow best-practices for SMTP TLS connections, it is recommended to use WithTLSPortPolicy instead.
func WithTLSPortPolicy ¶ added in v0.4.1
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.
Note: If a different port has already been set otherwise, the port-choosing and fallback automatism will be skipped.
func WithTimeout ¶
WithTimeout overrides the default connection timeout
func WithUsername ¶
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 isDeleted flag to true. The msgWriter will skip it then
func (*Part) GetCharset ¶ added in v0.4.1
GetCharset returns the currently set Charset of the Part
func (*Part) GetContent ¶ added in v0.3.0
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
GetDescription returns the currently set Content-Description of the Part
func (*Part) GetEncoding ¶ added in v0.3.0
GetEncoding returns the currently set Encoding of the Part
func (*Part) GetWriteFunc ¶ added in v0.3.0
GetWriteFunc returns the currently set WriterFunc of the Part
func (*Part) SetCharset ¶ added in v0.4.1
SetCharset overrides the Charset of the Part
func (*Part) SetContent ¶ added in v0.3.0
SetContent overrides the content of the Part with the given string
func (*Part) SetContentType ¶ added in v0.3.0
func (p *Part) SetContentType(contentType ContentType)
SetContentType overrides the ContentType of the Part
func (*Part) SetDescription ¶ added in v0.3.9
SetDescription overrides the Content-Description of the Part
func (*Part) SetEncoding ¶
SetEncoding creates a new mime.WordEncoder based on the encoding setting of the message
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(charset Charset) PartOption
WithPartCharset overrides the default Part charset
func WithPartContentDescription ¶ added in v0.3.9
func WithPartContentDescription(description string) PartOption
WithPartContentDescription overrides the default Part Content-Description
func WithPartEncoding ¶
func WithPartEncoding(encoding 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
type SMTPAuthType ¶
type SMTPAuthType string
SMTPAuthType represents a string to any SMTP AUTH type
const ( // SMTPAuthCramMD5 is the "CRAM-MD5" SASL authentication mechanism as described in RFC 4954 SMTPAuthCramMD5 SMTPAuthType = "CRAM-MD5" // SMTPAuthLogin is the "LOGIN" SASL authentication mechanism SMTPAuthLogin SMTPAuthType = "LOGIN" // SMTPAuthNoAuth is equivalent to performing no authentication at all. It is a convenience // option and should not be used. Instead, for mail servers that do no support/require // authentication, the Client should not be used with the WithSMTPAuth option SMTPAuthNoAuth SMTPAuthType = "" // SMTPAuthPlain is the "PLAIN" authentication mechanism as described in RFC 4616 SMTPAuthPlain SMTPAuthType = "PLAIN" // 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
Error implements the error interface for the SendError type
type TLSPolicy ¶
type TLSPolicy int
TLSPolicy type describes a int alias for the different TLS policies we allow
const ( // TLSMandatory requires that the connection to 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 to establish an encrypted connection via the // STARTTLS protocol. If the server does not support this, it will fall // back to non-encrypted plaintext transmission TLSOpportunistic // NoTLS forces the transaction to be not encrypted NoTLS )
Source Files ¶
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. |