Categorygithub.com/wneessen/go-mail
modulepackage
0.6.2
Repository: https://github.com/wneessen/go-mail.git
Documentation: pkg.go.dev

# README

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

GoDoc codecov Go Report Card Mentioned in Awesome Go #go-mail on Discord REUSE status OpenSSF Best Practices OpenSSF Scorecard buy ma a coffee

go-mail logo

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

go-mail follows idiomatic Go style and best practice. It has a small dependency footprint by mainly relying on the Go Standard Library and the Go extended packages. It combines a lot of functionality from the standard library to give easy and convenient access to mail and SMTP related tasks.

In the early days, parts of this library (especially some parts of msgwriter.go) had been forked/ported from go-mail/mail and respectively go-gomail/gomail. Today most of the ported code has been refactored.

The smtp package of go-mail has been forked from the original Go stdlib's net/smtp package and has then been extended by the go-mail team to fit the packages needs (more SMTP Auth methods, logging, concurrency-safety, etc.).

Features

Here are some highlights of go-mail's featureset:

  • Very small dependency footprint (mainly Go Stdlib and Go extended packages)
  • Modern, idiomatic Go
  • Sane and secure defaults
  • Implicit SSL/TLS support
  • Explicit STARTTLS support with different policies
  • Makes use of contexts for a better control flow and timeout/cancelation handling
  • SMTP Auth support
    • CRAM-MD5
    • LOGIN
    • PLAIN
    • SCRAM-SHA-1/SCRAM-SHA-1-PLUS
    • SCRAM-SHA-256/SCRAM-SHA-256-PLUS
    • XOAUTH2
  • RFC5322 compliant mail address validation
  • Support for common mail header field generation (Message-ID, Date, Bulk-Precedence, Priority, etc.)
  • Concurrency-safe reusing the same SMTP connection to send multiple mails
  • Support for attachments and inline embeds (from file system, io.Reader, embed.FS or fs.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.WriterTo 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.)
  • Output a go-mail message as EML file and parse EML file into a go-mail message
  • S/MIME message signing support (RSA and ECDSA)
  • UNIX domain socket support

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 alternatively find us on the Gophers Slack in #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.

Merch

Thanks to our wonderful friends at HelloTux we can offer great go-mail merchandising. All merch articles are embroidery to provide the best and most long-lasting quality possible.

If you want to support the open source community and represent your favourite Go mail library with some cool drip, check out our merch shop at: https://www.hellotux.com/go-mail.

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 created and developed by Winni Neessen, but over time a lot of amazing people contributed ot the project. Big thanks to all of them for improving the go-mail project (be it writing code, testing code, reviewing code, writing documenation or helping to translate the website):

image of contributors

A huge thank you also goes to Maria Letta for designing our super cool go-mail logo!

Sponsors

We sincerely thank our amazing sponsors for their generous support! Your contributions do not go unnoticed and helps keeping up the project!

# Packages

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.

# Functions

