天天看點

Golang使用SMTP發送郵件

使用SMTP發送郵件

import (
	"fmt"
	"net/smtp"
)

const (
	// 郵件伺服器位址
	SMTP_MAIL_HOST	= "smtp.126.com"
	// 端口
	SMTP_MAIL_PORT	= "25"
	// 發送郵件使用者賬号
	SMTP_MAIL_USER	= "[email protected]"
	// 授權密碼
	SMTP_MAIL_PWD	= ""
	// 發送郵件昵稱
	SMTP_MAIL_NICKNAME	= "SMTPMail"
)

func SendMail(address []string, subject string, body string) (err error) {
	// 通常身份應該是空字元串,填充使用者名.
	auth := smtp.PlainAuth("", SMTP_MAIL_USER, SMTP_MAIL_PWD, SMTP_MAIL_HOST)
	contentType := "Content-Type: text/html; charset=UTF-8"
	for _, v := range address {
		s := fmt.Sprintf("To:%s\r\nFrom:%s<%s>\r\nSubject:%s\r\n%s\r\n\r\n%s",
			v, SMTP_MAIL_NICKNAME, SMTP_MAIL_USER, subject, contentType, body)
		msg := []byte(s)
		addr := fmt.Sprintf("%s:%s", SMTP_MAIL_HOST, SMTP_MAIL_PORT)
		err = smtp.SendMail(addr, auth, SMTP_MAIL_USER, []string{v}, msg)
		if err != nil {
			return err
		}
	}
	return
}

           

#發送郵件測試

func main() {
	address := []string{"[email protected]", "[email protected]"}
	fmt.Println(mail.SendMail(address, "golang smtp mail", "golang smtp mail"))
}
           

郵箱如下

Golang使用SMTP發送郵件
Golang使用SMTP發送郵件