Golang multiple recipients with gomail.v2

血红的双手。 提交于 2019-12-21 14:52:57

问题


The only way that I've used to send emails via gomail.v2 is using the Send() function to each email in a for loop. But I need to show the other email addresses those the same email have been sent.

for _, recipient := range os.Args[3:] {
    mail.SetAddressHeader("From", "my@mail.com", "My Name")
    mail.SetHeader("To", recipient)
    mail.SetHeader("Subject", os.Args[2])
    mail.SetBody("text/html", os.Args[1])

    if err := dialer.DialAndSend(mail); err != nil {
        log.Printf("Could not send email to %q: %v", recipient, err)
        panic(err)
    }
}

I've found something like:

var emails bytes.Buffer

mail.SetAddressHeader("From", "my@mail.com.br", "My Name")
mail.SetHeader("Subject", os.Args[2])
mail.SetBody("text/html", os.Args[1])

for _, recipient := range os.Args[3:] {
    emails.WriteString(recipient + ",")
}

mail.SetHeader("To", emails.String())

if err := dialer.DialAndSend(mail); err != nil {
    log.Printf("Could not send email to %q: %v", buffer, err)
    panic(err)
}

It works by sending the email only to the first recipient in the String. And in the email manager like Gmail, Outlook or any other the other recipients addresses are showed, but not sent.

How should I do that properly?


回答1:


Give this a try?

recipients := os.Args[3:]
addresses := make([]string, len(recipients))
for i, recipient := range recipients {
    addresses[i] = mail.FormatAddress(recipient, "")
}

mail.SetHeader("To", addresses...)

if err := dialer.DialAndSend(mail); err != nil {
    log.Fatal(err)
}


来源:https://stackoverflow.com/questions/38066003/golang-multiple-recipients-with-gomail-v2

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!