Help - Search - Members - Calendar
Full Version: send Email with attachment using PHP
ieXbeta Board > Tech > Developer Center
jazzsinbad
CODE
<?php
  $sFROM   = $sCC     = $sTO  =   $sBCC   = "example@email.com";
  $sSUB    = "Email with attachment";         // Subject

// use the MD5 algorithm to generate a unique random hash
$random_hash = md5(date('r', time()));
$headers = "From: $sFROM\r\nReply-To: $sTO";
$headers .= "\r\nContent-Type: multipart/mixed; boundary=\"PHP-mixed-".$random_hash."\"";
$attachFile = "C:\mail\test.xls";

$attachment = chunk_split(base64_encode(file_get_contents($attachFile)));

//define the body of the message.
ob_start(); //Turn on output buffering
?>
--PHP-mixed-<?php echo $random_hash; ?>
Content-Type: multipart/alternative; boundary="PHP-alt-<?php echo $random_hash; ?>"

--PHP-alt-<?php echo $random_hash; ?>
Content-Type: text/html; charset="iso-8859-1"
Content-Transfer-Encoding: 7bit

<h2>Hello World!</h2>
<p>Testing message here ...</p>

--PHP-alt-<?php echo $random_hash; ?>--

--PHP-mixed-$random_hash
Content-Type: application/vnd.ms-excel; name=".basename($attachFile)
Content-Transfer-Encoding: base64
Content-Disposition: attachment

<?php echo $attachment; ?>
--PHP-mixed-<?php echo $random_hash"; ?>--

<?php    

//copy current buffer contents into $message variable and delete current output buffer
$message = ob_get_clean();
//send the email
$mail_sent = mail( $sTO, $sSUB, $message, $headers );
//if the message is sent successfully print "Mail sent". Otherwise print "Mail failed"
echo $mail_sent ? "Mail sent\r\n" : "Mail failed\r\n";

?>
Phonics Monkey
Is this a statement, or a question ... WTF are you after?!?

What kind of server is this running on?

Which way are you trying to tie into what kind of mail server SNMP/MAPI??

...Details help man...


Damn.
jazzsinbad
Oh, I'm sorry, I just want to shows how to write a simple php code to send a email with attachment file. It is using SMTP to sending it, so your php.ini setting must be set before can use this code. The type of attachement file can be anything just change the Content-type to other application/*other type*. But, the only weakness is it cannot include Bcc.
This is a "lo-fi" version of our main content. To view the full version with more information, formatting and images, please click here.
Invision Power Board © 2001-2008 Invision Power Services, Inc.