smtppool

package module
v0.3.3 Latest Latest
Warning

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

Go to latest
Published: Aug 24, 2021 License: MIT Imports: 24 Imported by: 0

README

smtppool

smtppool is a Go library that creates a pool of reusable SMTP connections for high throughput e-mailing. It gracefully handles idle connections, timeouts, and retries. The e-mail formatting, parsing, and preparation code is forked from jordan-wright/email.

Install

go get github.com/knadh/smtppool

Usage
package main

import (
	"fmt"
	"log"

	"github.com/knadh/smtppool"
)

func main() {
	// Try https://github.com/mailhog/MailHog for running a local dummy SMTP server.
	// Create a new pool.
	pool, err := smtppool.New(smtppool.Opt{
		Host:            "localhost",
		Port:            1025,
		MaxConns:        10,
		IdleTimeout:     time.Second * 10,
		PoolWaitTimeout: time.Second * 3,
	})
	if err != nil {
		log.Fatalf("error creating pool: %v", err)
	}

	e:= Email{
		From:    "John Doe <john@example.com>",
		To:      []string{"doe@example.com"},

		// Optional.
		Bcc:     []string{"doebcc@example.com"},
		Cc:      []string{"doecc@example.com"},

		Subject: "Hello, World",
		Text:    []byte("This is a test e-mail"),
		HTML:    []byte("<strong>This is a test e-mail</strong>"),
	}

	// Add attachments.
	if _, err := e.AttachFile("test.txt"); err != nil {
		log.Fatalf("error attaching file: %v", err)
	}

	if err := pool.Send(e); err != nil {
		log.Fatalf("error sending e-mail: %v", err)
	}
}

Licensed under the MIT license.

Documentation

Overview

Package smtppool creates a pool of reusable SMTP connections for high throughput e-mailing.

This file was forked from: https://github.com/jordan-wright/email (MIT License, Copyright (c) 2013 Jordan Wright).

Package smtppool creates a pool of reusable SMTP connections for high throughput e-mailing.

Index

Constants

View Source
const (
	ContentTypePlain            = "text/plain"
	ContentTypeHTML             = "text/html"
	ContentTypeOctetStream      = "application/octet-stream"
	ContentTypeMultipartAlt     = "multipart/alternative"
	ContentTypeMultipartMixed   = "multipart/mixed"
	ContentTypeMultipartRelated = "multipart/related"

	// MaxLineLength is the maximum line length per RFC 2045.
	MaxLineLength = 76
)

Global constants.

View Source
const (
	HdrContentType = "Content-Type"
	HdrSubject     = "Subject"
	HdrTo          = "To"
	HdrCC          = "Cc"
	HdrBCC         = "Bcc"
	HdrFrom        = "From"
	HdrReplyTo     = "Reply-To"
	HdrDate        = "Date"
	HdrMessageID   = "Message-Id"
	HdrMimeVersion = "MIME-Version"

	HdrContentTransferEncoding = "Content-Transfer-Encoding"
	HdrContentDisposition      = "ContentDisposition"
	HdrContentID               = "Content-ID"
)

SMTP headers and fields.

Variables

View Source
var (
	// ErrMissingBoundary is returned when there is no boundary given for a multipart entity.
	ErrMissingBoundary = errors.New("no boundary found for multipart entity")

	// ErrMissingContentType is returned when there is no "Content-Type" header for a MIME entity.
	ErrMissingContentType = errors.New("no Content-Type found for MIME entity")
)
View Source
var ErrPoolClosed = errors.New("pool closed")

ErrPoolClosed is thrown when a closed Pool is used.

Functions

This section is empty.

Types

type Attachment

type Attachment struct {
	Filename    string
	Header      textproto.MIMEHeader
	Content     []byte
	HTMLRelated bool
}

Attachment is a struct representing an email attachment. Based on the mime/multipart.FileHeader struct, Attachment contains the name, MIMEHeader, and content of the attachment in question.

