golang电子邮件和SMTP测试工具插件库MailHog的使用
Golang电子邮件和SMTP测试工具插件库MailHog的使用
概述
MailHog是一个用于开发者的电子邮件测试工具:
- 配置您的应用程序使用MailHog进行SMTP投递
- 在Web界面中查看消息,或通过JSON API检索它们
- 可选地将消息释放到真实的SMTP服务器进行投递
安装
MacOS安装
brew update && brew install mailhog
然后,在命令行中运行mailhog
启动MailHog。
Debian/Ubuntu (Go < v1.18)
sudo apt-get -y install golang-go
go get github.com/mailhog/MailHog
Go >= v1.17 (Debian Bookworm)
sudo apt-get -y install golang-go
go install github.com/mailhog/MailHog@latest
然后,在命令行中运行/path/to/MailHog
启动MailHog。例如,在Ubuntu上Go的bin文件路径是~/go/bin/
,所以可以这样启动:
~/go/bin/MailHog
FreeBSD安装
pkg install mailhog
sysrc mailhog_enable="YES"
service mailhog start
Docker安装
可以从Docker Hub运行MailHog,或使用提供的Dockerfile。
配置
查看如何配置MailHog,或使用默认设置:
- SMTP服务器在端口1025上启动
- HTTP服务器在端口8025上启动
- 内存中的消息存储
功能特点
- 实现RFC5321的ESMTP服务器
- 支持SMTP AUTH (RFC4954)和PIPELINING (RFC2920)
- 查看消息的Web界面(纯文本、HTML或源代码)
- 使用EventSource实现实时更新
- 将消息释放到真实的SMTP服务器
- 用于故障测试的Chaos Monkey
- 通过HTTP API列出、检索和删除消息
- MailHog UI和API的HTTP基本认证
- 多部分MIME支持
- 下载单个MIME部分
- 内存中的消息存储
- 基于MongoDB和文件的消息持久化存储
- 轻量级和可移植
- 无需安装
sendmail
mhsendmail是MailHog的sendmail替代品。它使用SMTP将邮件重定向到MailHog。
您也可以使用MailHog sendmail ...
代替单独的mhsendmail二进制文件。
或者,您可以通过提供-S
来使用本地的sendmail
命令,例如:
/usr/sbin/sendmail -S mail:1025
例如,在PHP中,您可以将以下任一行添加到php.ini
中:
sendmail_path = /usr/local/bin/mhsendmail
sendmail_path = /usr/sbin/sendmail -S mail:1025
Web界面
Golang使用示例
以下是一个使用Golang通过MailHog发送测试邮件的完整示例:
package main
import (
"fmt"
"net/smtp"
)
func main() {
// MailHog SMTP服务器配置
smtpHost := "localhost"
smtpPort := "1025"
from := "from@example.com"
to := []string{"to@example.com"}
message := []byte("Subject: MailHog Test\r\n\r\nThis is a test email sent via MailHog.")
// 连接到MailHog SMTP服务器
// 注意:MailHog不需要认证,所以用户名和密码可以为空
auth := smtp.PlainAuth("", "", "", smtpHost)
// 发送邮件
err := smtp.SendMail(smtpHost+":"+smtpPort, auth, from, to, message)
if err != nil {
fmt.Println("Error sending email:", err)
return
}
fmt.Println("Email sent successfully!")
}
贡献
MailHog是MailHog的重写版本,源自M3MTA。
克隆此仓库到$GOPATH/src/github.com/mailhog/MailHog
并输入make deps
。
需要Go 1.4+来构建。
使用make test
或goconvey
运行测试。
如果您做了任何更改,在提交pull请求之前运行go fmt ./...
。
许可证
版权所有 © 2014 - 2017, Ian Kent
根据MIT许可证发布,详情请参阅LICENSE。
更多关于golang电子邮件和SMTP测试工具插件库MailHog的使用的实战教程也可以访问 https://www.itying.com/category-94-b0.html