sweet idleness

Sending Email from a PHP script

November 12, 2008

This solution requires PEAR and PEAR packages Mail and Mail_Mime.

      1 <?php      2 include(’Mail.php’);      3 include(’Mail/mime.php’);
      4
      5 $mime = new Mail_mime();
      6 $mailer =& Mail::factory(’smtp’);
      7
      8 $html = ‘<html><body> Whoa there! <img src=”7tennis.jpg”></body></html>’;
      9 $text = ‘Whoa there!’;
     10
     11 $to=’recipient@example.com’;
     12 $hdrs = array(
     13    ‘From’ => ’sender@example.com’,
     14    ‘To’ => $to,
     15    ‘Subject’ => ‘Test message’
     16 );
     17
     18 $mime->setHTMLBody($html);
     19 $mime->setTxtBody($text);
     20 $mime->addHTMLImage(”./sampleimage.jpg”);
     21 $mime->addAttachment(”./sampleimage.jpg”);
     22
     23 $body = $mime->get();
     24 $hdrs = $mime->headers($hdrs);
     25
     26 $mailer->send($to, $hdrs, $body);
     27 if (PEAR::isError($mailer)) {
     28    echo(”<p>” . $mailer->getMessage() . “</p>”);
     29 } else {
     30    echo(”<p>Message successfully sent!</p>”);
     31 }
     32 ?>

Line 6 creates an instance of the mailer class. The first parameter, the name of the backend can be set to “mail”, “smtp”, or “sendmail”.  The optional second parameter is for backend specific parameters.  Here’s a sample mailer instance using smtp authentication:

$smtp = Mail::factory(’smtp’, array (’host’ => $host,’auth’ => true,’username’ => $username,’password’ => $password));

To set CC and BCC, add the fields ‘Cc’ and ‘Bcc’ to $hdrs (Line 12  - 16):

$hdrs = array(
   ‘From’ => $from,
   ‘To’ =>   ‘recipient1@example.com, ‘,
   ‘Bcc’=> ‘email1@example.com, email2@example.com’,
   ‘Cc’=> ‘email3@example.com, email4@example.com’,
   ‘Subject’ => ‘Test message’
);

Recipients (To, Bcc, and Cc) can contain comma delimited list of emails.

The order of the instructions line 23 and 24 cannot be reversed. I found this out the hard way :)

     23 $body = $mime->get();
     24 $hdrs = $mime->headers($hdrs);

You have to call the method get() before headers($additional_hdrs). If  you don’t do so, the headers will not be correct.  

Posted by george at 5:20 pm | permalink

Previous Comments

FYI, Mail and Mail_mime version installed on my machine:
pear/Mail_Mime 1.3.1
pear/Mail 1.1.3

Posted by george at November 12, 2008, 7:14 pm

Some time ago, I needed to buy a car for my organization but I didn’t earn enough money and could not purchase something. Thank heaven my father proposed to get the loans from reliable creditors. Thus, I did that and used to be happy with my credit loan.

Posted by GrayBERTA33 at February 4, 2011, 5:31 am