Go 使用 gomail 发送邮件

我们使用 gomail 这个库来发送邮件

下载库

go get gopkg.in/gomail.v2

调用库

package main

import (
    "gopkg.in/gomail.v2"
    "mime"
    "strconv"
    "sync"
)

func sendMail(mailTo string, subject, body string,wg *sync.WaitGroup)error {
    defer wg.Done()
    mailConn := map[string]string{
        "username": "support@****",
        "authCode": "****",
        "host":     "smtp.exmail.qq.com",
        "port":     "465",
    }
    port,_:=strconv.Atoi(mailConn["port"])
    m:=gomail.NewMessage()
    m.SetHeader("From",mime.QEncoding.Encode("UTF-8","Support")+"<"+mailConn["username"]+">")
    m.SetHeader("To",mailTo)
    m.SetHeader("Subject",subject)
    m.SetBody("text/html",body)
    d:=gomail.NewDialer(mailConn["host"],port,mailConn["username"],mailConn["authCode"])
    err:=d.DialAndSend(m)
    if err != nil {
        log.Fatalln("To:",mailTo,"##","Send Email Failed!Err:",err)
    }else{
        log.Println("To:",mailTo,"##","Send Email Successfully!")
    }
}

func main() {
    var wg sync.WaitGroup
    mailTo:=[]string{
        "***@live.com",
        "*****@qq.com",
    }
    subject:="Hello,Go Mail"
    body:="

Hello From Go Mail hhhhh

" for _,mail:=range mailTo{ wg.Add(1) go sendMail(mail,subject,body,&wg) } wg.Wait() }

使用Goruntine 来并发发送邮件。

你可能感兴趣的:(Go 使用 gomail 发送邮件)