go語言發送郵件

package main

import (
    "fmt"
    "net/smtp"
    "strings"
)

//發送郵件的邏輯函數
func SendMail(user, password, host, to, subject, body, mailtype string) error {
    hp := strings.Split(host, ":")
    auth := smtp.PlainAuth("", user, password, hp[0])
    var content_type string
    if mailtype == "html" {
        content_type = "Content-Type: text/" + mailtype + "; charset=UTF-8"
    } else {
        content_type = "Content-Type: text/plain" + "; charset=UTF-8"
    }

    msg := []byte("To: " + to + "\r\nFrom: " + user + "<" + user + ">\r\nSubject: " + subject + "\r\n" + content_type + "\r\n\r\n" + body)
    send_to := strings.Split(to, ";")
    err := smtp.SendMail(host, auth, user, send_to, msg)
    return err
}

func main() {
    // 郵箱賬號
    user := "xxxx@163.com"
    //注意,此處為授權碼、不是密碼
    password := "xxx"
    //smtp地址及端口
    host := "smtp.163.com:25"
    //接收者,內容可重復,郵箱之間用;隔開
    to := "xxxx@qq.com"
    //郵件主題
    subject := "測試通過golang發送郵件"
    //郵件內容
    text := "你好!"
    body := `
    <html>
    <body>
    <h3>
    "測試通過golang發送郵件"` + text + `
    </h3>
    </body>
    </html>
    `
    fmt.Println("send email")
    //執行邏輯函數
    err := SendMail(user, password, host, to, subject, body, "html")
    if err != nil {
        fmt.Println("發送郵件失敗!")
        fmt.Println(err)
    } else {
        fmt.Println("發送郵件成功!")
    }

}

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容