From b1cdfd62f6052efbaad47d33b60159f9fe7fb66c Mon Sep 17 00:00:00 2001 From: lixxxww <941403820@qq.com> Date: Tue, 23 Jan 2024 11:36:35 +0000 Subject: [PATCH] =?UTF-8?q?=E6=8F=90=E4=BA=A4kit/mail?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: lixxxww <941403820@qq.com> --- kit/mail/mail.go | 64 +++++++++++++++++++++++++++++++++++++++++++ kit/mail/mail_test.go | 19 +++++++++++++ 2 files changed, 83 insertions(+) create mode 100644 kit/mail/mail.go create mode 100644 kit/mail/mail_test.go diff --git a/kit/mail/mail.go b/kit/mail/mail.go new file mode 100644 index 0000000..90803e7 --- /dev/null +++ b/kit/mail/mail.go @@ -0,0 +1,64 @@ +package email + +import ( + "crypto/tls" + "fmt" + "net/smtp" + "strings" + + "github.com/jordan-wright/email" +) + +type Mail struct { + Host string `json:"host"` // 服务器地址 + Port int `json:"port"` // 服务器端口 + From string `json:"from"` // 邮箱账号 + Nickname string `json:"nickname"` // 发件人 + Secret string `json:"secret"` // 邮箱密码 + IsSSL bool `json:"isSsl"` // 是否开启ssl +} + +func (m Mail) Email(to, subject string, body string) error { + tos := strings.Split(to, ",") + return m.send(tos, subject, body) +} + +//@function: ErrorToEmail +//@description: 给email中间件错误发送邮件到指定邮箱 +//@param: subject string, body string +//@return: error + +func (m Mail) ErrorToEmail(to, subject string, body string) error { + tos := strings.Split(to, ",") + if tos[len(tos)-1] == "" { // 判断切片的最后一个元素是否为空,为空则移除 + tos = tos[:len(tos)-1] + } + return m.send(tos, subject, body) +} + +//@function: send +//@description: Email发送方法 +//@param: subject string, body string +//@return: error + +func (m Mail) send(to []string, subject string, body string) error { + + auth := smtp.PlainAuth("", m.From, m.Secret, m.Host) + e := email.NewEmail() + if m.Nickname != "" { + e.From = fmt.Sprintf("%s <%s>", m.Nickname, m.From) + } else { + e.From = m.From + } + e.To = to + e.Subject = subject + e.HTML = []byte(body) + var err error + hostAddr := fmt.Sprintf("%s:%d", m.Host, m.Port) + if m.IsSSL { + err = e.SendWithTLS(hostAddr, auth, &tls.Config{ServerName: m.Host}) + } else { + err = e.Send(hostAddr, auth) + } + return err +} diff --git a/kit/mail/mail_test.go b/kit/mail/mail_test.go new file mode 100644 index 0000000..2e70e75 --- /dev/null +++ b/kit/mail/mail_test.go @@ -0,0 +1,19 @@ +package email + +import "testing" + + +// 自行替换测试账户信息 +func TestMail_Email(t *testing.T) { + ma := Mail{ + Host: "smtp.163.com", + Port: 25, + From: "x@163.com", + Nickname: "x", + Secret: "x", + IsSSL: false, + } + + email := ma.Email("xx@163.com", "ceshi", "ceshibody") + t.Log(email) +}