gopkg/mail/mail.go

97 lines
2.9 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 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)
}
// TplContentSend 使用模版发送邮件
//
// Author : go_developer@163.com<白茶清欢>
//
// Date : 1:05 下午 2021/8/14
func (m *Mail) TplContentSend(mailTo []string, subject string, tplContent string, bindData map[string]string) error {
for k, v := range bindData {
tplContent = strings.ReplaceAll(tplContent, "{"+k+"}", v)
}
return m.BaseSend(mailTo, subject, tplContent)
}