1. 程式人生 > >GoLang郵件發送Demo(繼上篇msmtp)

GoLang郵件發送Demo(繼上篇msmtp)

test div else ucc success println pre pla hub

  GoLang越來越被看好,流行只是時間的問題了,閑暇時間玩玩Go。

  下面是發送郵件的demo,替換自己的郵箱,完全可以正常跑起來,用的是net/smtp包:

package main

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

func SendToMail(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 + "\r\nSubject: " + subject + "\r\n" + content_type + "\r\n\r\n" + body)
	err := smtp.SendMail(host, auth, user, []string{to}, msg)
	return err
}

func main() {
	user := "[email protected]"
	password := "********"
	host := "smtp.qq.com:587"
	to := "[email protected]"

	subject := "使用Golang發送郵件"

	body := `
<html>
<body>
<h3>
Test send to emailTest send to email
</h3>
</body>
</html>
`
	fmt.Println("send 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!")
	}

}

  技術分享

  GoLang的基礎包還是挺多的,也有github上的各種庫,使用很方便!

GoLang郵件發送Demo(繼上篇msmtp)