Use github.com/emersion/go-smtp to send notification email content through smtp
After adding the content of the html code, it will be displayed as it is in some mailboxes, and it is not displayed as html. The reason is that the Content-Type is not added.
tools/smtp.go
package tools import ( "encoding/base64" "github.com/emersion/go-sasl" "github.com/emersion/go-smtp" "strings" ) func SendSmtp(server string, from string, password string, to []string, subject string, body string) error { auth := sasl.NewPlainClient("", from, password) subjectBase := base64.StdEncoding.EncodeToString([]byte(subject)) msg := strings.NewReader( "From: " + from + "\r\n" + "To: " + strings.Join(to, ",") + "\r\n" + "Subject: =?UTF-8?B?" + subjectBase + "?=\r\n" + "Content-Type: text/html; charset=UTF-8" + "\r\n\r\n" + body + "\r\n") err := smtp.SendMail(server, auth, from, to, msg) if err != nil { return err } return nil }
Test case
tools/smtp_test.go
package tools import "testing" func TestSendSmtp(t *testing.T) { body := "<a href=''>hello</a>" SendSmtp("smtp.sina.cn:25", "[email protected]", "xxxxx", []string{"[email protected]"}, "123456", body) }
The current code is located under the tools package, that is, under the tools/ directory. When executing the test case, use the following command
go test tools/smtp.go tools/smtp_test.go
There is a tag in the content, and the result can be displayed normally in a connected form
Also note that my subject is base64 encoded
Subject: =?UTF-8?B?” + subjectBase + “?=\r\n
So that the subject part is not garbled, =?UTF-8?B? This is a fixed format in the mail protocol, for example, the following content, the middle part is the content after base64
=?UTF-8?B?5LiA5Y+35bqXNOWRqOW5tOW6hu+8jDEwMDDkuIfku7bng63plIA=?=