EMLToMsgFromFile opens and parses a .eml file at a provided file path and returns a pre-filled Msg pointer.
EMLToMsgFromReader parses a reader that holds EML content and returns a pre-filled Msg pointer.
EMLToMsgFromString parses a given EML string and returns a pre-filled Msg pointer.
NewAuthData creates a new AuthData instance with the provided username and password.
NewClient creates a new Client instance with the provided host and optional configuration Option functions.
NewMsg creates a new email message with optional MsgOption functions that customize various aspects of the message.
QuickSend is an all-in-one method for quickly sending simple text mails in go-mail.
WithBoundary sets the boundary of a Msg to the provided string value during its creation or initialization.
WithCharset sets the Charset type for a Msg during its creation or initialization.
WithDebugLog enables debug logging for the Client.
WithDialContextFunc sets the provided DialContextFunc as the DialContext for connecting to the SMTP server.
WithDSN enables DSN (Delivery Status Notifications) for the Client as described in RFC 1891.
WithDSNMailReturnType enables DSN (Delivery Status Notifications) for the Client as described in RFC 1891.
WithDSNRcptNotifyType enables DSN (Delivery Status Notifications) for the Client as described in RFC 1891.
WithEncoding sets the Encoding type for a Msg during its creation or initialization.
WithFileContentID sets the "Content-ID" header in the File's MIME headers to the specified ID.
WithFileContentType sets the content type of the File.
WithFileDescription sets an optional description for the File, which is used in the Content-Description header of the MIME output.
WithFileEncoding sets the encoding type for a File.
WithFileName sets the name of a File to the provided value.
WithHELO sets the HELO/EHLO string used by the Client.
WithLogAuthData enables logging of authentication data.
WithLogger defines a custom logger for the Client.
WithMiddleware adds the given Middleware to the end of the list of the Client middlewares slice.
WithMIMEVersion sets the MIMEVersion type for a Msg during its creation or initialization.
WithNoDefaultUserAgent disables the inclusion of a default User-Agent header in the Msg during its creation or initialization.
WithoutNoop indicates that the Client should skip the "NOOP" command during the dial.
WithPartCharset overrides the default Part charset.
WithPartContentDescription overrides the default Part Content-Description.
WithPartEncoding overrides the default Part encoding.
WithPassword sets the password that the Client will use for SMTP authentication.
WithPGPType sets the PGP type for the Msg during its creation or initialization, determining the encryption or signature method.
WithPort sets the port number for the Client and overrides the default port.
WithSMIMESigning enables the S/MIME signing flag for a Part.
WithSMTPAuth configures the Client to use the specified SMTPAuthType for SMTP authentication.
WithSMTPAuthCustom sets a custom SMTP authentication mechanism for the Client.
WithSSL enables implicit SSL/TLS for the Client.
WithSSLPort enables implicit SSL/TLS with an optional fallback for the Client.
WithTimeout sets the connection timeout for the Client and overrides the default timeout.
WithTLSConfig sets the tls.Config for the Client and overrides the default configuration.
WithTLSPolicy sets the TLSPolicy of the Client and overrides the DefaultTLSPolicy.
WithTLSPortPolicy enables explicit TLS via STARTTLS for the Client using the provided TLSPolicy.
WithUsername sets the username that the Client will use for SMTP authentication.

# Constants

