优化发邮件

This commit is contained in:
xing 2022-11-16 15:46:55 +08:00
parent db8906e239
commit fc10308df6
2 changed files with 14 additions and 20 deletions

View File

@ -6,7 +6,7 @@ import (
"github/fthvgb1/wp-go/config" "github/fthvgb1/wp-go/config"
"gopkg.in/gomail.v2" "gopkg.in/gomail.v2"
"mime" "mime"
"strings" "path"
) )
type AttacheFile struct { type AttacheFile struct {
@ -14,12 +14,7 @@ type AttacheFile struct {
Path string Path string
} }
func (f AttacheFile) GetName() string { func SendMail(mailTo []string, subject string, body string, files ...string) error {
t := strings.Split(f.Path, ".")
return fmt.Sprintf("%s.%s", f.Name, t[len(t)-1])
}
func SendMail(mailTo []string, subject string, body string, a ...AttacheFile) error {
m := gomail.NewMessage( m := gomail.NewMessage(
gomail.SetEncoding(gomail.Base64), gomail.SetEncoding(gomail.Base64),
) )
@ -32,12 +27,13 @@ func SendMail(mailTo []string, subject string, body string, a ...AttacheFile) er
m.SetHeader("Subject", subject) m.SetHeader("Subject", subject)
m.SetBody("text/html", body) m.SetBody("text/html", body)
for _, files := range a { for _, file := range files {
m.Attach(files.Path, _, f := path.Split(file)
gomail.Rename(files.Name), //重命名 m.Attach(file,
gomail.Rename(f), //重命名
gomail.SetHeader(map[string][]string{ gomail.SetHeader(map[string][]string{
"Content-Disposition": { "Content-Disposition": {
fmt.Sprintf(`attachment; filename="%s"`, mime.QEncoding.Encode("UTF-8", files.GetName())), fmt.Sprintf(`attachment; filename="%s"`, mime.QEncoding.Encode("UTF-8", f)),
}, },
}), }),
) )

View File

@ -6,12 +6,15 @@ import (
) )
func TestSendMail(t *testing.T) { func TestSendMail(t *testing.T) {
config.InitConfig("config.yaml") err := config.InitConfig("../config.yaml")
if err != nil {
panic(err)
}
type args struct { type args struct {
mailTo []string mailTo []string
subject string subject string
body string body string
a []AttacheFile files []string
} }
tests := []struct { tests := []struct {
name string name string
@ -24,18 +27,13 @@ func TestSendMail(t *testing.T) {
mailTo: []string{"fthvgb1@163.com"}, mailTo: []string{"fthvgb1@163.com"},
subject: "测试发邮件", subject: "测试发邮件",
body: "测试发邮件", body: "测试发邮件",
a: []AttacheFile{ files: []string{"/home/xing/Downloads/favicon.ico"},
{
Name: "附件",
Path: "/home/xing/Downloads/favicon.ico",
},
},
}, },
}, },
} }
for _, tt := range tests { for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) { t.Run(tt.name, func(t *testing.T) {
if err := SendMail(tt.args.mailTo, tt.args.subject, tt.args.body, tt.args.a...); (err != nil) != tt.wantErr { if err := SendMail(tt.args.mailTo, tt.args.subject, tt.args.body, tt.args.files...); (err != nil) != tt.wantErr {
t.Errorf("SendMail() error = %v, wantErr %v", err, tt.wantErr) t.Errorf("SendMail() error = %v, wantErr %v", err, tt.wantErr)
} }
}) })