Copied to clipboard
 
 
 
 

Send an Email Attachment with PHP

To send email attachments you need to make use of MIME (Multipurpose Internet Mail Extensions) - a mechanism that allows email to go beyond a basic, limited character set. MIME has many uses but for the purposes of this tutorial we will send a multipart/mixed MIME email; this means we can send a text email and attach any file to it.

As a courtesy, you can copy the code to your clipboard by clicking inside the code box. Or you can download the file: gzip zip uncompressed.

Code Block 1: Set Basic Header Details
  1. <?php
  2.  
  3. $to = isset($name) ? sprintf('%s <%s>',$name,$email) : $email;
  4. $from = 'Automated Attachement <web@gjtech.net>';
  5. $subject = 'Here is your attachment';
  6.  
  7. ?>

 

Code Block 1: Basic header details are self explanitory. Specify who the email is being sent to ($to), who the mail is from ($from) and what the subject is ($subject).

Code Block 2: Create Boundary Details
  1. <?php
  2.  
  3. $hash = array();
  4. $hash[] = sprintf('%s-%s=:%s',time(),md5(time()),rand(0,9));
  5. $hash[] = sprintf('%s-%s=:%s',time(),md5(time()),rand(10000,99999));
  6.  
  7. ?>

 

Code Block 2: The Content-Type field for multipart entities requires one parameter, "boundary", which is used to specify the encapsulation boundary. The encapsulation boundary is defined as a line consisting entirely of two hyphen characters ("-", decimal code 45) followed by the boundary parameter value from the Content-Type header field. $hash[0] will store this value.

$hash[1] stores the encapsulation boundary for the email content which must be applied before each message part.

Code Block 3: Set the File Attachment Details
  1. <?php
  2.  
  3. $filedir = 'files';
  4. $fileArray = array('2006-0111orion-full.jpg','2006-0111orion-full.zip');
  5. $attachments = NULL;
  6. foreach ($fileArray AS $key => $value)
  7. {
  8.         $fullpath = sprintf('%s/%s',$filedir,$value);
  9.         if (!file_exists($fullpath)) { continue; }
  10.        
  11.         $ext = str_replace('.',NULL,strstr($value,'.'));
  12.        
  13.         /*      @Local function to get file type
  14.         -----------------------------------------------------------*/
  15.         $filetype = get_filetype($ext);
  16.         $filechunks = chunk_split(base64_encode(file_get_contents($fullpath)));
  17.  
  18. $attachments .= <<<MAILATTACHMENT
  19.  
  20. --$hash[1]
  21. Content-Type: $filetype; name="$value"
  22. Content-Transfer-Encoding: base64
  23. Content-Disposition: attachment
  24. $filechunks
  25.  
  26. MAILATTACHMENT;
  27. }
  28.  
  29. ?>

 

Code Block 3: Set up details for the file(s) to be attached. The actual file(s) is/are trivial in this case since the file(s) can be located on the server or directly from an upload. Whether one or twenty attachements, all will be part of the $hash[1] boundary.

Once the file(s) has/have been established, the correct MIME type associated with the file(s) (based on the file's extention) must be obtained. The local function 'get_filetype' is not included in this tutorial but the end result for $filetype in this example is 'image/jpg' for the first file and 'application/zip' for the second file. For more information on MIME, please read up on it at Wikipedia.

Please note that any and all MIME content must never contain any tabs. The left-alignment of the $attachements variable inside the foreach loop must be without tabs and aligned completed left.

Code Block 4: Create mail headers and body
  1. <?php
  2.  
  3. $headers = <<<MAILHEADERS
  4. From: $from
  5. Reply-To: $from
  6. MIME-Version: 1.0
  7. Content-Type: multipart/mixed; boundary="$hash[0]"
  8. MAILHEADERS;
  9.  
  10. $message = <<<MAILBODY
  11. This is a multi-part message in MIME format.
  12.  
  13. --$hash[0]
  14. Content-Type: multipart/alternative; boundary="$hash[1]"
  15.  
  16. --$hash[1]
  17. Content-Type: text/plain; charset="utf-8"
  18. Content-Transfer-Encoding: quoted-printable
  19. Congrats. You have an attachment!
  20.  
  21. --$hash[1]
  22. Content-Type: text/html; charset="utf-8"
  23. Content-Transfer-Encoding: quoted-printable
  24. <h2>Contrats!</h2>
  25. <p><strong>You</strong> have an attachment.</p>
  26.  
  27. $attachments
  28.  
  29. --$hash[0]
  30. MAILBODY;
  31.  
  32. ?>

 

Code Block 4: Build the email headers and the email body.

Code Block 5: Send the email
  1. <?php
  2.  
  3. if (mail($to,$subject,$message,$headers))
  4. {
  5.         print('<p>Message Sent!</p>');
  6.         exit(0);
  7. }
  8. else
  9. {
  10.         print('<p>There was an error sending the mail.</p>');
  11.         exit(0);
  12. }
  13.  
  14. ?>

 

Code Block 5: Finally, send the email using the internal PHP mail function.

Back to Top