golang发送email SSL

email SSL

网上能找到使用golang 发送邮件和发送加密邮件的教程。发送简单的文本邮件很是简单,但遇到须要发送附件时就基本要靠github.com/scorredoira/emailgit

若是要发送加密带附件的邮件,邮件构造和加密处理加起来就显得代码有点杂。所以就本身封装了ssl部分。固然,邮件构造就再也不重复造轮子了,仍是使用这个库github.com/scorredoira/emailgithub

例子

用的是aliyun邮箱作测试。加密和非加密的区别就在于使用的时25端口仍是465端口。golang

package emailagent_test

import (
	"net/mail"
	"testing"

	"github.com/scorredoira/email"
	"github.com/zhnxin/emailagent"
)

func generateEmail() (*email.Message, error) {
	// compose the message
	m := email.NewMessage("Hi", "this is the body")
	//这里显示的发件人名和邮箱,随便写不会影响邮件发送
	m.From = mail.Address{Name: "nic name", Address: "username@aliyun.com"}
	m.To = []string{"target@aliyun.com"}

	// add attachments
	if err := m.Attach("agent.go"); err != nil {
		return nil, err
	}

	// add headers
	m.AddHeader("X-CUSTOMER-id", "xxxxx")
	return m, nil
}

func TestSSL(t *testing.T) {
	msg, err := generateEmail()
	if err != nil {
		t.Fatal(err)
	}
	agent := emailagent.New("exmaple@aliyun.com", "password", "smtp.aliyun.com", 465, true)
	//agent := emailagent.NewWithIdentify("identify","exmaple@aliyun.com", "password", "smtp.aliyun.com", 465, true)
	if err = agent.SendEmail(msg); err != nil {
		t.Fatal(err)
	}

}

func TestPlainAuth(t *testing.T) {
	msg, err := generateEmail()
	if err != nil {
		t.Fatal(err)
	}
	agent := emailagent.New("exmaple@aliyun.com", "password", "smtp.aliyun.com", 25, false)
	//agent := emailagent.NewWithIdentify("identify","exmaple@aliyun.com", "password", "smtp.aliyun.com", 25, false)
	if err = agent.SendEmail(msg); err != nil {
		t.Fatal(err)
	}
}
相关文章
相关标签/搜索