Beego¶
适用于 Beego 2.x(Go 1.22+)应用的集成指南。Mailexam 通过标准库 net/smtp 在 587 端口使用 STARTTLS 作为 SMTP 接入。
前置条件¶
- Mailexam 账户,以及已创建并具备 SMTP 凭据的项目。
- Go 1.22+。
从项目的欢迎邮件(或控制台)中复制:
YOUR_LOGIN— SMTP 登录名(例如xxxxx);YOUR_PASSWORD— SMTP 密码(与登录名成对的唯一凭据);- 主机 —
YOUR_LOGIN.mailexam.cn(与登录名一致)。
1. 依赖¶
go mod init example.com/mailexam-beego
go get github.com/beego/beego/v2@v2.3.4
go get github.com/joho/godotenv@v1.5.1
go.mod 文件(go get 后解析版本):
module example.com/mailexam-beego
go 1.22
require (
github.com/beego/beego/v2 v2.3.4
github.com/joho/godotenv v1.5.1
)
2. 环境变量¶
项目根目录的 .env 文件(勿将密码提交到 git):
MAILEXAM_LOGIN=YOUR_LOGIN
MAILEXAM_PASSWORD=YOUR_PASSWORD
MAILEXAM_PORT=587
MAIL_FROM=noreply@example.test
SMTP 主机:YOUR_LOGIN.mailexam.cn。
发件人地址
MAIL_FROM 可以是任意测试地址——邮件进入 Mailexam,而非真实收件人。
备选端口¶
3. 邮件发送模块¶
与 Gin 相同方式:项目根目录的 mail.go。
// mail.go
package main
import (
"crypto/tls"
"fmt"
"net"
"net/smtp"
"os"
"strconv"
)
func sendTest(to, subject, body string) error {
login := os.Getenv("MAILEXAM_LOGIN")
password := os.Getenv("MAILEXAM_PASSWORD")
if login == "" || password == "" {
return fmt.Errorf("MAILEXAM_LOGIN and MAILEXAM_PASSWORD must be set")
}
port, _ := strconv.Atoi(os.Getenv("MAILEXAM_PORT"))
if port == 0 {
port = 587
}
from := os.Getenv("MAIL_FROM")
if from == "" {
from = "noreply@example.test"
}
if to == "" {
to = "user@example.test"
}
if subject == "" {
subject = "Beego + Mailexam"
}
if body == "" {
body = "来自 Beego 的 Mailexam 测试"
}
host := login + ".mailexam.cn"
addr := fmt.Sprintf("%s:%d", host, port)
auth := smtp.PlainAuth("", login, password, host)
msg := []byte(fmt.Sprintf(
"From: %s\r\nTo: %s\r\nSubject: %s\r\nMIME-Version: 1.0\r\nContent-Type: text/plain; charset=UTF-8\r\n\r\n%s",
from, to, subject, body,
))
if port == 587 || port == 2525 {
return sendWithSTARTTLS(addr, host, auth, from, []string{to}, msg)
}
return smtp.SendMail(addr, auth, from, []string{to}, msg)
}
func sendWithSTARTTLS(addr, host string, auth smtp.Auth, from string, to []string, msg []byte) error {
conn, err := net.Dial("tcp", addr)
if err != nil {
return err
}
defer conn.Close()
client, err := smtp.NewClient(conn, host)
if err != nil {
return err
}
defer client.Close()
if ok, _ := client.Extension("STARTTLS"); ok {
if err = client.StartTLS(&tls.Config{ServerName: host}); err != nil {
return err
}
}
if auth != nil {
if err = client.Auth(auth); err != nil {
return err
}
}
if err = client.Mail(from); err != nil {
return err
}
for _, rcpt := range to {
if err = client.Rcpt(rcpt); err != nil {
return err
}
}
w, err := client.Data()
if err != nil {
return err
}
if _, err = w.Write(msg); err != nil {
return err
}
if err = w.Close(); err != nil {
return err
}
return client.Quit()
}
4. 控制器与路由¶
// main.go
package main
import (
"encoding/json"
"github.com/joho/godotenv"
beego "github.com/beego/beego/v2/server/web"
)
type sendRequest struct {
To string `json:"to"`
Subject string `json:"subject"`
Body string `json:"body"`
}
type MailController struct {
beego.Controller
}
func (c *MailController) PostTest() {
var req sendRequest
if len(c.Ctx.Input.RequestBody) > 0 {
_ = json.Unmarshal(c.Ctx.Input.RequestBody, &req)
}
if err := sendTest(req.To, req.Subject, req.Body); err != nil {
c.Ctx.Output.SetStatus(500)
c.Data["json"] = map[string]string{"error": err.Error()}
c.ServeJSON()
return
}
c.Data["json"] = map[string]string{"status": "ok"}
c.ServeJSON()
}
func main() {
_ = godotenv.Load()
beego.BConfig.Listen.HTTPAddr = "127.0.0.1"
beego.BConfig.Listen.HTTPPort = 8080
beego.Router("/mail/test", &MailController{}, "post:PostTest")
beego.Run()
}
启动并验证:
curl -X POST http://127.0.0.1:8080/mail/test \
-H 'Content-Type: application/json' \
-d '{"to":"user@example.test","subject":"测试","body":"你好"}'
邮件将出现在 Mailexam 控制台 → 您的项目 → 收件箱。
bee new 结构(可选)¶
执行 bee new 后,将 MailController 移至 controllers/mail.go,路由 — 至 routers/router.go:
5. 本地开发与 CI¶
| 环境 | 建议 |
|---|---|
local |
.env + 在 main 中 godotenv.Load() |
| CI | GitLab CI/CD Variables 中的密钥 MAILEXAM_LOGIN、MAILEXAM_PASSWORD |
.gitlab-ci.yml 示例:
variables:
MAILEXAM_LOGIN: $MAILEXAM_LOGIN
MAILEXAM_PASSWORD: $MAILEXAM_PASSWORD
MAILEXAM_PORT: "587"
MAIL_FROM: "noreply@example.test"
集成测试后,通过 Mailexam API 验证投递。
6. 常见问题¶
TLS 或认证失败
- 代码中
host—{login}.mailexam.cn,PlainAuth中 — 同一登录名。 - 登录名和密码为同一项目的邮件成对凭据。
587 端口
- 需要 STARTTLS(
sendWithSTARTTLS),不能直接使用无 TLS 的smtp.SendMail。
POST 请求体为空
- Beego 在
c.Ctx.Input.RequestBody中读取请求体;JSON 须设置Content-Type: application/json头。
控制台中看不到邮件
- 查看同一 Mailexam 项目的收件箱。
- 设置
beego.BConfig.RunMode = "dev",在500响应时检查日志。
参见¶
- 示例目录
- Beego 实现示例
- Gin — 另一 Go 框架,使用相同 SMTP 模块
- Mailexam API 文档
- Beego 文档