69 lines
2.1 KiB
Go
69 lines
2.1 KiB
Go
// Package mail 邮件发送配置
|
||
//
|
||
// Author : go_developer@163.com<白茶清欢>
|
||
//
|
||
// Date : 1:14 上午 2021/8/13
|
||
package mail
|
||
|
||
import (
|
||
"fmt"
|
||
|
||
"gopkg.in/gomail.v2"
|
||
)
|
||
|
||
var (
|
||
// Mail 邮件服务实例
|
||
Mail *mail
|
||
)
|
||
|
||
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 {
|
||
if Mail == nil {
|
||
Mail = &mail{}
|
||
if len(fromMailName) == 0 {
|
||
fromMailName = "系统邮件"
|
||
}
|
||
Mail.conf = map[string]string{
|
||
"user": fromMail,
|
||
"pass": pass,
|
||
"host": host,
|
||
"port": fmt.Sprintf("%v", port),
|
||
"from_mail_name": fromMailName,
|
||
}
|
||
|
||
Mail.port = port
|
||
Mail.mailDialer = gomail.NewDialer(Mail.conf["host"], port, Mail.conf["user"], Mail.conf["pass"])
|
||
}
|
||
return Mail
|
||
}
|
||
|
||
// 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)
|
||
}
|