go-gomail / gomail

The best way to send emails in Go.
MIT License
4.33k stars 573 forks source link

Is there way to utilize same sender variable in goroutine? #45

Closed kashpatel closed 8 years ago

kashpatel commented 8 years ago

Hi there,

I am trying to use following sender variable in multiple goroutine to send emails, But it does not work. (I pass same initialized sender variable in function which gets executed in goroutines pool)

It returns gomail: could not send email 1: EOF error and does not proceed

mailer := gomail.NewPlainDialer(smtpServer, smtpPort, smtpUser, smtpPassword) sender, err := mailer.Dial() if err != nil { log.Println("Mailer Could not be instantiated. Error: ", err) }

I already tried DialAndSend() in goroutines pool and it works. But I do not want to connect to server for each email as it gives multiple login attempts error from gmail server after sending more than 50 emails at same time.

Any hep would be appreciated. Thanks

alexcesaro commented 8 years ago

Your variable sender is an smtp.Client. It represents a connection to the SMTP server. When you use it concurrently it writes multiple emails at the same time on the same socket so the emails get mixed and the SMTP does not understand anything.

You should do something like in the daemon example of the documentation: you launch a goroutine that listens to a channel. When you want to send an email in your app you just put the message in the channel and the daemon goroutine will send the email in the background.

The message channel should be buffered so you can have a message queue. And if having only one daemon sending emails is not fast enough and the message queue always gets full you can launch multiple daemons listening to the queue. The emails will be sent faster and it will prevent the queue from getting full.

kashpatel commented 8 years ago

Thank you!