<span>[GO]使用go-smtp发送邮件通知</span> - Go语言中文社区

<span>[GO]使用go-smtp发送邮件通知</span>


直接使用go-smtp包  ,为了防止乱码 , 主题subject进行了base64编码

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 + "rn" +
            "To: " + strings.Join(to, ",") + "rn" +
            "Subject: =?UTF-8?B?" + subjectBase + "?=rn" +
            "rn" +
            body + "rn")
    err := smtp.SendMail(server, auth, from, to, msg)
    if err != nil {
        return err
    }
    return nil
}

使用的时候 , 注意端口号要加上 ,端口号是25 

如果发送失败 , 可以检测一下服务器是否允许访问外网25端口 , 一般腾讯云或者阿里云可能会封闭了访问25端口 , 并且不允许使用本机搭建的smtp服务进行发送 , 防止垃圾邮件泛滥

可以使用telnet smtp.sina.cn 25   这样的命令检测是否允许访问25端口

现在邮箱都是使用授权码进行验证的 , 注意是和登录密码有区别的 , 授权码一般在设置里面开启 , 只能重置生成不能修改

SendSmtp("smtp.sina.cn:25","taoshihan1@sina.com","xxxxx",[]string{"xxxx@qq.com"},"你好","邮件")

 

版权声明:本文来源博客园,感谢博主原创文章,遵循 CC 4.0 by-sa 版权协议,转载请附上原文出处链接和本声明。
原文链接:https://www.cnblogs.com/taoshihan/p/14415283.html
站方申明:本站部分内容来自社区用户分享,若涉及侵权,请联系站方删除。
  • 发表于 2021-04-07 20:38:31
  • 阅读 ( 1264 )
  • 分类:Go

0 条评论

请先 登录 后评论

官方社群

GO教程

猜你喜欢