目录

golang使用mailgun发邮件

golang使用mailgun发邮件

1. mailgun平台配置

在使用 Mailgun 发送邮件之前,你需要完成以下配置:

  1. 注册 Mailgun 账号 并获取 API Key。
  2. 验证你的域名(或使用 Mailgun 提供的 Sandbox 域名 进行测试)。
  3. 在 Mailgun 控制面板中找到你的 Private API Key 和 域名。
  4. 确保你的邮箱地址被 Mailgun 允许发送邮件(如果使用 Sandbox,接收者必须是验证邮箱)。

2. curl测试api key

在终端执行以下 curl 命令,确保 API Key 可用:

curl -s --user 'api:${API_KEY}' \
    https://api.mailgun.net/v3/xxxx.com/messages \
    -F from='Mailgun Sandbox <postmaster@xxxx.com>' \
    -F to='Tlt <tlt@gmail.com>' \
    -F subject='Hello Tlt' \
    -F text='Congratulations Tlt, you just sent an email with Mailgun! You are truly awesome!'

如果返回 200 或 202,说明 API Key 配置正确。

3. golang使用apikey发邮件

安装 Mailgun SDK

首先,安装 mailgun-go 依赖包:

go get github.com/mailgun/mailgun-go/v4

代码示例

以下是一个完整的 Go 代码示例,展示如何通过 Mailgun 发送邮件:

package main

import (
	"context"
	"fmt"
	"time"

	"github.com/mailgun/mailgun-go/v4"
)

func main() {
	// 从环境变量获取 API Key,防止硬编码泄露敏感信息
	apiKey := os.Getenv("API_KEY")
	if apiKey == "" {
		apiKey = "your-mailgun-api-key" // 请替换为你的 API Key
	}

	// 调用发送邮件函数
	// 请替换为你的 Mailgun 域名
	id, err := SendSimpleMessage("xxx.com", apiKey)
	fmt.Println(id)
	fmt.Println(err)
}

func SendSimpleMessage(domain, apiKey string) (string, error) {
	mg := mailgun.NewMailgun(domain, apiKey)

	//When you have an EU-domain, you must specify the endpoint:
	// mg.SetAPIBase("https://api.eu.mailgun.net/v3")
	m := mailgun.NewMessage(
		"Mailgun Sandbox <postmaster@xxxx.com>",
		"Hello Y Test",
		"Congratulations , you just sent an email with Mailgun! You are truly awesome!",
		"Tlt <tlt@gmail.com>",
	)

	// 创建带超时的上下文,避免 API 请求卡住
	ctx, cancel := context.WithTimeout(context.Background(), time.Second*30)
	defer cancel()

	_, id, err := mg.Send(ctx, m)
	return id, err
}

执行结果(成功发送邮件)

<20250317161129.4534a9e976fbd54a@dcertx.com>
<nil>

4.总结

  1. 先使用 curl 命令测试 API Key,确保 Mailgun 配置无误。
  2. 使用 Mailgun Go SDK,编写 SendSimpleMessage 函数,发送邮件。
  3. 使用环境变量管理 API Key,避免硬编码暴露敏感信息。
  4. 如果使用 Mailgun EU 服务器,需要设置 API Base。
  5. 确保 Mailgun 账号已验证,避免邮件发送失败。

这样,你就可以顺利地在 Golang 项目中集成 Mailgun 发送邮件了!🚀