簡體   English   中英

Go:連接到SMTP服務器並在一個連接中發送多個電子郵件?

[英]Go: Connect to SMTP server and send multiple emails in one connection?

我正在編寫一個程序包,我打算與本地SMTP服務器建立一個初始連接,然后等待一個通道,該通道將填充電子郵件,以便在需要發送時發送。

查看net / http似乎期望每次發送電子郵件時都應撥打SMTP服務器並進行身份驗證。 當然,我可以撥打和驗證一次,保持連接打開,只是添加新的電子郵件?

查看smtp.SendMail的源smtp.SendMail ,我看不出如何做到這一點,因為似乎沒有辦法回收*Clienthttp//golang.org/src/net/smtp/smtp 。去S = 7610:7688#L263

*Client有一個Reset函數,但其​​描述如下:

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

我不想中止當前的郵件交易,我希望有多個郵件交易。

如何保持與SMTP服務器的連接打開並在該連接上發送多封電子郵件?

你是正確的, smtp.SendMail沒有提供重用連接的方法。

如果您想要這種精細控制,則應使用持久客戶端連接。 這需要了解更多關於smtp命令和協議的信息。

  1. 使用smtp.Dial打開連接並創建客戶端對象。
  2. 根據需要使用client.Helloclient.Authclient.StartTLS
  3. 使用RcptMailData作為適當的發送消息。
  4. client.Quit()和關閉連接。

Gomail v2現在支持在一個連接中發送多封電子郵件。 文檔中的守護進程示例似乎與您的用例相符:

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)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM