SoFunction
Updated on 2025-04-13

Use Go language encapsulation to implement email sending function

In modern web development, the email sending function is a common requirement, especially in scenarios such as user registration, password reset, notification, etc., verification codes or other information are often required to send via email. This article will introduce how to encapsulate a common email sending package in Go language, supporting verification code sending and universal email sending.

Target

Encapsulate a packet sent by email

Support SMTP protocol to send emails

Provides the function of sending verification codes and ordinary emails

Implement object-oriented design through structures and methods

Complete unit testing to ensure code robustness

Dependency package

Before you start, you need to introduce the following dependencies:

go get /jordan-wright/email
go get /zap
go get /stretchr/testify
  • /jordan-wright/email: A commonly used Go language email sending library, simplifying the SMTP sending process.
  • /zap: An efficient log library developed by Uber for logging.
  • /stretchr/testify: Go's unit test library.

Project structure

├── email
│   ├──
│   └── email_test.go
├── model
│   └──
├── pkg
│   └──
├──
├──
└──

Code implementation

email/

Create email/ file and encapsulate email sending function.

package email

import (
	"fmt"
	"gin-mall/model"
	"gin-mall/pkg/logger"
	"net/smtp"
	"time"

	"/jordan-wright/email"
	"/zap"
)

// Emailtype Email struct {
	config  Config   // Email configuration	From    string   // Sender	To      []string // recipient	Subject string   // theme	Body    string   // content}

// Config mail configurationtype Config struct {
	SMTPServer string // SMTP server	SMTPPort   int    // SMTP port	Username   string // username	Password   string // password}

// NewEmail Create an Email instancefunc NewEmail(config Config) *Email {
	e := &Email{config: config}
	 = 
	return e
}

// SetFrom Set the senderfunc (e *Email) SetFrom(from string) {
	 = from
}

// SetTo Set Recipientfunc (e *Email) SetTo(to []string) {
	 = to
}

// AppendTo Add Recipientfunc (e *Email) AppendTo(to string) {
	 = append(, to)
}

// SetSubject Set the mail subjectfunc (e *Email) SetSubject(subject string) {
	 = subject
}

// SetBody Set the email contentfunc (e *Email) SetBody(body string) {
	 = body
}

// Send send emailfunc (e *Email) Send() error {
	auth := ("", , , )

	host := ("%s:%d", , )

	eClient := ()
	 = 
	 = 
	 = 
	 = []byte()

	err := (host, auth)
	if err != nil {
		return err
	}

	return nil
}

// SendVerifyCode Send verification codefunc (e *Email) SendVerifyCode(receiver, code, key string) error {
	// Save the verification code to cache	err := (key, code, 5*)
	if err != nil {
		("Cache setting failed", (err))
		return err
	}

	// Send email	msg := ("【XXX】Your verification code is: %s, please complete the verification within 5 minutes.", code)
	(receiver)
	("GinMall Verification Code")
	(msg)

	return ()
}

Main method description

Method name Function illustrate
NewEmail Create a new mail instance Create an email structure by passing in SMTP configuration
SetFrom Set the sender Customizable sender
SetTo Set up recipients Set the recipient array directly
AppendTo Add a recipient Dynamically add recipients
SetSubject Setting up the theme Set the title of the email
SetBody Set content Set the content of the email
Send Send an email Send emails via SMTP protocol
SendVerifyCode Send verification code Generate and send verification code

Unit Testing

email/email_test.go

Create email/email_test.go to test the email sending function.

package email

import (
	"testing"

	"/stretchr/testify/assert"
)

func TestSendEmail(t *) {
	config := Config{
		SMTPServer: "smtp.",
		SMTPPort:   25,
		Username:   "your-email@",
		Password:   "your-password",
	}

	email := NewEmail(config)
	(t, email)

	()
	("receiver@")
	("Test Email")
	("This is a test email.")

	err := ()
	(t, err)

	("Email sent successfully")
}

Example of usage

In the file, directly call the encapsulated method to send emails:

package main

import (
	"log"
	"gin-mall/email"
)

func main() {
	config := {
		SMTPServer: "smtp.",
		SMTPPort:   25,
		Username:   "your-email@",
		Password:   "your-password",
	}

	email := (config)
	()
	("receiver@")
	("Welcome to GinMall")
	("Thank you for signing up to GinMall!")

	err := ()
	if err != nil {
		("Failed to send email: %v", err)
	} else {
		("Email sent successfully")
	}
}

Code highlights

✅ Object-oriented design, well encapsulated

✅ Use /zap to record logs

✅Simplify SMTP sending with /jordan-wright/email

✅Use /stretchr/testify for unit testing

Directions for improvement

Support HTML format email content

Supports adding attachments

Setting mail parameters through configuration files

Add a retry mechanism for failed email sending

Summarize

By encapsulating /jordan-wright/email, we can quickly implement the email sending function. Well-encapsulated structures and methods make the code easier to expand and reuse. hope

This is the end of this article about using Go language to encapsulate the email sending function. For more related Go email sending content, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!