mailing

package module
v1.2.4 Latest Latest
Warning

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

Go to latest
Published: Sep 30, 2026 License: MIT Imports: 20 Imported by: 0

README

A Golang package for sending emails using SMTP, SparkPost, SendGrid and MailGun

This project starts from a full copy from https://github.com/harranali/mailing. 22 Sep 2026.

Features

  • Multiple File attachments
  • Multiple recipients
  • Multiple CC
  • Multiple BCC
  • HTML content type support
  • Plain Text content type support
  • Easy integration with smtp4dev testing server for development
  • Multiple Drivers Support: SMTP, SparkPost, SendGrid and MailGun

Install

Here is how to add it to your project

go get github.com/harranali/mailing

Using specific driver

Here is how to use SMTP Driver
// initiating the mailer with smtp driver
mailer := mailing.NewMailerWithSMTP(&mailing.SMTPConfig{
		Host:     "localhost", //the SMTP server host
		Port:     25, // The Port
		Username: "", 
		Password: "",
		TLSConfig: tls.Config{
			ServerName:         "localhost",
			InsecureSkipVerify: true, // (use true for development only) true accepts any certificate presented by the server
		},
	})
SMTP authentication mechanism

By default the driver selects the authentication mechanism dynamically: after STARTTLS it reads the server's advertised AUTH capabilities and prefers AUTH LOGIN (accepted by Microsoft Outlook/Office 365, Gmail, Amazon SES, Mailgun, SendGrid, Postmark, ...), falling back to AUTH PLAIN for legacy servers that only support it. This means Outlook/Office 365 accounts work out of the box even though they reject AUTH PLAIN.

You can force a specific mechanism through the AuthMechanism field:

mailer := mailing.NewMailerWithSMTP(&mailing.SMTPConfig{
		Host:          "smtp.office365.com",
		Port:          587,
		Username:      "user@yourdomain.com",
		Password:      "your-password",
		AuthMechanism: mailing.AuthLogin, // AuthAuto (default) | AuthLogin | AuthPlain
		TLSConfig: tls.Config{
			ServerName: "smtp.office365.com",
		},
	})

Leaving AuthMechanism empty keeps the previous behavior of being fully automatic and is backward compatible with existing configurations. AuthXOAuth2 is reserved as groundwork for OAuth2.

Here is how to use Spark Post Driver
// initiating the mailer with SparkPost driver
mailer := mailing.NewMailerWithSparkPost(&mailing.SparkPostConfig{
		BaseUrl:    "https://api.sparkpost.com",
		ApiKey:     "test-api-key",
		ApiVersion: 1,
	})
Here is how to use Send Grid Driver
// initiating the mailer with SendGrid driver
mailer := mailing.NewMailerWithSendGrid(&mailing.SendGridConfig{
		Host:     "https://api.sendgrid.com",
		Endpoint: "/v3/mail/send",
		ApiKey:   "API-KEY-HERE",
	})
Here is how to use Mail Gun Driver
// initiating the mailer with MailGun driver
mailer := mailing.NewMailerWithMailGun(&mailing.MailGunConfig{
		Domain: "your-domain.com",    // your-domain.com
		APIKey: "TEST-API-KEY", // your api key
		SkipTLSVerification true  // (set true for development only!) // true means accepts any tls certificate sent by the domain without verification
	})

Usage

Here is how to use it

// Initiate the package with SMTP Driver
mailer := mailing.NewMailerWithSMTP(&mailing.SMTPConfig{
		Host:     "localhost", //the SMTP server host
		Port:     25, // The Port
		Username: "", 
		Password: "",
		TLSConfig: tls.Config{
			ServerName:         "localhost",
			InsecureSkipVerify: true, // (use true for development only) true accepts any certificate presented by the server
		},
	})

// Set the Sender email address
mailer.SetFrom(mailing.EmailAddress{
        Name: "from name", // name can be set to empty string ("")
        Address: "from@mail.com",
    })

// Set the Recipients email addresses
mailer.SetTo([]mailing.EmailAddress{
        // name can be set to empty string ("")
        {Name: "first to name", Address: "theFirstTo@mail.com"},
        {Name: "second to name", Address: "theSecondTo@mail.com"},
    })

// Set CC email addresses
mailer.SetCC([]mailing.EmailAddress{
        // name can be set to empty string ("")
        {Name: "cc name", Address: "cc1@mail.com"},
        {Name: "cc name", Address: "cc2@mail.com"},
    })

// Set BCC email addresses
mailer.SetBCC([]mailing.EmailAddress{
        // name can be set to empty string ("")
        {Name: "bcc name", Address: "bcc@mail.com"},
    })

// Set the subject
mailer.SetSubject("This is the subject")

// Set the body (pick one: either HTML or Plain Text)
mailer.SetHTMLBody("<h1>This is the email body</h1>")
// OR
mailer.SetPlainTextBody("This is the email body")

