golang gomail+fasttemplate+mailhog 发送邮件
今天有写过一个基于go-simple-mail 发送email 的demo,主要是复用连接,但是发现有问题,后边尝试了下
gomail,发现很不错没有问题,通过分析代码,还是go-simple-mail 实现上的问题
gomail参考demo
大部分不变,主要是修改关于email 发送的实现
参考代码
emailv2.go
package notify
import (
"demoapp/config"
"io/ioutil"
"log"
"github.com/valyala/fasttemplate"
"gopkg.in/gomail.v2"
)
// EmailNotidy2 is a email notify
type EmailNotidy2 struct {
config config.Config
dialer *gomail.Dialer
templateCache map[string]string
}
// NewEailNotidy2 NewEailNotidy2 instance
func NewEailNotidy2() *EmailNotidy2 {
config := config.New()
d := gomail.NewDialer(config.Email.ServerHost, config.Email.ServerPort, config.Email.FromEmail, config.Email.FromPasswd)
bytes, err := ioutil.ReadFile(config.Template.EmailTemplate)
if err != nil {
log.Fatalf("init mail instance error:%s", err.Error())
}
return &EmailNotidy2{
config: config,
dialer: d,
templateCache: map[string]string{
config.Template.EmailTemplate: string(bytes),
},
}
}
// Send Send
func (e *EmailNotidy2) Send(to string, subject string, datafiles map[string]interface{}) error {
t := fasttemplate.New(e.templateCache[e.config.Template.EmailTemplate], "{{", "}}")
htmlBody := t.ExecuteString(datafiles)
m := gomail.NewMessage()
m.SetHeader("From", e.config.Email.FromEmail)
m.SetHeader("Subject", subject)
m.SetBody("text/plain", htmlBody)
sender, err := e.dialer.Dial()
err = sender.Send(e.config.Email.FromEmail, []string{to}, m)
if err != nil {
return err
}
return nil
}
main.go
package main
import (
"demoapp/notify"
"log"
"net/http"
_ "net/http/pprof"
"sync"
)
func main() {
emailnotidy := notify.NewEailNotidy2()
// not working tcp out of order
http.HandleFunc("/send", func(res http.ResponseWriter, req *http.Request) {
res.Write([]byte("send email"))
wg := sync.WaitGroup{}
wg.Add(2)
for i := 0; i < 2; i++ {
go func(wg *sync.WaitGroup) {
defer wg.Done()
err := emailnotidy.Send("dalong@qq.com", "demoapp", map[string]interface{}{
"content": "dalongdemoapp",
})
if err != nil {
log.Println("err:", err.Error())
}
}(&wg)
}
wg.Wait()
})
http.HandleFunc("/send2", func(res http.ResponseWriter, req *http.Request) {
res.Write([]byte("send email"))
for _, to := range []string{
"to1@example1.com",
"to3@example2.com",
"to4@example3.com",
} {
err := emailnotidy.Send(to, "demoapp", map[string]interface{}{
"content": "dalongdemoapp",
})
if err != nil {
log.Println("err:", err.Error())
}
}
})
http.ListenAndServe(":9090", nil)
}
参考资料
https://github.com/rongfengliang/golang-email-learning/tree/v2