需要引入 smtp包 mail.go
package main
import (
"bytes"
"encoding/base64"
"fmt"
"io/ioutil"
"net/smtp"
"strings"
)
const const_smtp_server = "server-ip:port"
//const const_email_content_type = "Content-Type: text/plain; charset=UTF-8"
const const_email_content_type = "Content-Type: text/html; charset=UTF-8"
const const_boundary = "THIS_IS_THE_BOUNDARY_FOR_EMAIL_BY_LXB"
func SendEmail(sender string, receivers []string, subject string, content string, attach_files []string) error {
var buf bytes.Buffer
buf.WriteString("To: ")
buf.WriteString(strings.Join(receivers, ","))
buf.WriteString("\r\nFrom: ")
//nickname := strings.Split(sender,"@")[0]
//buf.WriteString(nickname)
buf.WriteString("<")
buf.WriteString(sender)
buf.WriteString(">")
buf.WriteString("\r\nSubject: ")
buf.WriteString(subject)
buf.WriteString("\r\nContent-Type: multipart/mixed; boundary=")
buf.WriteString(const_boundary)
buf.WriteString("\r\n--")
buf.WriteString(const_boundary)
buf.WriteString("\r\n")
buf.WriteString(const_email_content_type)
buf.WriteString("\r\n\r\n")
buf.WriteString(content)
buf.WriteString("\r\n\r\n--")
buf.WriteString(const_boundary)
buf.WriteString("\r\n")
for _, filepath := range attach_files {
// 第一个附件
filedepts := strings.Split(filepath, "/")
filename := filedepts[len(filedepts)-1]
buf.WriteString("Content-Type: application/octet-stream\r\n")
buf.WriteString("Content-Description: 附件\r\n")
buf.WriteString("Content-Transfer-Encoding: base64\r\n")
buf.WriteString("Content-Disposition: attachment; filename=\"" + filename + "\"\r\n\r\n")
//读取并编码文件内容
attaData, err := ioutil.ReadFile(filepath)
if err != nil {
print(err)
return err
}
b := make([]byte, base64.StdEncoding.EncodedLen(len(attaData)))
base64.StdEncoding.Encode(b, attaData)
buf.Write(b)
buf.WriteString(fmt.Sprintf("\r\n--%s\r\n", const_boundary))
}
fmt.Println(buf.String())
err := smtp.SendMail(const_smtp_server, nil, sender, receivers, buf.Bytes())
fmt.Println("send mail err:", err)
return err
}
main.go
package main
import (
//"flag"
//"fmt"
"os"
)
func main() {
//var task string
//flag.StringVar(&task, "t", "", "task id")
//flag.Parse()
//if task == "" {
// fmt.Println("task is required.")
// flag.Usage()
// os.Exit(2)
//}
testStr := os.Args[1]
cont := "<html><body><p align=\"center\">表: 1</p><table align=\"center\" border=\"1\" cellpadding=\"10\"><tr><td>任务ID</td><td>列1</td><td>列2</td><td>列3</td></tr> <tr><td>" + testStr + "</td><td>" + testStr + "</td><td>" + testStr + "</td><td>" + testStr + "</td></tr></table></body></html>"
sender := ""
rcvs := []string{}
sbj := "test email"
// cont := "This is content"
file := []string{}
SendEmail(sender, rcvs, sbj, cont, file)
}