Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it fine to send email from another thread like this?

In a website, Some times sending an email take few seconds, so I need to send email from another thread, to don't wait until the email sent.

I found this answer on stackoverflow, Is it fine to do it this way, incase I will send just one email per request?

Or there is another standard way to do this?

like image 980
Amr Elgarhy Avatar asked Jun 29 '11 01:06

Amr Elgarhy


2 Answers

If possible, you should set up a local SMTP server that only listens on the loopback address (127.0.0.1) as this is exactly what mail queues are for. You can configure your SMTP server to relay through your real outbound mail server so that you don't run into problems with SPF treating your mail as spam.

This way your application can quickly queue the outbound mail and be on it's merry way and you can be reasonably sure that the message will eventually be delivered even in the event of heavy load, network issues, or even a crash.

like image 157
Josh Avatar answered Sep 28 '22 10:09

Josh


Spawning new threads from inside a request handler is potentially dangerous: if you get a spike in traffic, you might find yourself creating enough threads that makes the spike worse.

Better would be to hand off the mail sending to another process via a tool such as beanstalkd or other message queue or use a system-supplied mail command (my Linux system's mail(1) command can enqueue an email message in .07 seconds, adequate for moderate mail loads).

Gauge the amount of traffic you expect. If it is an internal tool that will only be used by a few dozen people, then spawning new threads is probably fine. If it is exposed to the big bad world, I'd recommend a more robust queuing mechanism that will have less impact on system resources.

like image 28
sarnold Avatar answered Sep 28 '22 10:09

sarnold