golang sends email SSL

Keywords: github SSL

email SSL

You can find online tutorials on using golang to send and encrypt messages. Sending a simple text message is very simple, but when you need to send an attachment, you basically need to github.com/scorredoira/email.

If you want to send encrypted mail with attachments, the combination of mail construction and encryption processing is a little bit complicated. So I encapsulated the ssl part myself. Of course, the mail construction will not repeat the wheel building, but use this library github.com/scorredoira/email.

Example

aliyun mailbox is used for testing. The difference between encryption and non encryption is whether port 25 or port 465 is used.

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")
	//The sender's name and email shown here will not be affected by casual writing
	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)
	}
}

Posted by intermediate on Tue, 03 Dec 2019 03:10:32 -0800