CharsetASCII represents the "US-ASCII" charset.
CharsetBig5 represents the "Big5" charset.
CharsetEUCKR represents the "EUC-KR" charset.
CharsetGB18030 represents the "GB18030" charset.
CharsetGB2312 represents the "GB2312" charset.
CharsetGBK represents the "GBK" charset.
CharsetISO2022JP represents the "ISO-2022-JP" charset.
CharsetISO2022KR represents the "ISO-2022-KR" charset.
CharsetISO88591 represents the "ISO-8859-1" charset.
CharsetISO885913 represents the "ISO-8859-13" charset.
CharsetISO885914 represents the "ISO-8859-14" charset.
CharsetISO885915 represents the "ISO-8859-15" charset.
CharsetISO885916 represents the "ISO-8859-16" charset.
CharsetISO88592 represents the "ISO-8859-2" charset.
CharsetISO88593 represents the "ISO-8859-3" charset.
CharsetISO88594 represents the "ISO-8859-4" charset.
CharsetISO88595 represents the "ISO-8859-5" charset.
CharsetISO88596 represents the "ISO-8859-6" charset.
CharsetISO88597 represents the "ISO-8859-7" charset.
CharsetISO88599 represents the "ISO-8859-9" charset.
CharsetKOI8R represents the "KOI8-R" charset.
CharsetKOI8U represents the "KOI8-U" charset.
CharsetShiftJIS represents the "Shift_JIS" charset.
CharsetTIS620 represents the "TIS-620" charset.
CharsetUnknown represents the "Unknown" charset.
CharsetUTF7 represents the "UTF-7" charset.
CharsetUTF8 represents the "UTF-8" charset.
CharsetWindows1250 represents the "windows-1250" charset.
CharsetWindows1251 represents the "windows-1251" charset.
CharsetWindows1252 represents the "windows-1252" charset.
CharsetWindows1255 represents the "windows-1255" charset.
CharsetWindows1256 represents the "windows-1256" charset.
DefaultPort is the default connection port to the SMTP server.
DefaultPortSSL is the default connection port for SSL/TLS to the SMTP server.
DefaultPortTLS is the default connection port for STARTTLS to the SMTP server.
DefaultTimeout is the default connection timeout.
DefaultTLSMinVersion defines the minimum TLS version to be used for secure connections.
DefaultTLSPolicy specifies the default TLS policy for connections.
DoubleNewLine represents a double newline character sequence ("\r\n\r\n").
DSNMailReturnFull requests that the entire mail message is returned in any failed DSN (Delivery Status Notification) issued for this recipient.
DSNMailReturnHeadersOnly requests that only the message headers of the mail message are returned in a DSN (Delivery Status Notification).
DSNRcptNotifyDelay indicates the sender's willingness to receive "delayed" DSNs.
DSNRcptNotifyFailure requests that a DSN (Delivery Status Notification) is issued if delivery of a message fails.
DSNRcptNotifyNever indicates that no DSN (Delivery Status Notifications) should be sent for the recipient under any condition.
DSNRcptNotifySuccess indicates that the sender requests a DSN (Delivery Status Notification) if the message is successfully delivered.
EncodingB64 represents the Base64 encoding as specified in RFC 2045.
EncodingQP represents the "quoted-printable" encoding as specified in RFC 2045.
EncodingUSASCII represents encoding with only US-ASCII characters (aka 7Bit) https://datatracker.ietf.org/doc/html/rfc2045#section-2.7.
ErrAmbiguous is a generalized delivery error for the SendError type that is returned if the exact reason for the delivery failure is ambiguous.
ErrConnCheck is returned if the Msg delivery failed when checking if the SMTP server connection is still working.
ErrGetRcpts is returned if the Msg.GetRecipients method fails during a Client.Send.
ErrGetSender is returned if the Msg.GetSender method fails during a Client.Send.
ErrNoUnencoded is returned if the Msg delivery failed when the Msg is configured for unencoded delivery but the server does not support this.
ErrSMTPData is returned if the Msg delivery failed when sending the DATA command to the sending SMTP server.
ErrSMTPDataClose is returned if the Msg delivery failed when trying to close the Client data writer.
ErrSMTPMailFrom is returned if the Msg delivery failed when sending the MAIL FROM command to the sending SMTP server.
ErrSMTPRcptTo is returned if the Msg delivery failed when sending the RCPT TO command to the sending SMTP server.
ErrSMTPReset is returned if the Msg delivery failed when sending the RSET command to the sending SMTP server.
ErrWriteContent is returned if the Msg delivery failed when sending Msg content to the Client writer.
HeaderBcc is the "Blind Carbon Copy" header field.
HeaderCc is the "Carbon Copy" header field.
HeaderContentDescription is the "Content-Description" header.
HeaderContentDisposition is the "Content-Disposition" header.
HeaderContentID is the "Content-ID" header.
HeaderContentLang is the "Content-Language" header.
HeaderContentLocation is the "Content-Location" header (RFC 2110).
HeaderContentTransferEnc is the "Content-Transfer-Encoding" header.
HeaderContentType is the "Content-Type" header.
HeaderDate represents the "Date" field.
HeaderDispositionNotificationTo is the MDN header as described in RFC 8098.
HeaderEnvelopeFrom is the envelope FROM header field.
HeaderFrom is the "From" header field.
HeaderImportance represents the "Importance" field.
HeaderInReplyTo represents the "In-Reply-To" field.
HeaderListUnsubscribe is the "List-Unsubscribe" header field.
HeaderListUnsubscribePost is the "List-Unsubscribe-Post" header field.
HeaderMessageID represents the "Message-ID" field for message identification.
HeaderMIMEVersion represents the "MIME-Version" field as per RFC 2045.
HeaderOrganization is the "Organization" header field.
HeaderPrecedence is the "Precedence" header field.
HeaderPriority represents the "Priority" field.
HeaderReferences is the "References" header field.
HeaderReplyTo is the "Reply-To" header field.
HeaderSubject is the "Subject" header field.
HeaderTo is the "Receipient" header field.
HeaderUserAgent is the "User-Agent" header field.
HeaderXAutoResponseSuppress is the "X-Auto-Response-Suppress" header field.
HeaderXMailer is the "X-Mailer" header field.
HeaderXMSMailPriority is the "X-MSMail-Priority" header field.
HeaderXPriority is the "X-Priority" header field.
ImportanceHigh indicates a high level of importance or priority in a Msg.
ImportanceLow indicates a low level of importance or priority in a Msg.
ImportanceNonUrgent indicates a non-urgent level of importance or priority in a Msg.
ImportanceNormal indicates a standard level of importance or priority for a Msg.
ImportanceUrgent indicates an urgent level of importance or priority in a Msg.
MaxBodyLength defines the maximum line length for the mail body.
MaxHeaderLength defines the maximum line length for a mail header.
MIME10 represents the MIME version "1.0" used in email messages.
MIMEAlternative MIMEType represents a MIME multipart/alternative type, used for emails with multiple versions.
MIMEMixed MIMEType represents a MIME multipart/mixed type used fork emails containing different types of content.
MIMERelated MIMEType represents a MIME multipart/related type, used for emails with related content entities.
MIMESMIMESigned MIMEType represents a MIME multipart/signed type, used for siging emails with S/MIME.
NoEncoding represents 8-bit encoding for email messages as specified in RFC 6152.
NoPGP indicates that a message should not be treated as PGP encrypted or signed and is the default value for a message.
NoTLS forces the transaction to be not encrypted.
PGPEncrypt indicates that a message should be treated as PGP encrypted.
PGPSignature indicates that a message should be treated as PGP signed.
SendmailPath is the default system path to the sendmail binary - at least on standard Unix-like OS.
SingleNewLine represents a single newline character sequence ("\r\n").
SMTPAuthAutoDiscover is a mechanism that dynamically discovers all authentication mechanisms supported by the SMTP server and selects the strongest available one.
SMTPAuthCramMD5 is the "CRAM-MD5" SASL authentication mechanism as described in RFC 4954.
SMTPAuthCustom is a custom SMTP AUTH mechanism provided by the user.
SMTPAuthLogin is the "LOGIN" SASL authentication mechanism.
SMTPAuthLoginNoEnc is the "LOGIN" SASL authentication mechanism.
SMTPAuthNoAuth is equivalent to performing no authentication at all.
SMTPAuthPlain is the "PLAIN" authentication mechanism as described in RFC 4616.
SMTPAuthPlainNoEnc is the "PLAIN" authentication mechanism as described in RFC 4616.
SMTPAuthSCRAMSHA1 is the "SCRAM-SHA-1" SASL authentication mechanism as described in RFC 5802.
SMTPAuthSCRAMSHA1PLUS is the "SCRAM-SHA-1-PLUS" SASL authentication mechanism as described in RFC 5802.
SMTPAuthSCRAMSHA256 is the "SCRAM-SHA-256" SASL authentication mechanism as described in RFC 7677.
SMTPAuthSCRAMSHA256PLUS is the "SCRAM-SHA-256-PLUS" SASL authentication mechanism as described in RFC 7677.
SMTPAuthXOAUTH2 is the "XOAUTH2" SASL authentication mechanism.
TLSMandatory requires that the connection to the server is encrypting using STARTTLS.
TLSOpportunistic tries to establish an encrypted connection via the STARTTLS protocol.
TypeAppOctetStream represents the MIME type for arbitrary binary data.
TypeMultipartAlternative represents the MIME type for a message body that can contain multiple alternative formats.
TypeMultipartMixed represents the MIME type for a multipart message containing different parts.
TypeMultipartRelated represents the MIME type for a multipart message where each part is a related file or resource.
TypePGPEncrypted represents the MIME type for PGP encrypted messages.
TypePGPSignature represents the MIME type for PGP signed messages.
TypeSMIMESigned represents the MIME type for S/MIME singed messages.
TypeTextHTML represents the MIME type for HTML text content.
TypeTextPlain represents the MIME type for plain text content.
VERSION indicates the current version of the package.

