這是一個建立於 的文章,其中的資訊可能已經有所發展或是發生改變。
由於go預設tls.Config{ServerName: host, InsecureSkipVerify: false},
func TestHtmlEmail(t *testing.T) {opt := &EmailOptions{User: "",Password: "",To: []string{""},From: "",Addr: "smtp.xxx.com:25",}auth := NewLoginAuth(opt.User, opt.Password)pic, err := ioutil.ReadFile(`C:\Pictures\example.png`)if err != nil {t.Log(err)}dest := make([]byte, base64.StdEncoding.EncodedLen(len(pic)))base64.StdEncoding.Encode(dest, pic)buf := bytes.Buffer{}fmt.Fprint(&buf, "<html><head></head><body><p>Test png</p><p><img src=\"data:image/png;base64,")_, err = buf.Write(dest)fmt.Fprint(&buf, "\"></p><body></html>")err = sendMail(opt.Addr, auth, opt.From, opt.To, buf.Bytes(), "subject")if err != nil {t.Log(err)}}type LoginAuth struct {username, password string}func NewLoginAuth(username, password string) smtp.Auth {return &LoginAuth{username, password}}func (a *LoginAuth) Start(server *smtp.ServerInfo) (string, []byte, error) {return "LOGIN", []byte{}, nil}func (a *LoginAuth) Next(fromServer []byte, more bool) ([]byte, error) {if more {switch string(fromServer) {case "Username:":return []byte(a.username), nilcase "Password:":return []byte(a.password), nildefault:return nil, errors.New("Unknown fromServer")}}return nil, nil}func sendMail(addr string, auth smtp.Auth, from string, to []string, msg []byte, subject string) error {conn, err := smtp.Dial(addr)host, _, _ := net.SplitHostPort(addr)if err != nil {return err}defer conn.Close()if ok, _ := conn.Extension("STARTTLS"); ok {config := &tls.Config{ServerName: host, InsecureSkipVerify: true}if err = conn.StartTLS(config); err != nil {return err}}if auth != nil {if ok, _ := conn.Extension("AUTH"); ok {if err = conn.Auth(auth); err != nil {return err}}}if err = conn.Mail(from); err != nil {return err}for _, addr := range to {if err = conn.Rcpt(addr); err != nil {return err}}w, err := conn.Data()if err != nil {return err}header := make(map[string]string)header["Subject"] = subjectheader["MIME-Version"] = "1.0"header["To"] = strings.Join(to, ",")header["From"] = fromheader["Content-Type"] = "text/HTML; charset=\"utf-8\""header["Content-Transfer-Encoding"] = "base64"message := ""for k, v := range header {message += fmt.Sprintf("%s: %s\r\n", k, v)}message += "\r\n" + base64.StdEncoding.EncodeToString(msg)_, err = w.Write([]byte(message))if err != nil {return err}err = w.Close()if err != nil {return err}return conn.Quit()}