Easier mail sending with PEAR::Mail

Although mail() sends email well enough, I want to introduce you to the much more advanced PEAR::Mail class. This does much the same as using mail(), with the exception that it has slightly smarter address and header handling - rather than taking a string of "header: value\r\nheader: value", it takes an array where the keys are the header names and the values are the header values. Similarly, you can send the same email to lots of people by passing an array of email addresses rather than just one.

Using PEAR::Mail we can write a simple email script like this:

    $mail = Mail::factory("mail");

    $headers = array("From"=>"me@example.com", "Subject"=>"Test Mail");
    $body = "This is a test!";
    $mail->send("best@friend.com", $headers, $body);

The Mail.php file is the PEAR::Mail script, so it needs to be included before any PEAR::Mail functions are used. Line two creates a default instance of PEAR::Mail - the parameter "mail" is passed in so that PEAR::Mail will use PHP's mail() function to send the email. If you pass in "sendmail", it will send direct via the sendmail program (Unix only).

Alternatively you can pass in "smtp", which lets you send a second parameter that is an array containing five keys: host, port, auth, username, and password. Each of these should have values assigned to them: host should be the SMTP server to connect to, port should be the port number (defaults to 25), auth should be true if you want to authenticate with username and password (defaults to false), and username and password should be set if you want to authenticate. Unless you really want the extra power of connecting directly by hand, it's best to stick with "mail"!

Line three sets up the headers to use in the email. Note that this time we need to provide the subject inside a header as well as the sender information. Here you can use all the techniques we have looked at so far, for example the From element could have the value "Me <me@example.com>" to have the email addresses pretty-printed.

Line four sets the body text to use in the email, which is standard enough. Line five is where the email is actually sent, and you will see that send() takes three parameters: address to send to, headers to use, and the content of the email. As mentioned already, the first parameter can either be a string with each person's name separated by a comma, or it can be an array.


Want to learn PHP 7?

Hacking with PHP has been fully updated for PHP 7, and is now available as a downloadable PDF. Get over 1200 pages of hands-on PHP learning today!

If this was helpful, please take a moment to tell others about Hacking with PHP by tweeting about it!

Next chapter: Sending mixed-type messages with PEAR::Mail_Mime >>

Previous chapter: MIME types

Jump to:


Home: Table of Contents

Copyright ©2015 Paul Hudson. Follow me: @twostraws.