邮件的一般格式
1 | From:chimps@example.com |
使用阿里云企业邮注意事项
如果你的域名为example.com
在阿里的域名那里都配好之后,发邮件的配置应该如下:1
2
3
4HOST: smtp.example.com
HOST_ADDR: smtp.example.com:25
USER: 该企业邮箱所创建的子邮箱
PASSWORD:user的password
代码:
主要是使用net/smtp包的SendMail
方法1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50package main
import (
"fmt"
"net/smtp"
"strings"
)
const (
HOST = "smtp.example.com"
ADDR = "smtp.example.com:25"
USER = "chimps@example.com"
PASSWORD = "xxx"
)
func main() {
to := "to1@163.com;to1@163.com"
subject := "TEST EMAIL"
email_type := "html"
message := "<h1>hello go</h1>"
if err := SendEmail(to, subject, email_type, message); err != nil {
fmt.Println("发送失败, reason:" + err.Error())
}
}
func SendEmail(to string, subject string, email_type string, message string) (err error) {
var content_type string
switch email_type {
case "html":
content_type = "Content-Type: text/html; chatset=UTF-8"
case "text":
content_type = "Content-Type: text/plain; chatset=UTF-8"
}
auth := smtp.PlainAuth("", USER, PASSWORD, HOST)
send_to := strings.Split(to, ";")
for _, v := range send_to {
var msg []string
msg = append(msg, "From:"+USER, "To:"+v, "Subject:"+subject, content_type, "\r\n"+message)
msg_string := strings.Join(msg, "\r\n")
fmt.Println(msg_string)
if err = smtp.SendMail(ADDR, auth, USER, []string{v}, []byte(msg_string)); err != nil {
fmt.Println("send fail , reason: " + err.Error())
return
} else {
fmt.Println("send ok :" + v)
}
}
return
}
改进
一般情况下,发邮件时间比较耗时的事情,一般走异步处理