mail

package module
v2.1.3+incompatible Latest Latest
Warning

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

Go to latest
Published: Sep 27, 2019 License: MIT Imports: 19 Imported by: 0

README

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

Go Doc Go Report

Coverage service link https://gocover.io/github.com/xhit/go-simple-mail

Inspired in joegrasse package github.com/joegrasse/mail Thanks

IMPORTANT This example is for version 2.1.0 and above, for v2.0.0 example go here https://gist.github.com/xhit/54516917473420a8db1b6fff68a21c99

Download

go get -u github.com/xhit/go-simple-mail

Usage

package main

import (
	"github.com/xhit/go-simple-mail"
	"log"
)

func main() {

	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>`

	server := mail.NewSMTPClient()
	
	//SMTP Server
	server.Host = "smtp.example.com"
	server.Port = 587
	server.Username = "test@example.com"
	server.Password = "examplepass"
	server.Encryption = mail.EncryptionTLS
	
	//Variable to keep alive connection
	server.KeepAlive = true
	
	//Timeout for connect to SMTP Server
	server.ConnectTimeout = 10 * time.Second
	
	//Timeout for send the data and wait respond
	server.SendTimeout = 10 * time.Second
	
	//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("xhit@example.com").
		AddCc("otherto@example.com").
		SetSubject("New Go Email")

	email.SetBody("text/html", htmlBody)

	email.AddInline("/path/to/image.png", "Gopher.png")

	//Call Send and pass the client
	err = email.Send(smtpClient)

	if err != nil {
		log.Println(err)
	} else {
		log.Println("Email Sent")
	}


	//Other email with same connection and attachments
	email = mail.NewMSG()
	
	email.SetFrom("HELLO <nube@example.com>").
		AddTo("xhit@example.com").
		SetSubject("dfgdfgdf")

	email.SetBody("text/plain", "Hello Gophers!")
	email.AddAlternative("text/html", htmlBody)

	email.AddAttachment("path/to/file","filename test")
	email.AddAttachment("path/to/file2")

	// also you can attach a base64 instead a file path
	email.AddAttachmentBase64("SGVsbG8gZ29waGVycyE=", "hello.txt")

	//Call Send and pass the client
	err = email.Send(smtpClient)

	if err != nil {
		log.Println(err)
	} else {
		log.Println("Email Sent")
	}
}

Documentation

Overview

Package mail implements the Simple Mail Transfer Protocol as defined in RFC 5321. It also implements the following extensions:

8BITMIME  RFC 1652
AUTH      RFC 2554
STARTTLS  RFC 3207

Additional extensions may be handled by clients.

The smtp package is frozen and is not accepting new features. Some external packages provide more functionality. See:

https://godoc.org/?q=smtp

Index

Constants

View Source
const (
	// EncryptionTLS sets encryption type to TLS when sending email
	EncryptionTLS encryption = iota
	// EncryptionSSL sets encryption type to SSL when sending email
	EncryptionSSL
	// EncryptionNone uses no encryption when sending email
	EncryptionNone
)
View Source
const (
	// EncodingQuotedPrintable sets the message body encoding to quoted-printable
	EncodingQuotedPrintable encoding = iota
	// EncodingBase64 sets the message body encoding to base64
	EncodingBase64
	// EncodingNone turns off encoding on the message body
	EncodingNone
)
View Source
const (
	// PriorityHigh sets the email priority to High
	PriorityHigh priority = iota
	// PriorityLow sets the email priority to Low
	PriorityLow
)

Variables

This section is empty.

Functions

This section is empty.

Types

type Auth

type Auth interface {
	// Start begins an authentication with a server.
	// It returns the name of the authentication protocol
	// and optionally data to include in the initial AUTH message
	// sent to the server. It can return proto == "" to indicate
	// that the authentication should be skipped.
	// If it returns a non-nil error, the SMTP client aborts
	// the authentication attempt and closes the connection.
	Start(server *ServerInfo) (proto string, toServer []byte, err error)

	// Next continues the authentication. The server has just sent
	// the fromServer data. If more is true, the server expects a
	// response, which Next should return as toServer; otherwise
	// Next should return toServer == nil.
	// If Next returns a non-nil error, the SMTP client aborts
	// the authentication attempt and closes the connection.
	Next(fromServer []byte, more bool) (toServer []byte, err error)
}

Auth is implemented by an SMTP authentication mechanism.

func PlainAuth

func PlainAuth(identity, username, password, host string) Auth

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 to host and act as identity. Usually identity should be the empty string, to act as username.

PlainAuth will only send the credentials if the connection is using TLS or is connected to localhost. Otherwise authentication will fail with an error, without sending the credentials.

type Client

type Client struct {
	// Text is the textproto.Conn used by the Client. It is exported to allow for
	// clients to add extensions.
	Text *textproto.Conn
	// contains filtered or unexported fields
}

A Client represents a client connection to an SMTP server.

func Dial

func Dial(addr string) (*Client, error)

Dial returns a new Client connected to an SMTP server at addr. The addr must include a port, as in "mail.example.com:smtp".

func NewClient

func NewClient(conn net.Conn, host string) (*Client, error)

NewClient returns a new Client using an existing connection and host as a server name to be used when authenticating.

func (*Client) Auth

func (c *Client) Auth(a Auth) error

Auth authenticates a client using the provided authentication mechanism. A failed authentication closes the connection. Only servers that advertise the AUTH extension support this function.

func (*Client) Close

func (c *Client) Close() error

Close closes the connection.

func (*Client) Data

func (c *Client) Data() (io.WriteCloser, error)

Data issues a DATA command to the server and returns a writer that can be used to write the mail headers and body. The caller should close the writer before calling any more methods on c. A call to Data must be preceded by one or more calls to Rcpt.

func (*Client) Extension

func (c *Client) Extension(ext string) (bool, string)

Extension reports whether an extension is support by the server. The extension name is case-insensitive. If the extension is supported, Extension also returns a string that contains any parameters the server specifies for the extension.

func (*Client) Hello

func (c *Client) Hello(localName string) error

Hello sends a HELO or EHLO to the server as the given host name. Calling this method is only necessary if the client needs control over the host name used. The client will introduce itself as "localhost" automatically otherwise. If Hello is called, it must be called before any of the other methods.

func (*Client) Mail

func (c *Client) Mail(from string) error

Mail issues a MAIL command to the server using the provided email address. If the server supports the 8BITMIME extension, Mail adds the BODY=8BITMIME parameter. This initiates a mail transaction and is followed by one or more Rcpt calls.

func (*Client) Noop

func (c *Client) Noop() error

Noop sends the NOOP command to the server. It does nothing but check that the connection to the server is okay.

func (*Client) Quit

func (c *Client) Quit() error

Quit sends the QUIT command and closes the connection to the server.

func (*Client) Rcpt

func (c *Client) Rcpt(to string) error

Rcpt issues a RCPT command to the server using the provided email address. A call to Rcpt must be preceded by a call to Mail and may be followed by a Data call or another Rcpt call.

func (*Client) Reset

func (c *Client) Reset() error

Reset sends the RSET command to the server, aborting the current mail transaction.

func (*Client) StartTLS

func (c *Client) StartTLS(config *tls.Config) error

StartTLS sends the STARTTLS command and encrypts all further communication. Only servers that advertise the STARTTLS extension support this function.

type Email

type Email struct {
	Charset    string
	Encoding   encoding
	Error      error
	SMTPServer *Client
	// 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.

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, 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) AddAttachment

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

AddAttachment 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 string, name string) *Email

AddAttachmentBase64 allows you to add an attachment in base64 to the email message. You need provide a name for the file.

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 allows you to add an inline attachment to the email message. You can optionally provide a different name for the file.

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) GetError

func (email *Email) GetError() error

GetError returns the first email error encountered

func (*Email) GetMessage

func (email *Email) GetMessage() string

GetMessage builds and returns the email message

func (*Email) Send

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

Send sends the composed email

func (*Email) SetBody

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

SetBody sets the body of the email message.

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 SMTPClient

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

SMTPClient represents a SMTP Client for send email

type SMTPServer

type SMTPServer struct {
	// From           string
	Encryption     encryption
	Username       string
	Password       string
	ConnectTimeout time.Duration
	SendTimeout    time.Duration
	Host           string
	Port           int
	KeepAlive      bool
}

SMTPServer represents a SMTP Server

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

type ServerInfo

type ServerInfo struct {
	Name string   // SMTP server name
	TLS  bool     // using TLS, with valid certificate for Name
	Auth []string // advertised authentication mechanisms
}

ServerInfo records information about an SMTP server.

Jump to

Keyboard shortcuts

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