![](/img/trans.png)
[英]Is it OK to connect smtp server once and send many emails in a long period?
[英]Go: Connect to SMTP server and send multiple emails in one connection?
我正在編寫一個程序包,我打算與本地SMTP服務器建立一個初始連接,然后等待一個通道,該通道將填充電子郵件,以便在需要發送時發送。
查看net / http似乎期望每次發送電子郵件時都應撥打SMTP服務器並進行身份驗證。 當然,我可以撥打和驗證一次,保持連接打開,只是添加新的電子郵件?
查看smtp.SendMail
的源smtp.SendMail
,我看不出如何做到這一點,因為似乎沒有辦法回收*Client
: http : //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命令和協議的信息。
smtp.Dial
打開連接並創建客戶端對象。 client.Hello
, client.Auth
和client.StartTLS
。 Rcpt
, Mail
, Data
作為適當的發送消息。 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.