golang发邮件

u22b · · 1124 次点击 · · 开始浏览    
这是一个创建于 的文章,其中的信息可能已经有所发展或是发生改变。

由于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), nil
		case "Password:":
			return []byte(a.password), nil
		default:
			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"] = subject
	header["MIME-Version"] = "1.0"
	header["To"] = strings.Join(to, ",")
	header["From"] = from
	header["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()
}

 


有疑问加站长微信联系(非本文作者)

本文来自:开源中国博客

感谢作者:u22b

查看原文:golang发邮件

入群交流(和以上内容无关):加入Go大咖交流群,或添加微信:liuxiaoyan-s 备注:入群;或加QQ群:692541889

1124 次点击  
加入收藏 微博
暂无回复
添加一条新回复 (您需要 登录 后才能回复 没有账号 ?)
  • 请尽量让自己的回复能够对别人有帮助
  • 支持 Markdown 格式, **粗体**、~~删除线~~、`单行代码`
  • 支持 @ 本站用户;支持表情(输入 : 提示),见 Emoji cheat sheet
  • 图片支持拖拽、截图粘贴等方式上传