type Email

type Email struct {
	ReplyTo []string
	From    string
	To      []string
	Bcc     []string
	Cc      []string
	Subject string

	// Text is the optional plain text form of the message.
	Text []byte

	// HTML is the optional HTML form of the message.
	HTML []byte

	// Sender overrides From as SMTP envelope sender (optional).
	Sender      string
	Headers     textproto.MIMEHeader
	Attachments []Attachment
	ReadReceipt []string
}

Email represents an e-mail message.

func NewEmailFromReader

func NewEmailFromReader(r io.Reader) (Email, error)

NewEmailFromReader reads a stream of bytes from an io.Reader, r, and returns an email struct containing the parsed data. This function expects the data in RFC 5322 format.

func (*Email) Attach

func (e *Email) Attach(r io.Reader, filename, c string) (a Attachment, err error)

Attach is used to attach content from an io.Reader to the email. Required parameters include an io.Reader, the desired filename for the attachment, and the Content-Type The function will return the created Attachment for reference, as well as nil for the error, if successful.

func (*Email) AttachFile

func (e *Email) AttachFile(filename string) (a Attachment, err error)

AttachFile is used to attach content to the email. It attempts to open the file referenced by filename and, if successful, creates an Attachment. This Attachment is then appended to the slice of Email.Attachments. The function will then return the Attachment for reference, as well as nil for the error, if successful.

func (*Email) Bytes

func (e *Email) Bytes() ([]byte, error)

Bytes converts the Email object to a []byte representation, including all needed MIMEHeaders, boundaries, etc.

type LoginAuth

type LoginAuth struct {
	Username string
	Password string
}

LoginAuth is the SMTP "LOGIN" type implementation for smtp.Auth.

func (*LoginAuth) Next

func (a *LoginAuth) Next(fromServer []byte, more bool) ([]byte, error)

Next passes the credentials for SMTP LOGIN auth type.

func (*LoginAuth) Start

func (a *LoginAuth) Start(server *smtp.ServerInfo) (string, []byte, error)

Start starts the SMTP LOGIN auth type. https://gist.github.com/andelf/5118732

type Opt

type Opt struct {
	// Host is the SMTP server's hostname.
	Host string `json:"host"`

	// Port is the SMTP server port.
	Port int `json:"port"`

	// HelloHostname is the optional hostname to pass with the HELO command.
	// Default is "localhost".
	HelloHostname string `json:"hello_hostname"`

	// MaxConns is the maximum allowed concurrent SMTP connections.
	MaxConns int `json:"max_conns"`

	// MaxMessageRetries is the number of times a message should be retried
	// if sending fails. Default is 2. Min is 1.
	MaxMessageRetries int `json:"max_msg_retries"`

	// IdleTimeout is the maximum time to wait for new activity on a connection
	// before closing it and removing it from the pool.
	IdleTimeout time.Duration `json:"idle_timeout"`

	// PoolWaitTimeout is the maximum time to wait to obtain a connection from
	// a pool before timing out. This may happen when all open connections are
	// busy sending e-mails and they're not returning to the pool fast enough.
	// This is also the timeout used when creating new SMTP connections.
	PoolWaitTimeout time.Duration `json:"wait_timeout"`

	// Auth is the smtp.Auth authentication scheme.
	Auth smtp.Auth

	// TLSConfig is the optional TLS configuration.
	TLSConfig *tls.Config
}

Opt represents SMTP pool options.

type Pool

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

Pool represents an SMTP connection pool.

func New

func New(o Opt) (*Pool, error)

New initializes and returns a new SMTP Pool.

func (*Pool) Close

func (p *Pool) Close()

Close closes the pool.

func (*Pool) Send

func (p *Pool) Send(e Email) error

Send sends an e-mail using an available connection in the pool. On error, the message is retried on a new connection.

Jump to

Keyboard shortcuts

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