golang发送email SSL

email SSL

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

如果要发送加密带附件的邮件,邮件构造和加密处理加起来就显得代码有点杂。因此就自己封装了ssl部分。当然,邮件构造就不再重复造轮子了,还是使用这个库github.com/scorredoira/email

例子

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

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)
	}
}

转载于:https://my.oschina.net/u/3703365/blog/3024656

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值