dangerChihuahua007
dangerChihuahua007

Reputation: 20875

What are the differences between sending email in PHP with mail, sendmail, and smtp?

I have heard that all of these methods are valid ways to send email in PHP.

What are their advantages and disadvantages?

Upvotes: 10

Views: 8157

Answers (1)

staticsan
staticsan

Reputation: 30555

The three options aren't quite in the same league, presuming the first means the mail() function.

Using the mail() function usually calls the local mail injector, commonly a binary program supplied by the MTA actually called "sendmail". The problem with mail() is that it is a non-straightforward interface with a number of gotchas and traps which are not well documented. This is because it mimics (IMO badly) the call to the Unix CLI mail command.

It is possible to call the local injector yourself, but this documented even less well. You may as well call mail(), anyway, since this is what the latter does.

Using SMTP comes with its own set of problems, however. If there is a local MTA that accepts and forwards mail, then it is not a bad solution. If there isn't, you will have to figure out which host you should be sending to. This will either be figuring out which external host should be doing your forwarding, or doing the actual MX lookup yourself. You will also need to know the SMTP protocol and be able to handle refusals for any reason. And you have to decide how you handle the need to re-try the send.

Doing the SMTP yourself also has the problem of not de-coupling the email sending from the reason the email is being sent. If there is a delay, or a problem, you have a page that will appear to be stuck. Using the local injector hands the former problem to the MTA; all you've done is queue the email for delivery. But then you don't have to worry about things like re-sending.

These three solutions also do not help you assemble your message, such as rich content, alternate content and attachments. You have to do all that (and add the correct headers!) yourself.

The normal recommendation is to locate a library that does all that for you, is robust and has a decent API. The usual one is PHP Mailer. The advantages of this library is that it also does all the message assembly, as well as figuring out how to do the delivery. But it's main win is that it Just Send The Message, trying mail() and local SMTP and even remote SMTP if it must. All transparantly.

Upvotes: 13

Related Questions