diff --git a/mail/mail.go b/mail/mail.go index 25ac561..0598117 100644 --- a/mail/mail.go +++ b/mail/mail.go @@ -6,7 +6,7 @@ import ( "github/fthvgb1/wp-go/config" "gopkg.in/gomail.v2" "mime" - "strings" + "path" ) type AttacheFile struct { @@ -14,12 +14,7 @@ type AttacheFile struct { Path string } -func (f AttacheFile) GetName() string { - 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 { +func SendMail(mailTo []string, subject string, body string, files ...string) error { m := gomail.NewMessage( gomail.SetEncoding(gomail.Base64), ) @@ -32,12 +27,13 @@ func SendMail(mailTo []string, subject string, body string, a ...AttacheFile) er m.SetHeader("Subject", subject) m.SetBody("text/html", body) - for _, files := range a { - m.Attach(files.Path, - gomail.Rename(files.Name), //重命名 + for _, file := range files { + _, f := path.Split(file) + m.Attach(file, + gomail.Rename(f), //重命名 gomail.SetHeader(map[string][]string{ "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)), }, }), ) diff --git a/mail/mail_test.go b/mail/mail_test.go index dfcbe25..6546bb5 100644 --- a/mail/mail_test.go +++ b/mail/mail_test.go @@ -6,12 +6,15 @@ import ( ) func TestSendMail(t *testing.T) { - config.InitConfig("config.yaml") + err := config.InitConfig("../config.yaml") + if err != nil { + panic(err) + } type args struct { mailTo []string subject string body string - a []AttacheFile + files []string } tests := []struct { name string @@ -24,18 +27,13 @@ func TestSendMail(t *testing.T) { mailTo: []string{"fthvgb1@163.com"}, subject: "测试发邮件", body: "测试发邮件", - a: []AttacheFile{ - { - Name: "附件", - Path: "/home/xing/Downloads/favicon.ico", - }, - }, + files: []string{"/home/xing/Downloads/favicon.ico"}, }, }, } for _, tt := range tests { 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) } })