1. 程式人生 > 實用技巧 >golang gomail+fasttemplate+mailhog 傳送郵件

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("[email protected]", "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{
      "[email protected]",
      "[email protected]",
      "[email protected]",
     } {
      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