[Go]解决go-smtp发送内容乱码和发送html邮件不解析
2023-02-18 15:41:10 时间
使用github.com/emersion/go-smtp , 通过smtp发送通知邮件内容
加上html代码的内容后 , 在一些邮箱里会被原样展示 , 并没有展示成html , 原因是没有加Content-Type , 加上之后就可以了
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 }
测试用例
tools/smtp_test.go
package tools import "testing" func TestSendSmtp(t *testing.T) { body := "<a href=''>hello</a>" SendSmtp("smtp.sina.cn:25", "taoshihan1@sina.com", "xxxxx", []string{"taoshihan1@sina.com"}, "123456", body) }
当前代码位于tools包下面 , 也就是tools/目录下 , 执行测试用例时 , 使用如下的命令
go test tools/smtp.go tools/smtp_test.go
内容里是a标签 , 结果可以正常的展示成连接的形式
还要注意我的subject是经过base64编码的
Subject: =?UTF-8?B?" + subjectBase + "?=\r\n
这样才能主题部分不乱码 , =?UTF-8?B?这是邮件协议里固定的格式 , 例如下面的内容 , 中间部分是base64后的内容
=?UTF-8?B?5LiA5Y+35bqXNOWRqOW5tOW6hu+8jDEwMDDkuIfku7bng63plIA=?=
相关文章
- Zebra BI 重大发布,与 Excel,PPT,Power BI 统一集成,一大壮举
- 如何在企业推广 Power BI,内建学习平台
- Power BI 原厂官方图标大全
- C++矩阵库Armadillo在Visual Studio中的配置
- PHP使用curl上传文件到远程服务器接口
- VBA: 自动定时关闭消息框
- VBA:基于指定列删除重复行
- VBA: 单元格区域基于指定列重新排序(3)
- VBA: 提高 VBA 宏性能的 8 个技巧
- VBA: 批量重命名文件夹和文件名称
- Power BI: 日期表的创建
- Go语言中常见100问题-#1 Unintended variable shadowing
- Go语言中常见100问题-#2 Unnecessary nested code
- Go语言中常见100问题-#3 Misusing init functions
- Go语言中常见100问题-#4 Overusing getters and setters
- Go语言中常见100问题-#5 Interface pollution
- Go语言中常见100问题-#6 Interface on the producer side
- Go语言中常见100问题-#7 Returning interfaces
- Go语言中常见100问题-#8 any says nothing
- Go语言中常见100问题-#9 Being confused about when to use generics