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