Email an Attachment Using PHP

The following is an example of a PHP function that will MIME encode a file and send it via email as an attachment.

I'm pulling the filename from the command line ($argv[1]). You could specify the address instead, of course.

#!/usr/bin/php
<?php

	// Setup the email
	$my_file = $argv[1];
	$my_name = "Joel Dare";
	$my_mail = "joel@example.com";
	$my_subject = "Ad Screenshot";
	$my_message = "Hi,\r\nAttached is a screenshot of an ad I thought might be prohibited.\r\n\r\n- Joel";
	$to_address = 'john@example.com';
	
	// Say what we are doing
	echo "\nSending $my_file via email...\n";
	
	// Send the email
	mail_attachment($my_file, $to_address, $my_mail, $my_name, $my_subject, $my_message);


	// =========================================================================
	// mail_attachment
	// -------------------------------------------------------------------------
	// Send an email, including an attachment.
	// =========================================================================
	function mail_attachment($file, $mailto, $from_mail, $from_name, $subject, $message) {
		
		// Read the file in and encode it
		$content = file_get_contents($file);
		$content = chunk_split(base64_encode($content));
		
		// Create a unique id to use in the MIME message
		$uid = md5(uniqid(time()));
		
		// Setup the file name to use in the email
		$name = basename($file);
		
		// Setup the email message
		$header = "From: ".$from_name." <".$from_mail.">\r\n";
		$header .= "MIME-Version: 1.0\r\n";
		$header .= "Content-Type: multipart/mixed; boundary=\"".$uid."\"\r\n\r\n";
		$header .= "This is a multi-part message in MIME format.\r\n";
		$header .= "--".$uid."\r\n";
		$header .= "Content-type:text/plain; charset=iso-8859-1\r\n";
		$header .= "Content-Transfer-Encoding: 7bit\r\n\r\n";
		$header .= $message."\r\n\r\n";
		$header .= "--".$uid."\r\n";
		$header .= "Content-Type: application/octet-stream; name=\"".$name."\"\r\n";
		$header .= "Content-Transfer-Encoding: base64\r\n";
		$header .= "Content-Disposition: attachment; filename=\"".$name."\"\r\n\r\n";
		$header .= $content."\r\n\r\n";
		$header .= "--".$uid."--";
		
		// Send the email
		$return = mail($mailto, $subject, "", $header);
		if ($return) {
		    echo "Mail sent.\n";
		} else {
		    echo "ERROR! Unable to send mail.\n";
		}
		
	}

?>
comments powered by Disqus
php/email_an_attachment_using_php.txt · Last modified: 2020/06/01 22:53 (external edit)