PHP Mail Attachment

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.

  1. <?php
  2. $to = isset($name) ? sprintf('%s <%s>',$name,$email) : $email;
  3. $from = 'Automated Attachement <someuser@somedomain.com>';
  4. $subject = 'Here is your attachment';
  5. ?>

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).

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

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.

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

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 <strong>without</strong> tabs and aligned completed left.

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

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

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

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