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: ” + “\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 := “eee@eee.com”
password := “111111111111111”
host := “smtp.eee.com:25”
to := “eeee@eee.com”

subject := “使用Golang发送邮件”

body := `

“Test send to email”



`
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!”)
}

}

/*
遇到的问题:

1、body := “,这里用的是反单引号,而非单引号;

2、err != nil,golang的nil在概念上和其它语言的null、None、nil、NULL一样,都指代零值或空值。nil是预先说明的标识符,也即通常意义上的关键字。在golang中,nil只能赋值给指针、channel、func、interface、map或slice类型的变量。如果未遵循这个规则,则会引发panic。对此官方有明确的说明:http://pkg.golang.org/pkg/builtin/#Type

3、参数auth,auth := smtp.PlainAuth(“”, user, password, hp[0])

4、强制类型转换,msg := []byte(“To: ” + to + “\r\nFrom: ” + user + “>\r\nSubject: ” + “\r\n” + content_type + “\r\n\r\n” + body)

5、多个邮箱:send_to := strings.Split(to, “;”)*/

发表评论

您的电子邮箱地址不会被公开。 必填项已用*标注

Captcha Code