gomailer

package module
v1.0.0 Latest Latest
Warning

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

Go to latest
Published: Dec 19, 2024 License: MIT Imports: 8 Imported by: 0

README

GoMailer Library

This Go Mailer Library provides a convenient way to send emails with support for attachments, multipart messages (HTML and plain text), and various authentication mechanisms. It supports features such as:

  • Sending emails with plain text, HTML content, or both (multipart/alternative).
  • Sending attachments with base64 encoding.
  • Customizable headers for the email message.
  • Handling different email formats (e.g., text/plain, text/html, multipart/alternative, multipart/mixed).

Installation

To install the library, run:

go get github.com/NawafSwe/gomailer

Usage

Creating a Mailer Client First, you need to create a new mailer client by calling the NewMailer function and passing the necessary parameters such as host, port, username, and password. You can also use the provided configuration options to customize the mailer client.

package main

import (
    "crypto/tls"
    "time"
	
    "github.com/NawafSwe/gomailer"
)

func main() {
    // Create a new mailer client with basic configuration
    mailer := gomailer.NewMailer(
        "smtp.example.com", // SMTP server host
        587,                // SMTP server port
        "user@example.com", // Username
        "password",         // Password
        // Additional configuration options
        gomailer.WithLocalName("localhost"),
        gomailer.WithTLSConfig(&tls.Config{InsecureSkipVerify: true}),
        gomailer.WithDialTimeout(10*time.Second),
        gomailer.WithSSLEnabled(true),
    )

    // Use the mailer client to send emails
    // ...
}

Configuration Options

Here are the available configuration options you can use with the NewMailer function:

  • WithLocalName: Configures the mailer with a local name.
  • WithTLSConfig: Configures the mailer with a custom tls.Config.
  • WithDialTimeout: Configures the mailer with a custom dial timeout.
  • WithAuth: Configures the mailer with a custom SMTP authentication mechanism.
  • WithSecrets: Configures the mailer with secrets for CRAM-MD5 authentication.
  • WithSSLEnabled: Configures the mailer to use SSL.

Sending an Email

Once you have configured the mailer client, you can construct and send email messages. Here is how you can do it: Create a New Message: Instantiate a new Message struct using the NewMessage function. Set Message Fields: Set the necessary fields such as From, Recipients, Subject, Body, HTMLBody, etc. Send the Message: Use the Send method of the mailer client to send the message.

package main

import (
    "log"
	
    "github.com/NawafSwe/gomailer"
    "github.com/NawafSwe/gomailer/message"
)

func main() {
    // Create a new mailer client
    mailer := gomailer.NewMailer(
        "smtp.example.com",
        587,
        "user@example.com",
        "password",
        gomailer.WithLocalName("localhost"),
        gomailer.WithTLSConfig(&tls.Config{InsecureSkipVerify: true}),
        gomailer.WithDialTimeout(10*time.Second),
        gomailer.WithSSLEnabled(true),
    )

    // Create a new email message
    msg := message.NewMessage()
    msg.From = "sender@example.com"
    msg.Recipients = []string{"recipient@example.com"}
    msg.Subject = "Test Email"
    msg.Body = "This is a plain text email body"
    msg.HTMLBody = "<p>This is an <b>HTML</b> email body</p>"

    // Optional: Set Cc, Bcc, or custom headers
    msg.Cc = []string{"cc@example.com"}
    msg.Bcc = []string{"bcc@example.com"}

    // Optional: Add attachments
    attachment := message.Attachment{
        Filename: "document.pdf",
        Data:     []byte("binary-data"),
        MIMEType: "application/pdf",
    }
    msg.Attachments = append(msg.Attachments, attachment)

    // Send the message
    if err := mailer.Send(msg); err != nil {
        log.Fatalf("failed to send email: %v", err)
    }
}

Connecting and Authenticating Once

To avoid establishing a connection to the SMTP server every time you send an email, you can use the ConnectAndAuthenticate method to connect and authenticate once, and then reuse the connection for multiple emails. Remember to call the Close method after you finish sending emails to terminate the connection.

package main

import (
    "log"
    "github.com/NawafSwe/gomailer"
    "github.com/NawafSwe/gomailer/message"
)

func main() {
    // Create a new mailer client
    mailer := gomailer.NewMailer(
        "smtp.example.com",
        587,
        "user@example.com",
        "password",
        gomailer.WithLocalName("localhost"),
        gomailer.WithTLSConfig(&tls.Config{InsecureSkipVerify: true}),
        gomailer.WithDialTimeout(10*time.Second),
        gomailer.WithSSLEnabled(true),
    )

    // Connect and authenticate once
    sender, err := mailer.ConnectAndAuthenticate()
    if err != nil {
        log.Fatalf("failed to connect and authenticate: %v", err)
    }
    defer sender.Close()

    // Create a new email message
    msg := message.NewMessage()
    msg.From = "sender@example.com"
    msg.Recipients = []string{"recipient@example.com"}
    msg.Subject = "Test Email"
    msg.Body = "This is a plain text email body"
    msg.HTMLBody = "<p>This is an <b>HTML</b> email body</p>"

    // Send the message
    if err := sender.Send(msg); err != nil {
        log.Fatalf("failed to send email: %v", err)
    }
}

