85 lines
2.5 KiB
Go
85 lines
2.5 KiB
Go
// Package mail 邮件发送配置
|
||
//
|
||
// Author : go_developer@163.com<白茶清欢>
|
||
//
|
||
// Date : 1:14 上午 2021/8/13
|
||
package mail
|
||
|
||
import (
|
||
"fmt"
|
||
"strings"
|
||
|
||
"git.zhangdeman.cn/zhangdeman/gopkg/util"
|
||
|
||
"gopkg.in/gomail.v2"
|
||
)
|
||
|
||
type Mail struct {
|
||
conf map[string]string
|
||
port int
|
||
mailDialer *gomail.Dialer
|
||
}
|
||
|
||
// NewMailMessage 获取邮件消息实例
|
||
//
|
||
// Author : go_developer@163.com<白茶清欢>
|
||
//
|
||
// Date : 1:32 上午 2021/8/13
|
||
func NewMailMessage(fromMail string, fromMailName string, pass string, host string, port int) *Mail {
|
||
m := &Mail{}
|
||
if len(fromMailName) == 0 {
|
||
fromMailName = "系统邮件"
|
||
}
|
||
m.conf = map[string]string{
|
||
"user": fromMail,
|
||
"pass": pass,
|
||
"host": host,
|
||
"port": fmt.Sprintf("%v", port),
|
||
"from_mail_name": fromMailName,
|
||
}
|
||
|
||
m.port = port
|
||
m.mailDialer = gomail.NewDialer(m.conf["host"], port, m.conf["user"], m.conf["pass"])
|
||
return m
|
||
}
|
||
|
||
// BaseSend 基础邮件发送
|
||
//
|
||
// Author : go_developer@163.com<白茶清欢>
|
||
//
|
||
// Date : 1:14 上午 2021/8/13
|
||
func (m *Mail) BaseSend(mailTo []string, subject string, body string) error {
|
||
message := gomail.NewMessage()
|
||
message.SetHeader("From", message.FormatAddress(m.conf["user"], m.conf["from_mail_name"])) //这种方式可以添加别名,即“XX官方”
|
||
//说明:如果是用网易邮箱账号发送,以下方法别名可以是中文,如果是qq企业邮箱,以下方法用中文别名,会报错,需要用上面此方法转码
|
||
//m.SetHeader("From", "FB Sample"+"<"+mailConn["user"]+">") //这种方式可以添加别名,即“FB Sample”, 也可以直接用<code>m.SetHeader("From",mailConn["user"])</code> 读者可以自行实验下效果
|
||
//m.SetHeader("From", mailConn["user"])
|
||
message.SetHeader("To", mailTo...) //发送给多个用户
|
||
message.SetHeader("Subject", subject) //设置邮件主题
|
||
message.SetBody("text/html", body) //设置邮件正文
|
||
|
||
d := gomail.NewDialer(m.conf["host"], m.port, m.conf["user"], m.conf["pass"])
|
||
|
||
return d.DialAndSend(message)
|
||
}
|
||
|
||
// TplSend 使用模版发送邮件
|
||
//
|
||
// Author : go_developer@163.com<白茶清欢>
|
||
//
|
||
// Date : 1:05 下午 2021/8/14
|
||
func (m *Mail) TplSend(mailTo []string, subject string, tpl string, bindData map[string]string) error {
|
||
var (
|
||
tplContent []byte
|
||
err error
|
||
)
|
||
if tplContent, err = util.ReadFileContent(tpl); nil != err {
|
||
return err
|
||
}
|
||
mailBody := string(tplContent)
|
||
for k, v := range bindData {
|
||
mailBody = strings.ReplaceAll(mailBody, "{"+k+"}", v)
|
||
}
|
||
return m.BaseSend(mailTo, subject, mailBody)
|
||
}
|