mail

package module
v2.11.0 Latest Latest
Warning

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

Go to latest
Published: Oct 12, 2021 License: MIT Imports: 29 Imported by: 0

README

Go Simple Mail

The best way to send emails in Go with SMTP Keep Alive and Timeout for Connect and Send.

Go Report Card go.dev

IMPORTANT

Examples in this README are for v2.2.0 and above. Examples for older versions can be found here.

The minimum Go version is 1.13, for Go 1.12 and older use branch go1.12.

Breaking change in 2.2.0: The signature of SetBody and AddAlternative used to accept strings ("text/html" and "text/plain") and not require on of the contentType constants (TextHTML or TextPlain). Upgrading, while not quite following semantic versioning, is quite simple:

  email := mail.NewMSG()
- email.SetBody("text/html", htmlBody)
- email.AddAlternative("text/plain", plainBody)
+ email.SetBody(mail.TextHTML, htmlBody)
+ email.AddAlternative(mail.TextPlain, plainBody)

Introduction

Go Simple Mail is a simple and efficient package to send emails. It is well tested and documented.

Go Simple Mail can only send emails using an SMTP server. But the API is flexible and it is easy to implement other methods for sending emails using a local Postfix, an API, etc.

This package contains (and is based on) two packages by Joe Grasse:

A lot of changes in Go Simple Mail were sent with not response.

Features

Go Simple Mail supports:

  • Multiple Attachments with path
  • Multiple Attachments in base64
  • Multiple Attachments from bytes (since v2.6.0)
  • Inline attachments from file, base64 and bytes (bytes since v2.6.0)
  • Multiple Recipients
  • Priority
  • Reply to
  • Set sender
  • Set from
  • Allow sending mail with different envelope from (since v2.7.0)
  • Embedded images
  • HTML and text templates
  • Automatic encoding of special characters
  • SSL/TLS and STARTTLS
  • Unencrypted connection (not recommended)
  • Sending multiple emails with the same SMTP connection (Keep Alive or Persistent Connection)
  • Timeout for connect to a SMTP Server
  • Timeout for send an email
  • Return Path
  • Alternative Email Body
  • CC and BCC
  • Add Custom Headers in Message
  • Send NOOP, RESET, QUIT and CLOSE to SMTP client
  • PLAIN, LOGIN and CRAM-MD5 Authentication (since v2.3.0)
  • Allow connect to SMTP without authentication (since v2.10.0)
  • Custom TLS Configuration (since v2.5.0)
  • Send a RFC822 formatted message (since v2.8.0)
  • Send from localhost (yes, Go standard SMTP package cannot do that because... WTF Google!)

Documentation

https://pkg.go.dev/github.com/jayturchi/go-simple-mail/v2?tab=doc

Download

This package uses go modules.

$ go get github.com/jayturchi/go-simple-mail/v2

Usage

package main

import (
	"log"

	"github.com/jayturchi/go-simple-mail/v2"
)

const htmlBody = `<html>
	<head>
		<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
		<title>Hello Gophers!</title>
	</head>
	<body>
		<p>This is the <b>Go gopher</b>.</p>
		<p><img src="cid:Gopher.png" alt="Go gopher" /></p>
		<p>Image created by Renee French</p>
	</body>
</html>`

func main() {
	server := mail.NewSMTPClient()

	// SMTP Server
	server.Host = "smtp.example.com"
	server.Port = 587
	server.Username = "test@example.com"
	server.Password = "examplepass"
	server.Encryption = mail.EncryptionSTARTTLS

	// Since v2.3.0 you can specified authentication type:
	// - PLAIN (default)
	// - LOGIN
	// - CRAM-MD5
	// - None
	// server.Authentication = mail.AuthPlain

	// Variable to keep alive connection
	server.KeepAlive = false

	// Timeout for connect to SMTP Server
	server.ConnectTimeout = 10 * time.Second

	// Timeout for send the data and wait respond
	server.SendTimeout = 10 * time.Second

	// Set TLSConfig to provide custom TLS configuration. For example,
	// to skip TLS verification (useful for testing):
	server.TLSConfig = &tls.Config{InsecureSkipVerify: true}

	// SMTP client
	smtpClient,err := server.Connect()

	if err != nil{
		log.Fatal(err)
	}

	// New email simple html with inline and CC
	email := mail.NewMSG()
	email.SetFrom("From Example <nube@example.com>").
		AddTo("jayturchi@example.com").
		AddCc("otherto@example.com").
		SetSubject("New Go Email")

	email.SetBody(mail.TextHTML, htmlBody)

	// also you can add body from []byte with SetBodyData, example:
	// email.SetBodyData(mail.TextHTML, []byte(htmlBody))
	// or alternative part
	// email.AddAlternativeData(mail.TextHTML, []byte(htmlBody))

	// add inline
	email.Attach(&mail.File{FilePath: "/path/to/image.png", Name:"Gopher.png", Inline: true})

	// always check error after send
	if email.Error != nil{
		log.Fatal(email.Error)
	}

	// Call Send and pass the client
	err = email.Send(smtpClient)
	if err != nil {
		log.Println(err)
	} else {
		log.Println("Email Sent")
	}
}