# Variables

ErrCertificateMissing should be used if the certificate is invalid.
ErrCramMD5AuthNotSupported is returned when the server does not support the "CRAM-MD5" SMTP authentication type.
ErrDeadlineExtendFailed is returned when an attempt to extend the connection deadline fails.
ErrDialContextFuncIsNil indicates that a required dial context function is not provided.
ErrInvalidDSNMailReturnOption is returned when an invalid DSNMailReturnOption is provided as argument to the WithDSN Option.
ErrInvalidDSNRcptNotifyCombination is returned when an invalid combination of DSNRcptNotifyOption is provided as argument to the WithDSN Option.
ErrInvalidDSNRcptNotifyOption is returned when an invalid DSNRcptNotifyOption is provided as argument to the WithDSN Option.
ErrInvalidHELO is returned when the HELO/EHLO value is invalid due to being empty.
ErrInvalidPort is returned when the specified port for the SMTP connection is not valid.
ErrInvalidTimeout is returned when the specified timeout is zero or negative.
ErrInvalidTLSConfig is returned when the provided TLS configuration is invalid or nil.
ErrLoginAuthNotSupported is returned when the server does not support the "LOGIN" SMTP authentication type.
ErrNoActiveConnection indicates that there is no active connection to the SMTP server.
ErrNoFromAddress indicates that the FROM address is not set, which is required.
ErrNoHostname is returned when the hostname for the client is not provided or empty.
ErrNoOutWriter is the error returned when no io.Writer is set for Base64LineBreaker.
ErrNoRcptAddresses indicates that no recipient addresses have been set.
ErrNoSupportedAuthDiscovered is returned when the SMTP Auth AutoDiscover process fails to identify any supported authentication mechanisms offered by the server.
ErrPlainAuthNotSupported is returned when the server does not support the "PLAIN" SMTP authentication type.
ErrPrivateKeyMissing should be used if private key is invalid.
ErrSCRAMSHA1AuthNotSupported is returned when the server does not support the "SCRAM-SHA-1" SMTP authentication type.
ErrSCRAMSHA1PLUSAuthNotSupported is returned when the server does not support the "SCRAM-SHA-1-PLUS" SMTP authentication type.
ErrSCRAMSHA256AuthNotSupported is returned when the server does not support the "SCRAM-SHA-256" SMTP authentication type.
ErrSCRAMSHA256PLUSAuthNotSupported is returned when the server does not support the "SCRAM-SHA-256-PLUS" SMTP authentication type.
ErrServerNoUnencoded indicates that the server does not support 8BITMIME for unencoded 8-bit messages.
ErrSMTPAuthMethodIsNil indicates that the SMTP authentication method provided is nil.
ErrXOauth2AuthNotSupported is returned when the server does not support the "XOAUTH2" schema.

