mail

package module
v0.0.0-...-d4e6e90 Latest Latest
Warning

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

Go to latest
Published: Dec 14, 2025 License: MIT Imports: 12 Imported by: 0

README

go-mail

Go Reference Go Report Card

go-mail: Go library for sending emails, supporting SMTP, attachments, and convenient message building.

Installation

go get github.com/fawwazid/go-mail

Features

  • Fluent Message Builder: Easily construct emails with a chainable API.
  • Attachments: Support for file attachments and inline files, with automatic base64 encoding.
  • SMTP Support: Built-in support for SSL, TLS (StartTLS), and plain connections.
  • Mocking: Includes a MockClient for easy unit testing in your application.

Usage

Sending a Simple Email
package main

import (
	"log"

	"github.com/fawwazid/go-mail"
)

func main() {
	// Create a new message
	msg := mail.NewMessage().
		SetFrom("[email protected]").
		AddTo("[email protected]").
		SetSubject("Hello from Go!").
		SetBody("text/plain", "This is a test email sent using go-mail.")

	// Create client (e.g., using Mailtrap, Gmail, etc.)
	// For Gmail usage, you likely need an App Password.
	client := mail.NewClient("smtp.example.com", 587, "user", "pass", mail.EncryptionTLS)

	// Send the email
	if err := client.Send(msg); err != nil {
		log.Fatalf("Failed to send email: %v", err)
	}
}
Sending HTML Email with Attachments
msg := mail.NewMessage().
    SetFrom("[email protected]").
    AddTo("[email protected]").
    SetSubject("Monthly Report").
    SetBody("text/html", "<h1>Report</h1><p>Please find the report attached.</p>")

// Add file from disk
if err := msg.AddAttachment("./report.pdf"); err != nil {
    log.Fatal(err)
}

// Add file from bytes
data := []byte("some content")
msg.AddAttachmentData("data.txt", data, "text/plain")

client := mail.NewClient("smtp.example.com", 465, "user", "pass", mail.EncryptionSSL)
if err := client.Send(msg); err != nil {
    log.Fatal(err)
}

Testing

You can use mail.MockClient to test your code without sending real emails.

mock := mail.NewMockClient()
myCodeThatSendsEmail(mock) // Inject the mock

if len(mock.SentMessages) != 1 {
    t.Errorf("Expected 1 message, got %d", len(mock.SentMessages))
}

License

MIT

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type Attachment

type Attachment struct {
	Filename    string
	ContentType string
	Content     []byte
	Inline      bool
}

Attachment represents an email attachment.

func CreateAttachmentFromFile

func CreateAttachmentFromFile(path string, opts ...FileOption) (*Attachment, error)

CreateAttachmentFromFile creates an Attachment from a file path. It reads the file content and sets the filename.

func (*Attachment) Base64

func (a *Attachment) Base64() string

Base64 returns the base64 encoded content of the attachment.

type Client

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

Client represents an SMTP client.

func NewClient

func NewClient(host string, port int, username, password string, encryption EncryptionType) *Client

NewClient creates a new SMTP client.

func (*Client) Send

func (c *Client) Send(messages ...*Message) error

Send sends one or more messages using the SMTP client. It handles potential connection and authentication details.

type EncryptionType

type EncryptionType string

EncryptionType defines the type of encryption to use for the SMTP connection.

const (
	// EncryptionNone uses no encryption.
	EncryptionNone EncryptionType = "NONE"
	// EncryptionSSL uses implicit SSL/TLS (usually port 465).
	EncryptionSSL EncryptionType = "SSL"
	// EncryptionTLS uses explicit TLS (STARTTLS, usually port 587).
	EncryptionTLS EncryptionType = "TLS"
)

type FileOption

type FileOption func(*Attachment)

FileOption defines options for attaching files.

func WithFileName

func WithFileName(name string) FileOption

WithFileName overrides the filename of the attachment.

func WithInline

func WithInline(inline bool) FileOption

WithInline sets the attachment as inline.

type Mailer

type Mailer interface {
	Send(messages ...*Message) error
}

Mailer defines an interface for sending emails. It is useful for dependency injection and testing.

type Message

type Message struct {
	From        string
	To          []string
	Cc          []string
	Bcc         []string
	Subject     string
	Body        string
	ContentType string // "text/plain" or "text/html"
	Attachments []*Attachment
}

Message represents an email message.

func NewMessage

func NewMessage() *Message

NewMessage creates a new empty message. Default Content-Type is text/plain.

func (*Message) AddAttachment

func (m *Message) AddAttachment(path string, opts ...FileOption) error

AddAttachment adds an attachment from a file path.

func (*Message) AddAttachmentData

func (m *Message) AddAttachmentData(filename string, content []byte, contentType string) *Message

AddAttachmentData adds an attachment from bytes.

func (*Message) AddBcc

func (m *Message) AddBcc(emails ...string) *Message

AddBcc adds recipients to the Bcc list.

func (*Message) AddCc

func (m *Message) AddCc(emails ...string) *Message

AddCc adds recipients to the Cc list.

func (*Message) AddTo

func (m *Message) AddTo(emails ...string) *Message

AddTo adds recipients to the To list.

func (*Message) Bytes

func (m *Message) Bytes() ([]byte, error)

Bytes returns the byte representation of the message.

func (*Message) SetBody

func (m *Message) SetBody(contentType, body string) *Message

SetBody sets the email body and content type.

func (*Message) SetFrom

func (m *Message) SetFrom(from string) *Message

SetFrom sets the sender address.

func (*Message) SetSubject

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

SetSubject sets the email subject.

func (*Message) Validate

func (m *Message) Validate() error

Validate checks if the message has minimum required fields.

type MockClient

type MockClient struct {
	SentMessages []*Message
	Err          error
}

MockClient is a mock implementation of Client for testing purposes.

func NewMockClient

func NewMockClient() *MockClient

NewMockClient creates a new MockClient.

func (*MockClient) Send

func (m *MockClient) Send(messages ...*Message) error

Send records the sent messages and returns any configured error.

Jump to

Keyboard shortcuts

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