// Set the sttachments files
mailer.SetAttachments([]mailing.Attachment{
        {
            Name: "first file",
            Path: "./myfiles/first-file.jpg",
        },
        {
            Name: "second file",
            Path: "./myfiles/second-file.pdf",
        },
    })
        
// Send the email
err := mailer.Send()
if err != nil {
    panic(err.Error())
}

Testing you emails with smtp4dev SMTP Testing Server

While developing your app you might need to test your emails, for that a customized docker-compose.yaml from the SMTP testing server smtp4dev is included.

Running the testing server

Copy the docker-compose.yaml to your pc, then start the container by running

docker-compose up
The testing server configuration

Here is how to connect to the testing server

mailer := mailing.NewMailerWithSMTP(&mailing.SMTPConfig{
		Host:     "localhost", //the SMTP server host
		Port:     25, // The Port
		Username: "", 
		Password: "",
		TLSConfig: tls.Config{
			ServerName:         "localhost",
			InsecureSkipVerify: true, // (use true for development only) true accepts any certificate presented by the server
		},
	})
Accessing the testing server UI

The testing server UI allows you to check the emails, here is a link to the ui of the testing server

http://localhost:5000

smtp4dev server ui

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func LoginAuth added in v1.2.3

func LoginAuth(username, password string) smtp.Auth

LoginAuth returns an smtp.Auth that authenticates using the AUTH LOGIN mechanism.

Types

type Attachment

type Attachment struct {
	Name string // name of the file
	Path string // full path to the file
}

type AuthMechanism added in v1.2.3

type AuthMechanism string

AuthMechanism selects the SMTP authentication mechanism used by the driver.

const (
	// AuthAuto lets the driver query the server's advertised AUTH capabilities
	// (after STARTTLS) and pick the best one: LOGIN when offered (accepted by
	// Outlook/Office 365, Gmail, Amazon SES, Mailgun, SendGrid, Postmark and
	// virtually all major providers), falling back to PLAIN for legacy servers
	// that only support it. This is the default when AuthMechanism is empty.
	AuthAuto AuthMechanism = "auto"
	// AuthLogin forces the AUTH LOGIN mechanism.
	AuthLogin AuthMechanism = "login"
	// AuthPlain forces the AUTH PLAIN mechanism (legacy servers only).
	AuthPlain AuthMechanism = "plain"
	// AuthXOAuth2 selects the AUTH XOAUTH2 mechanism. This is groundwork for
	// Microsoft's progressive removal of basic authentication; it is not yet
	// implemented and returns a descriptive error when selected.
	AuthXOAuth2 AuthMechanism = "xoauth2"
)

type Driver

type Driver interface {
	Send() error
	SetFrom(from mail.Address) error
	SetTo(toList []mail.Address) error
	SetCC(ccList []mail.Address) error
	SetBCC(bccList []mail.Address) error
	SetSubject(subject string) error
	SetHTMLBody(body string) error
	SetPlainTextBody(body string) error
	SetAttachments(attachments []Attachment) error
}

type EmailAddress

type EmailAddress struct {
	Name    string // the name can be empty
	Address string // ex: john@example.com
}

type MailGunConfig

type MailGunConfig struct {
	Domain              string // your-domain.com
	APIKey              string // your api key
	SkipTLSVerification bool   // (set true for development only!) // true means accepts any tls certificate sent by the domain without verification
}

type MailGunDriver

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

func (*MailGunDriver) Send

func (m *MailGunDriver) Send() error

func (*MailGunDriver) SetAttachments

func (m *MailGunDriver) SetAttachments(attachments []Attachment) error

func (*MailGunDriver) SetBCC

func (m *MailGunDriver) SetBCC(bccList []mail.Address) error

func (*MailGunDriver) SetCC

func (m *MailGunDriver) SetCC(ccList []mail.Address) error

func (*MailGunDriver) SetFrom

func (m *MailGunDriver) SetFrom(from mail.Address) error

func (*MailGunDriver) SetHTMLBody

func (m *MailGunDriver) SetHTMLBody(body string) error

func (*MailGunDriver) SetPlainTextBody

func (m *MailGunDriver) SetPlainTextBody(body string) error

func (*MailGunDriver) SetSubject

func (m *MailGunDriver) SetSubject(Subject string) error

func (*MailGunDriver) SetTo

func (m *MailGunDriver) SetTo(toList []mail.Address) error

type Mailer

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

func NewMailerWithMailGun

func NewMailerWithMailGun(config *MailGunConfig) *Mailer

Initiate the mailer with MailGun driver

func NewMailerWithSMTP

func NewMailerWithSMTP(config *SMTPConfig) *Mailer

Initiate the mailer with SMTP driver

func NewMailerWithSendGrid

func NewMailerWithSendGrid(config *SendGridConfig) *Mailer

Initiate the mailer with SendGrid driver

