Add Mail Attachment

Description: Adds mail attachments to outgoing PHP emails. Expects the full file path to the file you want to send, the boundary used in the email and the content type of the file to attach (assumes MS Excel by default). Make sure file name has no spaces to avoid any potential problems.
Tested Platform: PHP 7+
Language: PHP
// Adds an attachment and returns the content to add to the mutlipart/mixed mail message.
function addEmailAttachment($fullpath, $boundary, $contentType = "application/ms-excel") {
    if (file_exists($fullpath)) {
        $path_parts = pathinfo($fullpath);
        $theFile = $path_parts["basename"];

        $message .= "--{$boundary}n";
        $message .= "Content-Type: $contentType; name="{$theFile}"n";
        $message .= "Content-Transfer-Encoding: base64n";
        $message .= "Content-Disposition: attachment; filename="{$theFile}"nn";

        $fp = fopen($fullpath, 'r');

        $content = "";
        
        do {
            $data = fread($fp, 8192);
            if (strlen($data) === 0) {
                break;
            }
            $content .= $data;
        } while (true);
        
        fclose($fp);

        $content_encode = chunk_split(base64_encode($content));
        $message .= $content_encode . "n";
    } else { 
        $message = ""; 
    }
    
    return $message;
}

Posted: March 18, 2023

Return to the snippets listing