Solved

Edit working php mail() to include pdf attachment

Posted on 2008-06-20
3
968 Views
Last Modified: 2008-06-20
I have the following code that currently sends an email based on session variables.  It works perfectly (I have changed the email addresses only to comply with EE rules of not showing your real email address).

I need to ammend the following code so that it always sends out an attachment called form.pdf (which is found in the root directory).  How do I edit my code to add an PDF attachment.
<?php session_start();?>
<?php
	$emailSubject = 'New Automated Email';
	$webMaster = 'someone@fakeemail.com';
	$firstnameEM = $_SESSION['svFirstName'];
	$lastnameEM = $_SESSION['svLastName'];
	$companyEM = $_SESSION['svCompany'];
	$phoneEM = $_SESSION['svphone'];
	$emailEM = $_SESSION['svemail'];
	$dateEM = date('l, F dS Y.');
	$body = <<<EOD
<br><hr><br>
First Name:  $firstnameEM <br><br>
Last Name:  $lastnameEM <br><br>
Company:  $companyEM <br><br>
Phone: $phoneEM <br><br>
Email:  $emailEM <br><br>
Date Completed Form:  $dateEM <br><br>
 
EOD;
 
	/*$headers = "From: $emailField\r\n";  */
	$headers = "From:  fake@email.com\r\n";
	
	$headers .= "Content-type: text/html\r\n";
	$success = mail($webMaster, $emailSubject, $body, $headers);
	$theResults = <<<EOD
 
EOD;
echo "$theResults";
	
 
?>

Open in new window

0
Comment
Question by:fastfind1
  • 2
3 Comments
 
LVL 48

Expert Comment

by:hernst42
ID: 21830168
use a mailer class for the attachment like
http://phpmailers.f.net
http://swiftmailer.sf.net

those classes are easy to use and code the mail correctly. Your code should be easy transformed to use those classes.
0
 
LVL 48

Expert Comment

by:hernst42
ID: 21830172
ups should be http://phpmailer.sf.net
0
 
LVL 14

Accepted Solution

by:
agriesser earned 500 total points
ID: 21830228
I was in the need for something similar some time ago and found a fully working "send_mail" implementation on php.net.

In your case, you'd only have to substitute the mail() invocation with send_mail().
I attached the code snippet, please give it a try.

The parameter "attachments" to the function shown below must be filled like this:

  $attachment=array(0);
  $attachment[0] = array( "file" => $filename, "content_type" => "application/pdf" );

Please note that the "content_type" option has to be changed acording to the type of attachment you want to send.

/*
 * send_mail() implementation (uses the PHP mail() function and allows for attaching
 * files
 * found on http://php.net
 */
