optimized_go_tools/am_smtp/smtp.go

87 lines
2.0 KiB
Go
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

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密码可以是授权码
}
/*
* 发送平信(纯文字信)
* 参数:
* 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
}