这是我通过gmail发送邮件的唯一方式。v2在for循环中对每个电子邮件使用Send()函数。但是我需要向其他电子邮件地址显示相同的电子邮件已发送。
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)
}
}
我找到了这样的东西:
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)
}
它的工作原理是只将电子邮件发送给字符串中的第一个收件人。而在Gmail、Outlook或其他电子邮件管理器中,其他收件人的地址会显示出来,但不会发送。
我该怎么做呢?
试一试?
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)
}
扩展上面的例子
type recipient struct {
Name string `json:"Name"`
Address string `json:"Address"`
}
func sendToMultipleRecipientsWithGomailV2(recipients []recipient, subject, message string) {
mail := gomail.NewMessage()
addresses := make([]string, len(recipients))
for i, recipient := range recipients {
addresses[i] = mail.FormatAddress(recipient.Address, recipient.Name)
}
mail.SetHeader("From", "myaddress@gmail.com")
mail.SetHeader("To", addresses...)
mail.SetHeader("Subject", subject)
mail.SetBody("text/html", message)
dialer := gomail.Dialer{Host: "smtp.gmail.com", Port: 587, Username:"myaddress@gmail.com", Password: "mypassword"}
if err := dialer.DialAndSend(mail); err != nil {
log.Fatal(err)
}
mail.Reset()
}
func main() {
recipients := []recipient{{
Name: "User 1",
Address: "user1@gmail.com",
},{
Name: "User 2",
Address: "user2@yandex.com",
}}
sendToMultipleRecipientsWithGomailV2(recipients, "my subject", "my message")
}
https://gist.github.com/kmilodenisglez/ab6518ca77172fdd646501b04bafb479