25/05/2011

[PHP] Send mail with attachment using PEAR

If you use PEAR and want to send mails with attachments via PHP, you may find this helpful.

First, ensure you have installed PEAR’s Mail and Mail_mime packages. Then, you just need a function like this:

 

function send_mail($mail, $subject, $bodytxt, $bodyhtml, $attachment){
    require_once('Mail.php');
    require_once('Mail/mime.php');
    //mail parameters, this is the basic one
    $params = array("host"=>"YOUR_HOST");
    //creates smtp mail object
    $mail_sender = Mail::factory("smtp", $params);
    //creates mail headers
    $headers = array("From"=>"YOUR_ADDRESS", "To"=>$mail, "Subject"=>$subject);
    //creates attachment and body fields
    $crlf = "\n";
    $mime = new Mail_mime($crlf);
    $mime->setTXTBody($bodytxt);
    $mime->setHTMLBody($bodyhtml);
    $mime->addAttachment($attachment, "ATTACHMENT_TYPE");
    //never change these lines order
    $body = $mime->get();
    $headers = $mime->headers($headers);
    $error=$mail_sender->send($mail, $headers, $body);
    return $error;
}

 

where:

  • YOUR_HOST is your mail host, something like smtp.gmail.com
  • $mail is the recipient’s mail address
  • $bodytxt is the mail’s body in TXT format, do not use HTML markup here!
  • ATTACHMENT_TYPE is the attachment’s MIME type as per IANA’s specifications, something like image/jpeg
  • if you change the order of the last lines, the attach operation will not work

No comments:

Post a Comment

With great power comes great responsibility