Snippet: sending mail with PHP

      No Comments on Snippet: sending mail with PHP

In this snippet I will show you how to send mail with the PHP PEAR mail class. On most systems this is installed by default. It will allow you to send your message, encrypted to a server. First off, we start with some basic declarations:

<?php
 require_once "Mail.php";

 $from = "WiZZarD ";
 $to = "Somebody ";
 $subject = "Hello there";
 $body = "Hello, How are you?";
 $host = "ssl://mail.tovernaar.nl";
 $port = "587";
 $username = "smtp_username";
 $password = "smtp_password";

These are all pretty straightforward. In this case we set up a connection to a mailserver using SSL, on port 587. Also we define some addresses to be used as from- and to- address in the final mail. Last thing we set up is a username and password, since my mailserver requires this. For more options and how to use them you can use the documentation page of this package, there should be sufficient information there.

    $headers = array ('From' => $from,
        'To' => $to,
        'Subject' => $subject);
    $smtp = Mail::factory('smtp',
        array ('host' => $host,
            'port' => $port,
            'auth' => true,
            'username' => $username,
            'password' => $password));

Here we do two things: First we set up the headers that need to be used by our mail when its being sent. Right now we stick to a bare minimum, so we just create a from, to and subject field. Feel free to add any required headers (i.e. a X-Mailer: header). After this is done, its time to set up a instance of Mail::factory. We feed it the variables we set earlier in the script.

    $mail = $smtp->send($to, $headers, $body);
    if (PEAR::isError($mail)) 
    {
        echo("

" . $mail->getMessage() . "

"); } else { echo("

Message was sent successfully.

"); } ?>

This last bit wraps it all up. We try to send out our e-mail. After that’s done, we check to see if the message actually got out, or if we got an error in response.

That’s all!