Tag Archives: wamp server - Page 2

Sending email with attachment from localhost/WAMP Server using sendmail

PHPMailer and PEAR Mail supports sending attachment with email using their functions or extensions; but PHP’s own mail() function hasn’t any function separately to achieve this. Developers have to use their own code to attach file within email’s body to do so.

PHP’s mail() function can be used with sendmail.exe to send email from localhost/WAMP Server and I have already posted an article about it; so to configure it, refer to that article. This article will cover only the PHP code for sending email with attachment(s).

Solution
<?php
$random_hash = md5(time());
$file1 = "ebook.pdf";
$file2 = "image.jpg";
$to = "[recepient's_email_address]";
$subject = 'the subject';
$headers = 'From: [your_gmail_id]@gmail.com' . "\r\n" .
  'Reply-To: [your_gmail_id]@gmail.com' . "\r\n" .
  'X-Mailer: PHP/' . phpversion() . "\r\n" .
  'Content-Type: multipart/mixed; boundary="PHP-mixed-'.$random_hash.'"';
$attachment1 = chunk_split(base64_encode(file_get_contents($file1)));
$attachment2 = chunk_split(base64_encode(file_get_contents($file2)));

$message = <<<EMAIL_MESSAGE
--PHP-mixed-$random_hash
Content-Type: text/html; charset="iso-8859-1"; boundary="PHP-alt-$random_hash

<h2>Hello World!</h2>
<p>This is something with <b>HTML</b> formatting.</p>
--PHP-mixed-$random_hash
Content-Type: application/pdf; name="$file1" 
Content-Transfer-Encoding: base64 
Content-Disposition: attachment 

$attachment1
--PHP-mixed-$random_hash
Content-Type: image/jpg; name="$file2" 
Content-Transfer-Encoding: base64 
Content-Disposition: attachment 

$attachment2
--PHP-mixed-$random_hash--
EMAIL_MESSAGE;

if(mail($to, $subject, $message, $headers))
	echo "Email sent";
else
	echo "Email sending failed";
?>

The “else” part in the above code might never get executed because mail() function will not return false when used with sendmail.exe; so might not get the error/reason if you don’t receive email.

Don’t try to send email from Yahoo!’s free email account, because it is not allowing users to send email using its SMTP server from other email clients or other such facilities (like this, specified in this article), only premium/paid members can use external resources than Yahoo! Mail to send emails.