Features

  • Plain Text and HTML Emails: Send emails with plain text, HTML content, or both.
  • Attachments: Attach files to your emails with base64 encoding.
  • Custom Headers: Add custom headers to your email messages.
  • Multiple Recipients: Support for To, Cc, and Bcc recipients.

License

This project is licensed under the MIT License. See the LICENSE file for details.

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func WithAuth

func WithAuth(auth smtp.Auth) func(*Mailer)

WithAuth configures Mailer with smtp.Auth mechanism.

func WithDialTimeout

func WithDialTimeout(t time.Duration) func(*Mailer)

WithDialTimeout configures Mailer with time.Duration for dial timeout.

func WithLocalName

func WithLocalName(l string) func(mailer *Mailer)

WithLocalName configures Mailer with localName.

func WithSSLEnabled

func WithSSLEnabled(s bool) func(*Mailer)

WithSSLEnabled configures Mailer with ssl option.

func WithSecrets

func WithSecrets(s string) func(*Mailer)

WithSecrets configures Mailer with secrets to authenticate for CRAM-MD5.

func WithTLSConfig

func WithTLSConfig(cfg *tls.Config) func(*Mailer)

WithTLSConfig configures Mailer with tls.Config.

Types

type Mailer

type Mailer struct {
	// Port represents the port of the SMTP server.
	Port int
	// Host represents the host of the SMTP server.
	Host string
	// Username is used to authenticate to the SMTP server.
	Username string
	// Password is the password to use to authenticate to the SMTP server.
	Password string
	// contains filtered or unexported fields
}

Mailer encapsulates the connection overhead and holds the email functionality. It provides methods to send emails with and without TLS.

func NewMailer

func NewMailer(host string, port int, username, password string, opts ...Options) *Mailer

NewMailer creates a new mailer to send emails via smtp.

func (*Mailer) ConnectAndAuthenticate

func (m *Mailer) ConnectAndAuthenticate() (SendCloser, error)

ConnectAndAuthenticate connects and authenticates the Mailer to an SMTP server and saves the connection internally. To terminate the connection, the consumer must issue a Mailer.Close call after they finish sending emails.

Returns:

SendCloser: An interface that provides methods to send emails and close the connection.
error: An error if the connection or authentication fails, or nil if successful.

The function performs the following steps: 1. Establishes a TLS connection to the SMTP server using the provided host and port. 2. If SSL is enabled (port is 465), it wraps the connection with TLS. 3. Creates a new SMTP client using the established connection. 4. If a local name is provided, it sends a HELO/EHLO command with the local name. 5. If the port is not 465, it checks for the STARTTLS extension and starts TLS if supported. 6. Checks for supported authentication mechanisms and sets the appropriate authentication method. 7. Authenticates with the SMTP server using the selected authentication method. 8. Returns a mailSender instance that implements the SendCloser interface.

func (*Mailer) Send

func (m *Mailer) Send(message message.Message) error

Send dials the SMTP server with the proper authentication and sends an email.

Parameters:

  • message (message.Message): The message to be sent.

Returns:

  • error: An error if the email could not be sent, or nil if the email was sent successfully.

The function performs the following steps: 1. Connects and authenticates to the SMTP server using the `ConnectAndAuthenticate` method of the `Mailer` struct. 2. Sends the email using the `Send` method of the `SendCloser` interface. 3. Closes the connection to the SMTP server.

Example usage:

mailer := NewMailer("smtp.example.com", 465, "user@example.com", "password")
message := message.Message{
    From:       "sender@example.com",
    Recipients: []string{"recipient@example.com"},
    Body:       "This is a test email.",
}
err := mailer.Send(message)
if err != nil {
    log.Fatalf("Failed to send email: %v", err)
}

type Options

type Options func(*Mailer)

Options to configure Mailer.

type SendCloser

type SendCloser interface {
	// Close terminate the smtp server session.
	Close() error
	// Send sends message.Message.
	Send(message message.Message) error
}

SendCloser is an interface that encapsulates the functionality of sending a message and closing the connection to the SMTP server. It provides methods to send an email message and to terminate the SMTP server session.

Directories

Path Synopsis
internal
mock
Package mock is a generated GoMock package.
Package mock is a generated GoMock package.

Jump to

Keyboard shortcuts

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