go - 向多个收件人发送 smtp 电子邮件

标签 go

我正在使用 this发送 smtp。它适用于一个接收器,但我想要多个接收器。我尝试了以下方法:

func sendemail(body string) {  
    from := "smtpemail" 
    pass := "pass"
    to := "a@gmail.com,b@gmail.com"
    ....
}

我也试过:

to := "\"a@gmail.com\",\"b@gmail.com\""

和:

to := []string{"a@gmail.com","b@gmail.com"}

它们都不起作用。抱歉,太简单了,我刚开始使用 golang

最佳答案

来自 net/smtp 文档:

The msg parameter should be an RFC 822-style email with headers first, a blank line, and then the message body. The lines of msg should be CRLF terminated. The msg headers should usually include fields such as "From", "To", "Subject", and "Cc".

RFC 822要求 To: header 值是逗号分隔的列表。因此,虽然 to 变量应该保持为 []string 并作为其 to 参数传递给 smtp.SendMail , 邮件标题(在消息中)应该以逗号分隔的列表形式出现。试试下面看看它是否有效:

func send(body string) {
    // ...
    to := []string{"foo@mailinator.com", "bar@mailinator.com"}
    toHeader := strings.Join(to, ",")

    msg := "From: " + from + "\n" +
        "To: " + toHeader + "\n" + // use toHeader
        "Subject: Hello there\n\n" +
        body

    err := smtp.SendMail("smtp.gmail.com:587",
        smtp.PlainAuth("", from, pass, "smtp.gmail.com"),
        from, to, []byte(msg))

    // ...
}

关于go - 向多个收件人发送 smtp 电子邮件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46805579/

相关文章:

go - 如何实现一个channel和多个reader同时读取相同的数据?

go - 禁止在 golang 内联

postgresql - postgres中如何查询timestamptz并与go中的time.Time进行比较?

http - 从 Golang 中的网络/上下文中获取值

go - Go中根据依赖执行任务

go - 多部分文件字段不可读

c - 将 *C.uint8_t 转换为 []uint8 是否安全?

go - 为什么 Go 可以将 GC 暂停时间降低到 1 毫秒以下,而 JVM 却没有?

reflection - 在 Go 中获取接口(interface)的 reflect.Type 的更好方法

go - 如何在golang中为new relic(Golang New relic integration)创建通用或全局上下文?