func NewMailerWithSparkPost

func NewMailerWithSparkPost(config *SparkPostConfig) *Mailer

Initiate the mailer with SparkPost driver

func (*Mailer) Send

func (m *Mailer) Send() error

Send the email

func (*Mailer) SetAttachments

func (m *Mailer) SetAttachments(attachments []Attachment) *Mailer

Add attachments to the email

func (*Mailer) SetBCC

func (m *Mailer) SetBCC(emailAddresses []EmailAddress) *Mailer

List of bcc of the email

func (*Mailer) SetCC

func (m *Mailer) SetCC(emailAddresses []EmailAddress) *Mailer

List of cc of the email

func (*Mailer) SetFrom

func (m *Mailer) SetFrom(emailAddress EmailAddress) *Mailer

Sender of the email

func (*Mailer) SetHTMLBody

func (m *Mailer) SetHTMLBody(body string) *Mailer

Set the body of the email in html format make sure to use only one version of the email body, either the html or the plain text to use the html, call the function SetHTMLBody(body string) and if you want to use the text, call the function SetPlainTextBody(body string)

func (*Mailer) SetPlainTextBody

func (m *Mailer) SetPlainTextBody(body string) *Mailer

Set the body of the email in plain text format make sure to use only one version of the email body, either the html or the plain text to use the html, call the function SetHTMLBody(body string) and if you want to use the text, call the function SetPlainTextBody(body string)

func (*Mailer) SetSubject

func (m *Mailer) SetSubject(subject string) *Mailer

Title of the email

func (*Mailer) SetTo

func (m *Mailer) SetTo(emailAddresses []EmailAddress) *Mailer

List of receivers of the email

type SMTPConfig

type SMTPConfig struct {
	Host      string
	Port      int
	Username  string
	Password  string
	TLSConfig tls.Config
	// AuthMechanism selects the authentication mechanism. When left empty it
	// defaults to AuthAuto (dynamic selection: prefer LOGIN, fall back to
	// PLAIN). Set it to AuthLogin or AuthPlain to force a specific mechanism.
	// Existing configurations that omit this field keep working unchanged.
	AuthMechanism AuthMechanism
	// AccessToken holds an OAuth2 access token for XOAUTH2 authentication.
	// Groundwork for the future XOAUTH2 support; unused for now.
	AccessToken string
}

type SendGridConfig

type SendGridConfig struct {
	Host     string // "https://api.sendgrid.com"
	Endpoint string // "/v3/mail/send"
	ApiKey   string // SENDGRID_API_KEY
}

type SendGridDriver

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

func (*SendGridDriver) Send

func (s *SendGridDriver) Send() error

func (*SendGridDriver) SetAttachments

func (s *SendGridDriver) SetAttachments(attachments []Attachment) error

func (*SendGridDriver) SetBCC

func (s *SendGridDriver) SetBCC(bccList []mail.Address) error

func (*SendGridDriver) SetCC

func (s *SendGridDriver) SetCC(ccList []mail.Address) error

func (*SendGridDriver) SetFrom

func (s *SendGridDriver) SetFrom(from mail.Address) error

func (*SendGridDriver) SetHTMLBody

func (s *SendGridDriver) SetHTMLBody(body string) error

func (*SendGridDriver) SetPlainTextBody

func (s *SendGridDriver) SetPlainTextBody(body string) error

func (*SendGridDriver) SetSubject

func (s *SendGridDriver) SetSubject(Subject string) error

func (*SendGridDriver) SetTo

func (s *SendGridDriver) SetTo(toList []mail.Address) error

type SparkPostConfig

type SparkPostConfig struct {
	BaseUrl    string // example: https://api.sparkpost.com
	ApiKey     string // SPARKPOST_API_KEY
	ApiVersion int    // example: 1
}

type SparkPostDriver

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

func (*SparkPostDriver) Send

func (s *SparkPostDriver) Send() error

func (*SparkPostDriver) SetAttachments

func (s *SparkPostDriver) SetAttachments(attachments []Attachment) error

func (*SparkPostDriver) SetBCC

func (s *SparkPostDriver) SetBCC(bccList []mail.Address) error

func (*SparkPostDriver) SetCC

func (s *SparkPostDriver) SetCC(ccList []mail.Address) error

func (*SparkPostDriver) SetFrom

func (s *SparkPostDriver) SetFrom(from mail.Address) error

func (*SparkPostDriver) SetHTMLBody

func (s *SparkPostDriver) SetHTMLBody(body string) error

func (*SparkPostDriver) SetPlainTextBody

func (s *SparkPostDriver) SetPlainTextBody(body string) error

func (*SparkPostDriver) SetSubject

func (s *SparkPostDriver) SetSubject(Subject string) error

func (*SparkPostDriver) SetTo

func (s *SparkPostDriver) SetTo(toList []mail.Address) error

Jump to

Keyboard shortcuts

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