email

package
v0.37.0 Latest Latest
Warning

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

Go to latest
Published: Mar 23, 2026 License: AGPL-3.0 Imports: 7 Imported by: 0

README

Email Package

This package provides email functionality for the Dracory framework. It includes:

  • SMTP email sending
  • Responsive HTML email templates
  • Plain text conversion from HTML

Usage

Sending Emails
import (
    "github.com/yourusername/dracory/base/email"
    "log/slog"
)

// Create a logger
logger := slog.Default()

// Create an email sender
sender := email.NewSMTPSender(email.Config{
    Host:     "smtp.example.com",
    Port:     "587",
    Username: "username",
    Password: "password",
    Logger:   logger,
})

// Send an email
err := sender.Send(email.SendOptions{
    From:     "sender@example.com",
    To:       []string{"recipient@example.com"},
    Subject:  "Test Email",
    HtmlBody: "<h1>Hello World</h1><p>This is a test email.</p>",
})

if err != nil {
    // Handle error
}
Using Email Templates
import "github.com/yourusername/dracory/base/email"

// Create email content
content := "<h1 style='" + email.StyleHeading + "'>Welcome!</h1>" +
           "<p style='" + email.StyleParagraph + "'>Thank you for registering.</p>" +
           "<a href='https://example.com/confirm' style='" + email.StyleButton + "'>Confirm Email</a>"

// Generate email template
template := email.DefaultTemplate(email.TemplateOptions{
    Title:   "Welcome to Our App",
    Content: content,
    AppName: "My Application",
    HeaderLinks: map[string]string{
        "Login": "https://example.com/login",
    },
})

// Use the template in SendOptions
sender.Send(email.SendOptions{
    From:     "sender@example.com",
    To:       []string{"recipient@example.com"},
    Subject:  "Welcome to Our App",
    HtmlBody: template,
})

Customization

