Search code examples
phpemailphpmailer

PHP Mail()/PHPMailer vs. Transactional Email Service vs. SMTP


A common, but fairly unpredictable issue that comes up with my web clients is getting emails to send from their website without being caught up by email spam blockers. The most reliable solution I've found is to use SMTP credentials to send the email via the client's email server. However, that doesn't work if the client is using Office 365, but hosting their website on Google Cloud/Compute Engine because the Office 365 email ports are blocked. So then I'm left with 2 options: a transactional email relay (like Mailgun or Sendgrid) OR a PHP email tool (PHPMailer or mail()).

The former is very reliable, but requires the client to setup an account, pay a subscription fee, and create a new SPF record. The setup and pros/cons of the latter is way less clear to me, but seems easier. PHP developers definitely seem to prefer mail() over PHPMailer, but I've never found a complete list of reasons for this preference (if you are not using PHPMailer to send mail via SMTP/IMAP). What are the pros and cons to using mail() over PHPMailer or any other PHP email library?

I've also never fully understand the setup necessary to use one of these tools reliably. If you are using mail()/PHPMailer, do you have to create an SPF record? If so, how do you figure out the domain name or IP address of the server sending the email so you can create the SPF record (WP Engine, for example, has no instructions on creating an SPF record)?


Solution

  • mail and PHPMailer are both just solutions to create a mail and "drop it on the wire". mail is a very low-level bare bones API to the system's sendmail or compatible alternative configured in php.ini. Using mail you will have to get the mail format itself exactly right, you're basically passing the raw email headers and body to mail(), which passes it to whatever sendmail compatible MTA is set up on the system, which will attempt to deliver it according to its configuration.

    PHPMailer is just a wrapper around that which takes some of the burden of worrying about email header/body formatting off you, and adds the facility to directly talk to SMTP servers instead of requiring a local MTA to be set up.

    Fundamentally neither solution does anything vis-à-vis spam for you. Spam filters look at the sending server and domain/DNS configuration (apart from the message content itself), neither of which is influenced by the use of mail/PHPMailer. You'll still have to set up the MTA/domain/DNS records properly to legitimise whatever server will end up sending the email.