Send multiple emails in same connection

	//Set your smtpClient struct to keep alive connection
	server.KeepAlive = true

	for _, to := range []string{
		"to1@example1.com",
		"to3@example2.com",
		"to4@example3.com",
	} {
		// New email simple html with inline and CC
		email := mail.NewMSG()
		email.SetFrom("From Example <nube@example.com>").
			AddTo(to).
			SetSubject("New Go Email")

		email.SetBody(mail.TextHTML, htmlBody)

		// add inline
		email.Attach(&mail.File{FilePath: "/path/to/image.png", Name:"Gopher.png", Inline: true})

		// always check error after send
		if email.Error != nil{
			log.Fatal(email.Error)
		}

		// Call Send and pass the client
		err = email.Send(smtpClient)
		if err != nil {
			log.Println(err)
		} else {
			log.Println("Email Sent")
		}
	}

More examples

See example/example_test.go.

Documentation

Index

Constants

View Source
const (
	// EncodingNone turns off encoding on the message body
	EncodingNone encoding = iota
	// EncodingBase64 sets the message body encoding to base64
	EncodingBase64
	// EncodingQuotedPrintable sets the message body encoding to quoted-printable
	EncodingQuotedPrintable
)
View Source
const (
	// TextPlain sets body type to text/plain in message body
	TextPlain contentType = iota
	// TextHTML sets body type to text/html in message body
	TextHTML
	// TextCalendar sets body type to text/calendar in message body
	TextCalendar
)
View Source
const (
	// PriorityLow sets the email priority to Low
	PriorityLow priority = iota
	// PriorityHigh sets the email priority to High
	PriorityHigh
)
View Source
const (
	NTLMVersion1 = ntlm.Version1
	NTLMVersion2 = ntlm.Version2
)
View Source
const (
	NEGOTIATE_MESSAGE    = 1
	CHALLENGE_MESSAGE    = 2
	AUTHENTICATE_MESSAGE = 3
)
View Source
const (
	NEGOTIATE_UNICODE                  = 0x00000001
	NEGOTIATE_OEM                      = 0x00000002
	NEGOTIATE_TARGET                   = 0x00000004
	NEGOTIATE_SIGN                     = 0x00000010
	NEGOTIATE_SEAL                     = 0x00000020
	NEGOTIATE_DATAGRAM                 = 0x00000040
	NEGOTIATE_LMKEY                    = 0x00000080
	NEGOTIATE_NTLM                     = 0x00000200
	NEGOTIATE_ANONYMOUS                = 0x00000800
	NEGOTIATE_OEM_DOMAIN_SUPPLIED      = 0x00001000
	NEGOTIATE_OEM_WORKSTATION_SUPPLIED = 0x00002000
	NEGOTIATE_ALWAYS_SIGN              = 0x00008000
	NEGOTIATE_TARGET_TYPE_DOMAIN       = 0x00010000
	NEGOTIATE_TARGET_TYPE_SERVER       = 0x00020000
	NEGOTIATE_EXTENDED_SESSIONSECURITY = 0x00080000
	NEGOTIATE_IDENTIFY                 = 0x00100000
	REQUEST_NON_NT_SESSION_KEY         = 0x00400000
	NEGOTIATE_TARGET_INFO              = 0x00800000
	NEGOTIATE_VERSION                  = 0x02000000
	NEGOTIATE_128                      = 0x20000000
	NEGOTIATE_KEY_EXCH                 = 0x40000000
	NEGOTIATE_56                       = 0x80000000
)

Variables

This section is empty.

Functions

func NTLMAuth

func NTLMAuth(host, user, password string, version ntlm.Version) *ntlmAuth

func NTLMV1Auth

func NTLMV1Auth(host, user, password, workstation string) *ntlmv1Auth

PlainAuth returns an Auth that implements the PLAIN authentication mechanism as defined in RFC 4616. The returned Auth uses the given username and password to authenticate on TLS connections to host and act as identity. Usually identity will be left blank to act as username.

func SendMessage

func SendMessage(from string, recipients []string, msg string, client *SMTPClient) error

SendMessage sends a message (a RFC822 formatted message) 'from' must be an email address, recipients must be a slice of email address

Types

type AuthType