function send_mail($to, $body, $subject, $fromaddress, $fromname, $attachments=false)
{
  $eol="\r\n";
  $mime_boundary=md5(time());
 
  # Common Headers
  $headers .= "From: ".$fromname."<".$fromaddress.">".$eol;
  $headers .= "Reply-To: ".$fromname."<".$fromaddress.">".$eol;
  $headers .= "Return-Path: ".$fromname."<".$fromaddress.">".$eol;    // these two to set reply address
  $headers .= "Message-ID: <".time()."-".$fromaddress.">".$eol;
  $headers .= "X-Mailer: PHP v".phpversion().$eol;          // These two to help avoid spam-filters
 
  # Boundry for marking the split & Multitype Headers
  $headers .= 'MIME-Version: 1.0'.$eol;
  $headers .= "Content-Type: multipart/mixed; boundary=\"".$mime_boundary."\"".$eol.$eol;
 
  # Open the first part of the mail
  $msg = "--".$mime_boundary.$eol;
 
  $htmlalt_mime_boundary = $mime_boundary."_htmlalt"; //we must define a different MIME boundary for this section
  # Setup for text OR html -
  $msg .= "Content-Type: multipart/alternative; boundary=\"".$htmlalt_mime_boundary."\"".$eol.$eol;
 
  # Text Version
  $msg .= "--".$htmlalt_mime_boundary.$eol;
  $msg .= "Content-Type: text/plain; charset=iso-8859-1".$eol;
  $msg .= "Content-Transfer-Encoding: 8bit".$eol.$eol;
  $msg .= strip_tags(str_replace(array("<br>", "<br />", "<br/>"), array("\n", "\n", "\n"), $body)) . $eol . $eol;
//  $msg .= strip_tags(str_replace("<br>", "\n", substr($body, (strpos($body, "<body>")+6)))).$eol.$eol;
 
  # HTML Version
  $msg .= "--".$htmlalt_mime_boundary.$eol;
  $msg .= "Content-Type: text/html; charset=iso-8859-1".$eol;
  $msg .= "Content-Transfer-Encoding: 8bit".$eol.$eol;
  $msg .= $body.$eol.$eol;
 
  //close the html/plain text alternate portion
  $msg .= "--".$htmlalt_mime_boundary."--".$eol.$eol;
 
  if ($attachments !== false)
  {
    for($i=0; $i < count($attachments); $i++)
    {
      if (is_file($attachments[$i]["file"]))
      {
        # File for Attachment
        $file_name = substr($attachments[$i]["file"], (strrpos($attachments[$i]["file"], "/")+1));
 
        $handle=fopen($attachments[$i]["file"], 'rb');
        $f_contents=fread($handle, filesize($attachments[$i]["file"]));
        $f_contents=chunk_split(base64_encode($f_contents));    //Encode The Data For Transition using base64_encode();
        $f_type=filetype($attachments[$i]["file"]);
        fclose($handle);
 
        # Attachment
        $msg .= "--".$mime_boundary.$eol;
        $msg .= "Content-Type: ".$attachments[$i]["content_type"]."; name=\"".$file_name."\"".$eol;  // sometimes i have to send MS Word, use 'msword' instead of 'pdf'
        $msg .= "Content-Transfer-Encoding: base64".$eol;
        $msg .= "Content-Description: ".$file_name.$eol;
        $msg .= "Content-Disposition: attachment; filename=\"".$file_name."\"".$eol.$eol; // !! This line needs TWO end of lines !! IMPORTANT !!
        $msg .= $f_contents.$eol.$eol;
      }
    }
  }
 
  # Finished
  $msg .= "--".$mime_boundary."--".$eol.$eol;  // finish with two eol's for better security. see Injection.
 
  # SEND THE EMAIL
  ini_set(sendmail_from,$fromaddress);  // the INI lines are to force the From Address to be used !
  $mail_sent = mail($to, $subject, $msg, $headers);
 
  ini_restore(sendmail_from);
 
  return $mail_sent;
}

Open in new window

0

Featured Post

Free Tool: Site Down Detector

Helpful to verify reports of your own downtime, or to double check a downed website you are trying to access.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

Title # Comments Views Activity
Help in good tutorials for PHP, HTML and CSS 6 40
Why will this INSERT statement not insert the date? 2 21
MVC - procedural PHP 10 36
Test if unique ID is in log file 5 22
A publishing tool, a Version Control System, or a Collaboration Platform! These can be some of the defining words for the two very famous web-hosting Git repositories: Bitbucket and Github. Git is widely used amongst the programmers and developers f…
Introduction This article is intended for those who are new to PHP error handling (https://www.experts-exchange.com/articles/11769/And-by-the-way-I-am-New-to-PHP.html).  It addresses one of the most common problems that plague beginning PHP develop…
Wufoo.com provides powerful tools for surveying targeted groups, and utilizing data from completed surveys to find trends, discover areas of demand or customer expectation, and make business decisions on products or services.
In this seventh video of the Xpdf series, we discuss and demonstrate the PDFfonts utility, which lists all the fonts used in a PDF file. It does this via a command line interface, making it suitable for use in programs, scripts, batch files — any pl…

861 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question