Go:连接到SMTP服务器并在一个连接中发送多个电子邮件?

时间:2015-05-26 05:35:09

标签: email go smtp smtp-auth

我正在编写一个程序包,我打算与本地SMTP服务器建立一个初始连接,然后等待一个通道,该通道将填充电子邮件,以便在需要发送时发送。

查看net / http似乎期望每次发送电子邮件时都应拨打SMTP服务器并进行身份验证。当然,我可以拨打和验证一次,保持连接打开,只需添加新电子邮件即可?

查看smtp.SendMail的来源,我不知道如何做到这一点,因为似乎没有办法回收*Clienthttp://golang.org/src/net/smtp/smtp.go?s=7610:7688#L263

Reset有一个*Client函数,但其​​描述是:

 Reset sends the RSET command to the server, aborting the current mail transaction.

我不想中止当前的邮件交易,我希望有多个邮件交易。

如何保持与SMTP服务器的连接打开并在该连接上发送多封电子邮件?

2 个答案:

答案 0 :(得分:5)

你是正确的smtp.SendMail没有提供重用连接的方法。

如果您想要这种精细控制,则应使用持久客户端连接。这需要了解更多关于smtp命令和协议的信息。

  1. 使用smtp.Dial打开连接并创建客户端对象。
  2. 视情况使用client.Helloclient.Authclient.StartTLS
  3. 使用RcptMailData作为发送消息。
  4. client.Quit()并在完成任务后紧密联系。

答案 1 :(得分:2)

Gomail v2现在支持在一个连接中发送多封电子邮件。文档中的Daemon example似乎与您的用例相符:

ch := make(chan *gomail.Message)

go func() {
    d := gomail.NewPlainDialer("smtp.example.com", 587, "user", "123456")

    var s gomail.SendCloser
    var err error
    open := false
    for {
        select {
        case m, ok := <-ch:
            if !ok {
                return
            }
            if !open {
                if s, err = d.Dial(); err != nil {
                    panic(err)
                }
                open = true
            }
            if err := gomail.Send(s, m); err != nil {
                log.Print(err)
            }
        // Close the connection to the SMTP server if no email was sent in
        // the last 30 seconds.
        case <-time.After(30 * time.Second):
            if open {
                if err := s.Close(); err != nil {
                    panic(err)
                }
                open = false
            }
        }
    }
}()

// Use the channel in your program to send emails.

// Close the channel to stop the mail daemon.
close(ch)