The email template can be customized by providing different options to the DefaultTemplate function:

  • Title: The email title (appears in the browser tab)
  • Content: The HTML content of the email
  • AppName: The application name (appears in header and footer)
  • HeaderBackgroundColor: The background color of the header (default: #17A2B8)
  • Year: The copyright year (default: current year)
  • HeaderLinks: A map of link text to URLs for the header

Style Constants

The package provides comprehensive style constants for consistent email styling across all projects. These constants define inline CSS styles required for proper email client rendering.

Typography Styles
  • StyleHeading1 - Primary heading (24px, bold)
  • StyleHeading2 - Secondary heading (20px, bold)
  • StyleHeading3 - Tertiary heading (18px, bold)
  • StyleParagraph - Standard paragraph (16px, 1.6 line height)
  • StyleSmall - Small text for disclaimers (14px)
Button Styles
  • StyleButtonPrimary - Main call-to-action (blue background)
  • StyleButtonSecondary - Secondary action (outlined, no background)
  • StyleButtonSuccess - Positive actions (green background)
  • StyleButtonDanger - Destructive actions (red background)
  • StyleButtonSmall - Smaller button variant
Layout Styles
  • StyleContainer - Centered container (max-width 600px)
  • StyleSection - Content section with light background
  • StyleDivider - Horizontal rule/separator
  • StyleCard - Bordered card container
Alert Styles
  • StyleAlertInfo - Informational messages (blue)
  • StyleAlertSuccess - Success messages (green)
  • StyleAlertWarning - Warning messages (yellow)
  • StyleAlertDanger - Error/danger messages (red)
List Styles
  • StyleListUnordered - Unordered (bulleted) lists
  • StyleListOrdered - Ordered (numbered) lists
  • StyleListItem - Individual list items
Table Styles
  • StyleTable - Base table style
  • StyleTableHead - Table header cells
  • StyleTableCell - Table data cells
Utility Styles
  • StyleTextCenter - Center text horizontally
  • StyleTextRight - Align text to the right
  • StyleTextMuted - Muted/secondary text (gray)
  • StyleTextPrimary - Primary brand color text (blue)
  • StyleTextSuccess - Success state text (green)
  • StyleTextDanger - Danger/error state text (red)
  • StyleTextWarning - Warning state text (yellow)
  • StyleBgLight - Light background color
  • StyleBgDark - Dark background color
Usage Example
import (
    "github.com/dracory/base/email"
    "github.com/dracory/hb"
)

// Create styled email content
h1 := hb.Heading1().
    HTML("Welcome to Our Service").
    Style(email.StyleHeading1)

p := hb.Paragraph().
    HTML("Thank you for registering with us.").
    Style(email.StyleParagraph)

button := hb.Hyperlink().
    Text("Get Started").
    Href("https://example.com/start").
    Style(email.StyleButtonPrimary)

alert := hb.Div().
    HTML("Important: Please verify your email address.").
    Style(email.StyleAlertInfo)

content := hb.Div().Children([]hb.TagInterface{
    h1,
    p,
    button,
    alert,
}).ToHTML()

// Generate full email template
template := email.DefaultTemplate(email.TemplateOptions{
    Title:   "Welcome",
    Content: content,
    AppName: "My Application",
})
Using Email Components (Laravel-style)

This package provides a set of pre-styled components that make building emails as easy as in Laravel. They return *hb.Tag objects that you can further customize if needed.

import "github.com/dracory/base/email"

// Build a complex email body using components
content := email.Container(
    email.Heading("Welcome to Dracory!", 1),
    email.Paragraph("We're glad to have you on board."),
    email.Section(
        email.Heading("Your Profile Status", 2),
        email.Alert("Your email is not verified yet.", "warning"),
        email.Button("Verify Email", "https://example.com/verify"),
    ),
    email.Divider(),
    email.Table(
        []string{"Feature", "Status"},
        [][]string{
            {"API Access", "Enabled"},
            {"Storage", "10GB"},
        },
    ),
).ToHTML()

// Use the generated content in the template
htmlBody := email.DefaultTemplate(email.TemplateOptions{
    Title:   "Welcome",
    Content: content,
    AppName: "MyApp",
})

Brand Color Customization

The package provides brand color variables that can be customized to match your project's brand identity.

Available Color Variables
  • ColorPrimary - Main brand color (default: #007BFF blue)
  • ColorSecondary - Secondary elements (default: #6C757D gray)
  • ColorSuccess - Success states (default: #28A745 green)
  • ColorDanger - Error/danger states (default: #DC3545 red)
  • ColorWarning - Warnings (default: #FFC107 yellow)
  • ColorInfo - Informational messages (default: #17A2B8 teal)
  • ColorLight - Light backgrounds (default: #F8F9FA)
  • ColorDark - Dark elements (default: #343A40)
Method 1: Override Individual Colors

Customize specific colors in your project's init() function:

package main

import (
    "github.com/dracory/base/email"
)

func init() {
    // Set your brand's primary color (e.g., purple)
    email.ColorPrimary = "#6f42c1"
    
    // Set your brand's header color for templates
    email.ColorInfo = "#17A2B8" // Teal for Dracory brand
}
Method 2: Set All Brand Colors at Once

Use SetBrandColors() to customize all colors in one call:

func init() {
    email.SetBrandColors(
        "#6f42c1", // Primary (purple)
        "#6C757D", // Secondary (gray)
        "#28A745", // Success (green)
        "#DC3545", // Danger (red)
        "#FFC107", // Warning (yellow)
        "#17A2B8", // Info (teal)
        "#F8F9FA", // Light
        "#343A40", // Dark
    )
}
Method 3: Custom Style Builders

For one-off custom colors, use style builder functions:

// Create a custom purple button
purpleButton := email.ButtonStyle("#6f42c1", "#5a32a3", "white")

// Create an outlined button with custom color
outlinedPurple := email.ButtonStyleSecondary("#6f42c1")

// Create a custom alert with brand colors
customAlert := email.AlertStyle("#e9d5ff", "#d8b4fe", "#3b0764")
Usage Example with Custom Brand
package main

import (
    "github.com/dracory/base/email"
    "github.com/dracory/hb"
)

func init() {
    // Customize for a purple brand theme
    email.ColorPrimary = "#6f42c1"
}

func sendWelcomeEmail() {
    // This button will now be purple instead of blue
    button := hb.Hyperlink().
        Text("Get Started").
        Href("https://example.com/start").
        Style(email.StyleButtonPrimary)
    
    // This text will also use the purple brand color
    brandText := hb.Span().
        Text("Premium Features").
        Style(email.StyleTextPrimary)
    
    // Generate email with custom header color
    template := email.DefaultTemplate(email.TemplateOptions{
        Title:                 "Welcome",
        Content:               content,
        AppName:               "MyApp",
        HeaderBackgroundColor: "#6f42c1", // Match brand color
    })
}
Important Notes
  • Color variables must be set before using any styles that depend on them
  • The best place to set colors is in your project's init() function
  • Color changes affect all emails using the base package styles
  • For template headers, use HeaderBackgroundColor in TemplateOptions

Documentation

Index

Constants

View Source
const (
	// StyleHeading1 is the primary heading style (24px, bold)
	StyleHeading1 = "margin:0px;padding:10px 0px;text-align:left;font-size:24px;font-weight:600;color:#333333;"

	// StyleHeading2 is the secondary heading style (20px, bold)
	StyleHeading2 = "margin:0px;padding:8px 0px;text-align:left;font-size:20px;font-weight:600;color:#333333;"

	// StyleHeading3 is the tertiary heading style (18px, bold)
	StyleHeading3 = "margin:0px;padding:6px 0px;text-align:left;font-size:18px;font-weight:600;color:#333333;"

	// StyleParagraph is the standard paragraph style (16px, normal line height)
	StyleParagraph = "margin:0px;padding:10px 0px;text-align:left;font-size:16px;line-height:1.6;color:#333333;"

	// StyleSmall is for smaller text like disclaimers or footnotes (14px)
	StyleSmall = "margin:0px;padding:5px 0px;text-align:left;font-size:14px;color:#666666;"
)

Typography Styles

These constants define inline CSS styles for text elements in HTML emails. Email clients require inline styles for proper rendering.

View Source
const (
	// StyleContainer is a centered container with max-width (600px)
	StyleContainer = "max-width: 600px; margin: 0 auto; padding: 20px; background-color: #ffffff;"

	// StyleSection is a content section with light background
	StyleSection = "margin: 20px 0px; padding: 15px; background-color: #f8f9fa; border-radius: 6px;"

	// StyleDivider is a horizontal rule/separator
	StyleDivider = "height: 1px; background-color: #dee2e6; margin: 20px 0px; border: none;"

	// StyleCard is a bordered card container
	StyleCard = "padding: 20px; background-color: #ffffff; border: 1px solid #dee2e6; border-radius: 8px; margin: 10px 0px;"
)

Layout Styles

These constants define inline CSS styles for layout containers and sections.

View Source
const (
	// StyleAlertInfo is for informational messages (uses ColorInfo)
	StyleAlertInfo = "" /* 127-byte string literal not displayed */

	// StyleAlertSuccess is for success messages (uses ColorSuccess)
	StyleAlertSuccess = "" /* 127-byte string literal not displayed */

	// StyleAlertWarning is for warning messages (uses ColorWarning)
	StyleAlertWarning = "" /* 127-byte string literal not displayed */

	// StyleAlertDanger is for error/danger messages (uses ColorDanger)
	StyleAlertDanger = "" /* 127-byte string literal not displayed */
)

Alert Styles

These constants define inline CSS styles for alert/notification boxes.

View Source
const (
	// StyleListUnordered is for unordered (bulleted) lists
	StyleListUnordered = "margin: 10px 0px; padding-left: 20px; color: #333333;"

	// StyleListOrdered is for ordered (numbered) lists
	StyleListOrdered = "margin: 10px 0px; padding-left: 20px; color: #333333;"

	// StyleListItem is for individual list items
	StyleListItem = "margin: 5px 0px; line-height: 1.5;"
)

List Styles

These constants define inline CSS styles for lists.

View Source
const (
	// StyleTable is the base table style
	StyleTable = "width: 100%; border-collapse: collapse; margin: 15px 0px;"

	// StyleTableHead is for table header cells
	StyleTableHead = "background-color: #f8f9fa; border: 1px solid #dee2e6; padding: 12px; text-align: left; font-weight: 600;"

	// StyleTableCell is for table data cells
	StyleTableCell = "border: 1px solid #dee2e6; padding: 12px; text-align: left;"
)

Table Styles

These constants define inline CSS styles for tables.

Variables

View Source
var (
	// ColorPrimary is the main brand color (default: blue)
	// Override example: email.ColorPrimary = "#6f42c1" // purple
	ColorPrimary = "#007BFF"

	// ColorSecondary is for secondary elements (default: gray)
	ColorSecondary = "#6C757D"

	// ColorSuccess is for positive/success states (default: green)
	ColorSuccess = "#28A745"

	// ColorDanger is for errors/danger states (default: red)
	ColorDanger = "#DC3545"

	// ColorWarning is for warnings (default: yellow/orange)
	ColorWarning = "#FFC107"

	// ColorInfo is for informational messages (default: teal/cyan)
	ColorInfo = "#17A2B8"

	// ColorLight is for light backgrounds (default: light gray)
	ColorLight = "#F8F9FA"

	// ColorDark is for dark elements (default: dark gray)
	ColorDark = "#343A40"
)

BrandColor allows projects to customize email colors to match their brand. These variables can be overridden in a project's init() function.

View Source
var (
	// StyleButtonPrimary is the main call-to-action button (uses ColorPrimary)
	StyleButtonPrimary = "display: inline-block; padding: 12px 24px; font-size: 16px; font-weight:600; color: white; background-color: " + ColorPrimary + "; text-align: center; text-decoration: none; border-radius: 6px; border: 1px solid " + ColorPrimary + ";"

	// StyleButtonSecondary is a secondary action button (outlined, uses ColorPrimary)
	StyleButtonSecondary = "display: inline-block; padding: 12px 24px; font-size: 16px; font-weight:600; color: " + ColorPrimary + "; background-color: transparent; text-align: center; text-decoration: none; border-radius: 6px; border: 2px solid " + ColorPrimary + ";"

	// StyleButtonSuccess is for positive actions (uses ColorSuccess)
	StyleButtonSuccess = "display: inline-block; padding: 12px 24px; font-size: 16px; font-weight:600; color: white; background-color: " + ColorSuccess + "; text-align: center; text-decoration: none; border-radius: 6px; border: 1px solid " + ColorSuccess + ";"

	// StyleButtonDanger is for destructive actions (uses ColorDanger)
	StyleButtonDanger = "display: inline-block; padding: 12px 24px; font-size: 16px; font-weight:600; color: white; background-color: " + ColorDanger + "; text-align: center; text-decoration: none; border-radius: 6px; border: 1px solid " + ColorDanger + ";"

	// StyleButtonSmall is a smaller button variant (uses ColorPrimary)
	StyleButtonSmall = "display: inline-block; padding: 8px 16px; font-size: 14px; font-weight:600; color: white; background-color: " + ColorPrimary + "; text-align: center; text-decoration: none; border-radius: 4px; border: 1px solid " + ColorPrimary + ";"
)

Button Styles

These variables define inline CSS styles for button/link elements. They use BrandColor variables which can be customized per-project. Use these for call-to-action links in emails.

View Source
var (
	// StyleTextCenter centers text horizontally
	StyleTextCenter = "text-align: center;"

	// StyleTextRight aligns text to the right
	StyleTextRight = "text-align: right;"

	// StyleTextMuted is for muted/secondary text (gray)
	StyleTextMuted = "color: #6c757d;"

	// StyleTextPrimary is for primary brand color text (uses ColorPrimary)
	StyleTextPrimary = "color: " + ColorPrimary + ";"

	// StyleTextSuccess is for success state text (uses ColorSuccess)
	StyleTextSuccess = "color: " + ColorSuccess + ";"

	// StyleTextDanger is for danger/error state text (uses ColorDanger)
	StyleTextDanger = "color: " + ColorDanger + ";"

	// StyleTextWarning is for warning state text (uses ColorWarning)
	StyleTextWarning = "color: " + ColorWarning + ";"

	// StyleBgLight is for light background color (uses ColorLight)
	StyleBgLight = "background-color: " + ColorLight + ";"

	// StyleBgDark is for dark background color (uses ColorDark)
	StyleBgDark = "background-color: " + ColorDark + ";"
)

Utility Styles

These variables define inline CSS utility styles for common formatting needs. They use BrandColor variables which can be customized per-project.

Functions

func Alert added in v0.37.0

func Alert(text, variant string) *hb.Tag

Alert creates a styled alert box. Supported variants: info, success, warning, danger.

func AlertStyle added in v0.37.0

func AlertStyle(backgroundColor, borderColor, textColor string) string

AlertStyle generates a custom alert style with specified colors. Use this when you need alerts with custom color schemes.

Example:

customAlert := email.AlertStyle("#6f42c1", "#e9d5ff", "#3b0764")
// Creates a purple-themed alert

func Button added in v0.37.0

func Button(text, url string) *hb.Tag

Button creates a styled primary brand button.

func ButtonDanger added in v0.37.0

func ButtonDanger(text, url string) *hb.Tag

ButtonDanger creates a styled danger button.

func ButtonSecondary added in v0.37.0

func ButtonSecondary(text, url string) *hb.Tag

ButtonSecondary creates a styled secondary (outlined) button.

func ButtonSmall added in v0.37.0

func ButtonSmall(text, url string) *hb.Tag

ButtonSmall creates a smaller primary button.

func ButtonStyle added in v0.37.0

func ButtonStyle(backgroundColor, borderColor, textColor string) string

ButtonStyle generates a custom button style with the specified colors. Use this when you need a button with a specific brand color not covered by BrandColor variables.

Example:

customButton := email.ButtonStyle("#6f42c1", "#5a32a3", "white")
// Creates a purple button with darker purple border and white text

func ButtonStyleSecondary added in v0.37.0

func ButtonStyleSecondary(color string) string

ButtonStyleSecondary generates a custom outlined button style. Use this for secondary actions with custom brand colors.

Example:

customSecondaryBtn := email.ButtonStyleSecondary("#6f42c1")
// Creates an outlined purple button

func ButtonSuccess added in v0.37.0

func ButtonSuccess(text, url string) *hb.Tag

ButtonSuccess creates a styled success button.

func Card added in v0.37.0

func Card(children ...hb.TagInterface) *hb.Tag

Card creates a styled card container.

func Container added in v0.37.0

func Container(children ...hb.TagInterface) *hb.Tag

Container creates a styled container with maximum width.

func DefaultTemplate

func DefaultTemplate(options TemplateOptions) string

DefaultTemplate generates a standard responsive email template

func Divider added in v0.37.0

func Divider() *hb.Tag

Divider creates a horizontal rule/separator.

func Heading added in v0.37.0

func Heading(text string, level int) *hb.Tag

Heading creates a styled heading (level 1-3). If level is outside 1-3, it defaults to Heading1.

func Paragraph added in v0.37.0

func Paragraph(text string) *hb.Tag

Paragraph creates a styled paragraph.

func Section added in v0.37.0

func Section(children ...hb.TagInterface) *hb.Tag

Section creates a styled section with a light background.

func SetBrandColors added in v0.37.0

func SetBrandColors(primary, secondary, success, danger, warning, info, light, dark string)

SetBrandColors allows setting all brand colors at once. Call this in your project's init() function to customize email colors.

Example:

func init() {
    email.SetBrandColors(
        "#6f42c1", // Primary (purple)
        "#6C757D", // Secondary (gray)
        "#28A745", // Success (green)
        "#DC3545", // Danger (red)
        "#FFC107", // Warning (yellow)
        "#17A2B8", // Info (teal)
        "#F8F9FA", // Light
        "#343A40", // Dark
    )
}

func Small added in v0.37.0

func Small(text string) *hb.Tag

Small creates a styled small paragraph.

func Table added in v0.37.0

func Table(headers []string, rows [][]string) *hb.Tag

Table creates a styled data table from headers and rows.

Types

type Config

type Config struct {
	// Host is the SMTP server host
	Host string

	// Port is the SMTP server port
	Port string

	// Username is the SMTP server username
	Username string

	// Password is the SMTP server password
	Password string

	// Logger for logging errors
	Logger *slog.Logger
}

Config holds the email configuration

type SMTPSender

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

SMTPSender implements the Sender interface using SMTP

func (*SMTPSender) Send

func (s *SMTPSender) Send(options SendOptions) error

Send sends an email using SMTP

type SendOptions

type SendOptions struct {
	// From is the email sender
	From string

	// FromName is the name of the sender (unused for now)
	FromName string

	// To is the list of recipients
	To []string

	// Bcc is the list of BCC recipients
	Bcc []string

	// Cc is the list of CC recipients
	Cc []string

	// Subject is the email subject
	Subject string

	// HtmlBody is the HTML content of the email
	HtmlBody string

	// TextBody is the plain text content of the email
	TextBody string
}

SendOptions defines the options for sending an email

type Sender

type Sender interface {
	// Send sends an email with the given options
	Send(options SendOptions) error
}

Sender defines the interface for sending emails

func NewSMTPSender

func NewSMTPSender(config Config) Sender

NewSMTPSender creates a new SMTP email sender

type TemplateOptions

type TemplateOptions struct {
	// Title is the email title
	Title string

	// Content is the HTML content to include in the template
	Content string

	// AppName is the application name to display in the header and footer
	AppName string

	// HeaderBackgroundColor is the background color for the header
	HeaderBackgroundColor string

	// Year is the copyright year (defaults to current year if empty)
	Year string

	// HeaderLinks is a map of link text to URLs for the header
	HeaderLinks map[string]string
}

TemplateOptions defines the options for generating an email template

Jump to

Keyboard shortcuts

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