dqf67993 2016-06-28 02:12
浏览 417
已采纳

Golang使用gomail.v2的多个收件人

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条回答 默认 最新

  • drfcaw7460 2016-06-28 06:52
    关注

    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)
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 stm32代码移植没反应
  • ¥15 matlab基于pde算法图像修复,为什么只能对示例图像有效
  • ¥100 连续两帧图像高速减法
  • ¥15 组策略中的计算机配置策略无法下发
  • ¥15 如何绘制动力学系统的相图
  • ¥15 对接wps接口实现获取元数据
  • ¥20 给自己本科IT专业毕业的妹m找个实习工作
  • ¥15 用友U8:向一个无法连接的网络尝试了一个套接字操作,如何解决?
  • ¥30 我的代码按理说完成了模型的搭建、训练、验证测试等工作(标签-网络|关键词-变化检测)
  • ¥50 mac mini外接显示器 画质字体模糊