Send smtp mail in php with HTML page attach as a text
- by Nirmal
Hello All....
I have a requirement of sending mail using smtp server in php.
Now I am able to send the mail using smtp for a plain text.
but I have a requirement where I need to attach an HTML page, which includes set of images.
Now for that I am trying the following code :
<?php
require_once "Mail.php";
$to = '[email protected]';
$from = '[email protected]';
$subject = $_POST['subject'];
$body = $_POST['message'];
$fileatt = $_FILES['fileatt']['tmp_name'];
$fileatt_type = $_FILES['fileatt']['type'];
$fileatt_name = $_FILES['fileatt']['name'];
$headers = array ('From' => $from,
'To' => $to,
'Subject' => $subject);
if (is_uploaded_file($fileatt)) {
echo("<p>Inside 1</p>");
$file = fopen($fileatt,'rb');
$data = fread($file,filesize($fileatt));
fclose($file);
// Generate a boundary string
$semi_rand = md5(time());
$mime_boundary = "==Multipart_Boundary_x{$semi_rand}x";
array_push(&$headers, 'MIME-Version: 1.0');
array_push(&$headers, 'Content-Type: multipart/mixed;');
array_push(&$headers, " boundary=\"{$mime_boundary}\"");
echo("<p>Inside 2</p>");
$body = "This is a multi-part message in MIME format.\n\n" .
"--{$mime_boundary}\n" .
"Content-Type: text/plain; charset=\"iso-8859-1\"\n" .
"Content-Transfer-Encoding: 7bit\n\n" .
$body . "\n\n";
echo("<p>Inside 3</p>");
$data = chunk_split(base64_encode($data));
echo("<p>Inside 4</p>");
$body .= "--{$mime_boundary}\n" .
"Content-Type: {$fileatt_type};\n" .
" name=\"{$fileatt_name}\"\n" .
"Content-Transfer-Encoding: base64\n\n" .
$data . "\n\n" .
"--{$mime_boundary}--\n";
echo("<p>Inside 5</p>");
}
$host = "[email protected]";
$username = "[email protected]";
$password = "user";
$smtp = Mail::factory('smtp',
array ('host' => $host,
'auth' => true,
'username' => $username,
'password' => $password));
$mail = $smtp->send($to, $headers, $body);
if (PEAR::isError($mail)) {
echo("<p>" . $mail->getMessage() . "</p>");
} else {
echo("<p>Message successfully sent!</p>");
}
?>
Now this code works fine for me, and it's sending the mail to the target email address.
But when I open this email in the inbox, it's showing me the following text in the mailbox:
This is a multi-part message in MIME format.
--==Multipart_Boundary_x368d72fe1ff44518e90537abdb4bf029x
Content-Type: text/plain; charset="iso-8859-1"
Content-Transfer-Encoding: 7bit
test 1011
--==Multipart_Boundary_x368d72fe1ff44518e90537abdb4bf029x
Content-Type: text/html;
name="mailing.html"
Content-Transfer-Encoding: base64
PCFET0NUWVBFIGh0bWwgUFVCTElDICItLy9XM0MvL0RURCBYSFRNTCAxLjAgVHJhbnNpdGlvbmFs
Ly9FTiIgImh0dHA6Ly93d3cudzMub3JnL1RSL3hodG1sMS9EVEQveGh0bWwxLXRyYW5zaXRpb25h
................
So, it's clearly showing me the encoded data.
So, what should modify to send the proper html page that should be visible in targeted email's inbox?
Thanks in advance...