# Structs

No description provided by the author
Base64LineBreaker handles base64 encoding with the insertion of new lines after a certain number of characters.
No description provided by the author
File represents a file with properties such as content type, description, encoding, headers, name, and a writer function.
Msg represents an email message with various headers, attachments, and encoding settings.
Part is a part of the Msg.
Reader is a type that implements the io.Reader interface for a Msg.
SendError is an error wrapper for delivery errors of the Msg.
SMIME represents the configuration and state for S/MIME signing.

# Interfaces

Middleware represents the interface for modifying or handling email messages.

# Type aliases

AddrHeader is a type wrapper for a string and represents email address headers fields in a Msg.
Charset is a type wrapper for a string representing different character encodings.
ContentType is a type wrapper for a string and represents the MIME type of the content being handled.
No description provided by the author
No description provided by the author
No description provided by the author
Encoding is a type wrapper for a string and represents the type of encoding used for email messages and/or parts.
FileOption is a function type used to modify properties of a File.
Header is a type wrapper for a string and represents email header fields in a Msg.
Importance is a type wrapper for an int and represents the level of importance or priority for a Msg.
MiddlewareType is a type wrapper for a string.
MIMEType is a type wrapper for a string and represents the MIME type for the Msg content or parts.
MIMEVersion is a type wrapper for a string nad represents the MIME version used in email messages.
MsgOption is a function type that modifies a Msg instance during its creation or initialization.
No description provided by the author
PartOption returns a function that can be used for grouping Part options.
PGPType is a type wrapper for an int, representing a type of PGP encryption or signature.
SendErrReason represents a comparable reason on why the delivery failed.
SMTPAuthType is a type wrapper for a string type.
TLSPolicy is a type wrapper for an int type and describes the different TLS policies we allow.