smtp v1

A Go package that provides a simple interface for sending emails via SMTP.

Repository

Installation

go get -u github.com/metadiv-io/smtp

Environment Variables

The package requires the following environment variables:

  • SMTP_HOST: SMTP server host

  • SMTP_PORT: SMTP server port

  • SMTP_USERNAME: SMTP account username/email

  • SMTP_PASSWORD: SMTP account password

  • SMTP_DISPLAY_NAME: Display name for the sender (optional)

Usage

Creating a Dialer

There are two ways to create an SMTP dialer:

  1. Using environment variables:

dialer := smtp.NewDefaultDialer()
  1. Manual configuration:

dialer := smtp.NewDialer(
    "Company Name",     // display name
    "smtp.gmail.com",   // host
    587,               // port
    "user@gmail.com",  // username
    "your-password",   // password
)

Sending Emails

The package supports both HTML and plain text emails:

Sending HTML Email

to := smtp.EmailList("recipient@example.com")
cc := smtp.EmailList("cc@example.com")
bcc := smtp.EmailList("bcc@example.com")

subject := "Hello {{name}}"
body := "<h1>Hello {{name}}</h1><p>This is an HTML email</p>"

// Optional: Value map for template replacement
values := map[string]string{
    "{{name}}": "John",
}

err := dialer.SendHTMLEmail(to, cc, bcc, subject, body, values)

Sending Text Email

to := smtp.EmailList("recipient@example.com")
cc := smtp.EmailList("cc@example.com")
bcc := smtp.EmailList("bcc@example.com")

subject := "Hello {{name}}"
body := "Hello {{name}}, this is a plain text email"

// Optional: Value map for template replacement
values := map[string]string{
    "{{name}}": "John",
}

err := dialer.SendTextEmail(to, cc, bcc, subject, body, values)

Helper Functions

EmailList

Creates a slice of email addresses:

emails := smtp.EmailList("user1@example.com", "user2@example.com")

Features

  • Environment variable configuration support

  • HTML and plain text email support

  • Template variable replacement in subject and body

  • Multiple recipients (To, CC, BCC)

  • Custom sender display name

  • Simple and intuitive API

Dependencies

  • gopkg.in/mail.v2: For email handling

  • github.com/metadiv-io/env: For environment variable management

Notes

  • The sender email will use the display name if provided, otherwise it will use the username

  • Template replacement is optional and can be omitted by not providing a values map

  • Empty CC and BCC lists are allowed

Last updated