golang學(xué)習(xí)筆記(4)
2111
發(fā)布于 云南 2021-03-31 · 1.3w瀏覽 2贊

      有了監(jiān)控程序我們還需要有通知的功能,這里使用郵件通知


package main

 

import (

    "fmt"

    "net/smtp"

    "strings"

)

//SendToMail 發(fā)送郵件

func SendToMail(user, password, host, to, subject, body, mailtype string) error {

    hp := strings.Split(host, ":")

    auth := smtp.PlainAuth("", user, password, hp[0])

    sendTo := strings.Split(to, ";")

    done := make(chan error, 1024)

    var contentType string

    if mailtype == "html" {

        contentType = "Content-Type: text/" + mailtype + "; charset=UTF-8"

    } else {

        contentType = "Content-Type: text/plain" + "; charset=UTF-8"

    }

 

    go func() {

        defer close(done)

        for _, strTo := range sendTo {

            msg := []byte("To: " + to + "\r\nFrom: " + user + "\r\nSubject: " + subject + "\r\n" + contentType + "\r\n\r\n" + body)

            err := smtp.SendMail(host, auth, user, []string{strTo}, msg)

            done <- err

        }

    }()

 

    for i := 0; i < len(sendTo); i++ {

        <-done

    }

    //fmt.Println(sendTo)

    return nil

}

 

main func(){

    user := "發(fā)郵件用的郵箱地址"

    password := "發(fā)郵件用的郵箱密碼"

    host := "smtp.exmail.qq.com:25"//smtp服務(wù)器地址,這里使用的是騰訊企業(yè)郵箱的smtp

    to := "接收郵件的郵箱地址1;接收郵件的郵箱地址2"//可以使用;分隔,實(shí)現(xiàn)發(fā)送到多個(gè)郵箱

    subject := "通知郵件"

    body := "<html><head><tille>通知郵件</title></head><body><h3>通知郵件測試</h3></body></html>"

    fmt.Println("sending email")

    err := SendToMail(user, password, host, to, subject, body, "html")

    if err != nil {

        fmt.Println("Send mail error!")

        fmt.Println(err)

    } else {

        fmt.Println("Send mail success!")

    }

}


      使用“net/smtp”包實(shí)現(xiàn)郵件發(fā)送功能,需要自備一個(gè)郵箱作為發(fā)件郵箱,最好使用大廠的郵箱作為發(fā)件郵箱,以免被識(shí)別為垃圾郵件拒收。

2111
~
瀏覽 1.3w
2
相關(guān)推薦
最新評(píng)論
贊過的人 2
評(píng)論加載中...

暫無評(píng)論,快來評(píng)論吧!