Search code examples
phpemailpear

Syntax for sending a email header attachment


Possible Duplicate:
How to send emails with PHP using the PEAR Mail package with attachment

I want to send an email with PHP using a generated attachment (not a file on the server), I was curious about the syntax.

<?php
@require_once "Mail.php";

$from = "[email protected]>";
$to = "[email protected]>";
$subject = "Hi!";
$body = "Attached is the file\n\n";

$attachment = header( 'Content-Type: text/csv' );
$attachment = $attachment.header( 'Content-Disposition: attachment;filename=example.csv');
$attachment =  'transactionid,valid,fname,lname,email,studentid,status
            "654","1","First Name","Last Name","[email protected]","1000000"';
$body = $body.$attachment;


$headers = array ('From' => $from,
'To' => $to,
'Subject' => $subject);


$smtp = @Mail::factory('smtp', array('host' => $host,
                                    'port' => $port,
                                    'auth' => true,
                                    'username' => $mail_username,
                                    'password' => $mail_password));

$mail = @$smtp->send($to, $headers, $body);
if (@PEAR::isError($mail)) {
   echo("<p>" . $mail->getMessage() . "</p>");
} else {
   echo("<p>Message successfully sent!</p>");
}
?>

EDIT: Please note, i know there are many examples of attaching a file from the server in an email, but I am asking about attaching a generated csv file (that is NOT on the server) to an email.


Solution

  • Start with How to send emails with PHP using the PEAR Mail package with attachment

    Then replace the following:

    if ($mime->addAttachment($file,'application/pdf')){
    

    with

    $file =  'transactionid,valid,fname,lname,email,studentid,status
                "654","1","First Name","Last Name","[email protected]","1000000"';
    if ($mime->addAttachment($file,'text/csv', 'example.csv', false)){
    

    see documentation at http://pear.php.net/manual/en/package.mail.mail-mime.addattachment.php