type AuthType int
const (
	// AuthPlain implements the PLAIN authentication
	AuthPlain AuthType = iota
	// AuthLogin implements the LOGIN authentication
	AuthLogin
	// AuthCRAMMD5 implements the CRAM-MD5 authentication
	AuthCRAMMD5
	// AuthNTLM for Windows servers authentication
	AuthNTLM
	// AuthNone for SMTP servers without authentication
	AuthNone
)

type Email

type Email struct {
	Charset    string
	Encoding   encoding
	Error      error
	SMTPServer *smtpClient
	// contains filtered or unexported fields
}

Email represents an email message.

func NewMSG

func NewMSG() *Email

NewMSG creates a new email. It uses UTF-8 by default. All charsets: http://webcheatsheet.com/HTML/character_sets_list.php

func (*Email) AddAddresses

func (email *Email) AddAddresses(header string, addresses ...string) *Email

AddAddresses allows you to add addresses to the specified address header.

func (*Email) AddAlternative

func (email *Email) AddAlternative(contentType contentType, body string) *Email

AddAlternative allows you to add alternative parts to the body of the email message. This is most commonly used to add an html version in addition to a plain text version that was already added with SetBody.

func (*Email) AddAlternativeData

func (email *Email) AddAlternativeData(contentType contentType, body []byte) *Email

AddAlternativeData allows you to add alternative parts to the body of the email message. This is most commonly used to add an html version in addition to a plain text version that was already added with SetBody.

func (*Email) AddAttachment

func (email *Email) AddAttachment(file string, name ...string) *Email

AddAttachment. DEPRECATED. Use Attach method. Allows you to add an attachment to the email message. You can optionally provide a different name for the file.

func (*Email) AddAttachmentBase64

func (email *Email) AddAttachmentBase64(b64File, name string) *Email

AddAttachmentBase64. DEPRECATED. Use Attach method. Allows you to add an attachment in base64 to the email message. You need provide a name for the file.

func (*Email) AddAttachmentData

func (email *Email) AddAttachmentData(data []byte, filename, mimeType string) *Email

AddAttachmentData. DEPRECATED. Use Attach method. Allows you to add an in-memory attachment to the email message.

func (*Email) AddBcc

func (email *Email) AddBcc(addresses ...string) *Email

AddBcc adds a Bcc address. You can provide multiple addresses at the same time.

func (*Email) AddCc

func (email *Email) AddCc(addresses ...string) *Email

AddCc adds a Cc address. You can provide multiple addresses at the same time.

func (*Email) AddHeader

func (email *Email) AddHeader(header string, values ...string) *Email

AddHeader adds the given "header" with the passed "value".

func (*Email) AddHeaders

func (email *Email) AddHeaders(headers textproto.MIMEHeader) *Email

AddHeaders is used to add multiple headers at once

func (*Email) AddInline

func (email *Email) AddInline(file string, name ...string) *Email

AddInline. DEPRECATED. Use Attach method. Allows you to add an inline attachment to the email message. You can optionally provide a different name for the file.

func (*Email) AddInlineBase64

func (email *Email) AddInlineBase64(b64File, name, mimeType string) *Email

AddInlineBase64. DEPRECATED. Use Attach method. Allows you to add an inline in-memory base64 encoded attachment to the email message. You need provide a name for the file. If mimeType is an empty string, attachment mime type will be deduced from the file name extension and defaults to application/octet-stream.

func (*Email) AddInlineData

func (email *Email) AddInlineData(data []byte, filename, mimeType string) *Email

AddInlineData. DEPRECATED. Use Attach method. Allows you to add an inline in-memory attachment to the email message.

func (*Email) AddTo

func (email *Email) AddTo(addresses ...string) *Email

AddTo adds a To address. You can provide multiple addresses at the same time.

func (*Email) Attach

func (email *Email) Attach(file *File) *Email

Attach allows you to add an attachment to the email message. The attachment can be inlined

func (*Email) GetError

func (email *Email) GetError() error

GetError returns the first email error encountered

func (*Email) GetFrom

func (email *Email) GetFrom() string

GetFrom returns the sender of the email, if any

func (*Email) GetMessage

func (email *Email) GetMessage() string

GetMessage builds and returns the email message (RFC822 formatted message)

func (*Email) GetRecipients

func (email *Email) GetRecipients() []string

GetRecipients returns a slice of recipients emails

func (*Email) Send

func (email *Email) Send(client *SMTPClient) error

Send sends the composed email

func (*Email) SendEnvelopeFrom

func (email *Email) SendEnvelopeFrom(from string, client *SMTPClient) error

SendEnvelopeFrom sends the composed email with envelope sender. 'from' must be an email address.

func (*Email) SetBody

func (email *Email) SetBody(contentType contentType, body string) *Email

SetBody sets the body of the email message.

func (*Email) SetBodyData

