optimized_go_tools/am_smtp/smtp.go

87 lines
2.0 KiB
Go
Raw Normal View History

2024-07-08 03:14:19 +00:00
package am_smtp
import (
"bytes"
"gopkg.in/gomail.v2"
"html/template"
)
// EmailConnection结构体
type EmailConnection struct {
Server string `json:"server"` // smtp服务器地址
Port int `json:"port"` // smtp服务器端口
Username string `json:"user-name"` // smtp登录名
Password string `json:"password"` // smtp密码可以是授权码
2024-07-08 03:14:19 +00:00
}
/*
* 发送平信纯文字信
* 参数
* 1. from string发信邮箱地址
* 2. to []string寄送邮箱地址可以多个
* 3. subject string邮件主题
* 4. text string邮件内容
* 5. conn EmailConnection邮件连接信息
*/
func SendPlainMail(
from string,
to []string,
subject string,
text string,
conn EmailConnection,
) error {
message := gomail.NewMessage()
message.SetHeader("From", from)
message.SetHeader("To", to...)
message.SetHeader("Subject", subject)
message.SetBody("text/plain", text)
d := gomail.NewDialer(conn.Server, conn.Port, conn.Username, conn.Password)
if err := d.DialAndSend(message); err != nil {
return err
}
return nil
}
/*
* 发送HTML信
* 参数
* 1. from string发信邮箱地址
* 2. to []string寄送邮箱地址可以多个
* 3. subject string邮件主题
* 4. html string邮件内容html模板所在的路径必须能找到
* 5. data interface{}需要加载到html模板中的数据集合
* 6. conn EmailConnection邮件连接信息
*/
func SendHTMLMail(
from string,
to []string,
subject string,
html string,
data interface{},
conn EmailConnection,
) error {
tmpl, err := template.ParseFiles(html)
if err != nil {
return err
}
var body bytes.Buffer
if err := tmpl.Execute(&body, data); err != nil {
return err
}
message := gomail.NewMessage()
message.SetHeader("From", from)
message.SetHeader("To", to...)
message.SetHeader("Subject", subject)
message.SetBody("text/html", body.String())
d := gomail.NewDialer(conn.Server, conn.Port, conn.Username, conn.Password)
if err := d.DialAndSend(message); err != nil {
return err
}
return nil
}