func (email *Email) SetBodyData(contentType contentType, body []byte) *Email

SetBodyData sets the body of the email message from []byte

func (*Email) SetDate

func (email *Email) SetDate(dateTime string) *Email

SetDate sets the date header to the provided date/time. The format of the string should be YYYY-MM-DD HH:MM:SS Time Zone.

Example: SetDate("2015-04-28 10:32:00 CDT")

func (*Email) SetFrom

func (email *Email) SetFrom(address string) *Email

SetFrom sets the From address.

func (*Email) SetPriority

func (email *Email) SetPriority(priority priority) *Email

SetPriority sets the email message priority. Use with either "High" or "Low".

func (*Email) SetReplyTo

func (email *Email) SetReplyTo(address string) *Email

SetReplyTo sets the Reply-To address.

func (*Email) SetReturnPath

func (email *Email) SetReturnPath(address string) *Email

SetReturnPath sets the Return-Path address. This is most often used to send bounced emails to a different email address.

func (*Email) SetSender

func (email *Email) SetSender(address string) *Email

SetSender sets the Sender address.

func (*Email) SetSubject

func (email *Email) SetSubject(subject string) *Email

SetSubject sets the subject of the email message.

type Encryption

type Encryption int

Encryption type to enum encryption types (None, SSL/TLS, STARTTLS)

const (
	// EncryptionNone uses no encryption when sending email
	EncryptionNone Encryption = iota
	// EncryptionSSL: DEPRECATED. Use EncryptionSSLTLS. Sets encryption type to SSL/TLS when sending email
	EncryptionSSL
	// EncryptionTLS: DEPRECATED. Use EncryptionSTARTTLS. sets encryption type to STARTTLS when sending email
	EncryptionTLS
	// EncryptionSSLTLS sets encryption type to SSL/TLS when sending email
	EncryptionSSLTLS
	// EncryptionSTARTTLS sets encryption type to STARTTLS when sending email
	EncryptionSTARTTLS
)

func (Encryption) String

func (encryption Encryption) String() string

type File

type File struct {
	// FilePath is the path of the file to attach.
	FilePath string
	// Name is the name of file in attachment. Required for Data and B64Data. Optional for FilePath.
	Name string
	// MimeType of attachment. If empty then is obtained from Name (if not empty) or FilePath. If cannot obtained, application/octet-stream is set.
	MimeType string
	// B64Data is the base64 string to attach.
	B64Data string
	// Data is the []byte of file to attach.
	Data []byte
	// Inline defines if attachment is inline or not.
	Inline bool
}

File represents the file that can be added to the email message. You can add attachment from file in path, from base64 string or from []byte. You can define if attachment is inline or not. Only one, Data, B64Data or FilePath is supported. If multiple are set, then the first in that order is used.

type NTLMSSP

type NTLMSSP struct {
	Domain      string
	UserName    string
	Password    string
	Workstation string
}

func (*NTLMSSP) Free

func (auth *NTLMSSP) Free()

func (*NTLMSSP) InitialBytes

func (auth *NTLMSSP) InitialBytes() ([]byte, error)

func (*NTLMSSP) NextBytes

func (auth *NTLMSSP) NextBytes(bytes []byte) ([]byte, error)

type SMTPClient

type SMTPClient struct {
	Client      *smtpClient
	KeepAlive   bool
	SendTimeout time.Duration
}

SMTPClient represents a SMTP Client for send email

func (*SMTPClient) Close

func (smtpClient *SMTPClient) Close() error

Close closes the connection

func (*SMTPClient) Noop

func (smtpClient *SMTPClient) Noop() error

Noop send NOOP command to smtp client

func (*SMTPClient) Quit

func (smtpClient *SMTPClient) Quit() error

Quit send QUIT command to smtp client

func (*SMTPClient) Reset

func (smtpClient *SMTPClient) Reset() error

Reset send RSET command to smtp client

type SMTPServer

type SMTPServer struct {
	Authentication AuthType
	Encryption     Encryption
	Username       string
	Password       string
	Helo           string
	ConnectTimeout time.Duration
	SendTimeout    time.Duration
	Host           string
	Port           int
	KeepAlive      bool
	TLSConfig      *tls.Config
}

SMTPServer represents a SMTP Server If authentication is CRAM-MD5 then the Password is the Secret

func NewSMTPClient

func NewSMTPClient() *SMTPServer

NewSMTPClient returns the client for send email

func (*SMTPServer) Connect

func (server *SMTPServer) Connect() (*SMTPClient, error)

Connect returns the smtp client

func (*SMTPServer) GetEncryptionType

func (server *SMTPServer) GetEncryptionType() Encryption

GetEncryptionType returns the encryption type used to connect to SMTP server

Jump to

Keyboard shortcuts

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