Send html emails using PHPMailer and html templates - php

I'm trying to get the emails sent from my contact (using PHPMailer) sent in a nice html template (phtml actually).
What works: I receive the html template so no issue with the transmission
What does not work: The variables (message, phone number, etc) are not reflected in the body of my html template.
I have tried several things in the html template, without success: <?= htmlspecialchars($message) ?> and #message# and <?php echo$_POST['message'] ?>
What is the issue?
Thanks,
Here is the PHPMailer code:
<?php
require 'PHPMailer/PHPMailerAutoload.php';
$mail = new PHPMailer;
$mail->CharSet = 'utf-8';
$body = file_get_contents('htmlemail.phtml');
//Enable SMTP debugging.
$mail->SMTPDebug = false;
//Set PHPMailer to use SMTP.
$mail->isSMTP();
//Set SMTP host name
$mail->Host = "smtp.sendgrid.net";
//Set this to true if SMTP host requires authentication to send email
$mail->SMTPAuth = true;
//Provide username and password
$mail->Username = "";
$mail->Password = "";
//If SMTP requires TLS encryption then set it
$mail->SMTPSecure = "tls";
//Set TCP port to connect to
$mail->Port = 587;
$mail->From = $_POST['email'];
$mail->FromName = $_POST['first_name'] . " " . $_POST['last_name'];
$mail->addAddress("#gmail.com");
//CC and BCC
$mail->addCC("");
$mail->addBCC("");
$mail->isHTML(true);
$mail->Subject = "Nouveau message depuis ";
$mail->MsgHTML($body);
$response = array();
if(!$mail->send()) {
$response = array('message'=>"Mailer Error: " . $mail->ErrorInfo, 'status'=> 0);
} else {
$response = array('message'=>"Message has been sent successfully", 'status'=> 1);
}
/* send content type header */
header('Content-Type: application/json');
/* send response as json */
echo json_encode($response);
?>

Using ob_start
ob_start();
include 'htmlemail.php';
$body = ob_get_clean();
Or
You can also use a templating method to generate the email body for multiple uses.
E.g.
In your html template, have variables assigned like this:
Thank you {NAME} for contacting us.
Your phone number is {PHONE}
Then before calling your phpmailer, create an array to process the email body:
$email_vars = array(
'name' => $_POST['name'],
'phone' => $_POST['phone'],
);
And finally, with phpmailer...
$body = file_get_contents('htmlemail.phtml');
if(isset($email_vars)){
foreach($email_vars as $k=>$v){
$body = str_replace('{'.strtoupper($k).'}', $v, $body);
}
}
This way your emails will have all the dynamic content you need in the body.

try this. From morning onwards I am trying to resolve this thread finally I did it. I thought to share it and may be useful to someone.
Here is my code:
<?php
// I removed mysql query
require '../../../PHPMailer/PHPMailerAutoload.php';
$mail = new PHPMailer;
$mail->isSMTP();
$mail->Host = 'xxxxx';
$mail->SMTPAuth = true;
$mail->Username = 'xxxx';
$mail->Password = 'xxxxx';
$mail->SMTPSecure = 'openssl';
$mail->Port = 587;
$mail->isHTML(true);
$mail->setFrom('from', 'title');
$mail->addAddress($row1['email'] , $row1['fullname']);
$mail->addAttachment('p2t-'.$row1['id'].'.pdf');
$mail->addEmbeddedImage('logo.png', 'logo_p2t');
$mail->addEmbeddedImage('web/'.$row1['photo'].'', 'logo_p2t1');
$mail->Subject = 'Thanks for registering with us';
$mail->Body = "
<html>
<head>
<title></title>
</head>
<body>
<div style='width:800px;background:#fff;border-style:groove;'>
<div style='width:50%;text-align:left;'><a href='your website url'> <img
src=\"cid:logo_p2t\" height=60 width=200;'></a></div>
<hr width='100%' size='2' color='#A4168E'>
<div style='width:50%;height:20px; text-align:right;margin-
top:-32px;padding-left:390px;'><a href='your url' style='color:#00BDD3;text-
decoration:none;'>
My Bookings</a> | <a href='your url' style='color:#00BDD3;text-
decoration:none;'>Dashboard </a> </div>
<h2 style='width:50%;height:40px; text-align:right;margin:0px;padding-
left:390px;color:#B24909;'>Booking Confirmation</h2>
<div style='width:50%;text-align:right;margin:0px;padding-
left:390px;color:#0A903B'> Booking ID:1150 </div>
<h4 style='color:#ea6512;margin-top:-20px;'> Hello, " .$row1['fullname']."
</h4>
<p>Thank You for booking with us.Your Booking Order is Confirmed Now. Please
find the trip details along with the invoice. </p>
<hr/>
<div style='height:210px;'>
<table cellspacing='0' width='100%' >
<thead>
<col width='80px' />
<col width='40px' />
<col width='40px' />
<tr>
<th style='color:#0A903B;text-align:center;'>" .$row1['car_title']."</th>
<th style='color:#0A903B;text-align:left;'>Traveller Info</th>
<th style='color:#0A903B;text-align:left;'>Your Pickup Details: </th>
</tr>
</thead>
<tbody>
<tr>
<td style='color:#0A903B;text-align:left;padding-bottom:5px;text-
align:center;'><img src=\"cid:logo_p2t1\" height='90' width='120'></td>
<td style='text-align:left;'>" .$row1['fullname']." <br> " .$row1['email']."
<br> " .$row1['phone']." <br>" .$row1['nearestcity']." </td>
<td style='text-align:left;'>" .$row1['pickupaddress']." <br> Pickuptime:"
.$row1['pickuptime']." <br> Pickup Date:" .$row1['pickupdate']."
<br> Dropoff: " .$row1['dropoffaddress']."</td>
</tr>
<tr>
</tbody>
</table>
<hr width='100%' size='1' color='black' style='margin-top:10px;'>
<table cellspacing='0' width='100%' style='padding-left:300px;'>
<thead>
<tr>
<th style='color:#0A903B;text-align:right;padding-bottom:5px;width:70%'>Base
Price:</th>
<th style='color:black;text-align:left;padding-bottom:5px;padding-
left:10px;width:30%'>" .$row1['base_price']."</th>
</tr>
<tr>
<th style='color:#0A903B;text-align:right;padding-bottom:5px;'>GST(5%):</th>
<th style='color:black;text-align:left;padding-bottom:5px;padding-
left:10px;'>" .$row1['gst']."</th>
</tr>
<tr>
<th style='color:#0A903B;text-align:right;'>Total Price:</th>
<th style='color:black;text-align:left;padding-bottom:5px;padding-
left:10px;'>" .$row1['total_price']."</th>
</tr>
</thead>
</table>
</div>
</div>
</body>
</html>";
if(!$mail->send()) {
echo 'Message could not be sent.';
echo 'Mailer Error: ' . $mail->ErrorInfo;
} else {
echo 'Message has been sent';
}
echo "<script type='text/javascript'> document.location = './'; </script>";
?>
And the output is:
Image of the custom html code embedded in mail body.
Thanks.
All the best.

$body = file_get_contents('htmlemail.phtml');
reads the file as is and puts in the variable $body. It should not have <?php ?> because that would mean a recursion.
If you want the php code inside htmlemail.phtml to be executed, you can include() or require() it.
In your htmlemail.phtml, use this:
<?php
$body = "
Hello {$_POST['name']}
This is your message {$_POST['message']}
Thanks
";
in your php, replace
$body = file_get_contents('htmlemail.phtml');
with
include('htmlemail.phtml');
Do not include other double quotes " in your phtml file, or learn about them in PHP first.
What is the difference between single-quoted and double-quoted strings in PHP?

$mail->isHTML(true); // Define as HTML
$mail->Body = HTMLBODY
$mail->AltBody = TEXTBODY
No need to define content type PHPMailler set everything

try this,
$mail->Body = 'This is the HTML message body <strong>in bold!</strong>';
i hope it will be helpful

Related

Why phpmailer is not sending mail to my domain mail server

I'm trying to send mail to my domain mail server:
I used a try{} catch(){} to detect if there is any error, but surprisingly, there isn't any error.
<?php
function Redirect_to($New_Location){
header("Location:" . $New_Location);
exit;
}
if(isset($_POST['Submitenq'])){
require('phpmailer/PHPMailerAutoload.php');
define ('GUSER','courses#cadcentreju.org');
define ('GPWD','mymailpass');
$recever1 = 'courses#cadcentreju.org';
$enq_name = $_POST["enq_name"];
$enq_email = $_POST["enq_email"];
$enq_phone = $_POST["enq_phone"];
$enq_message = $_POST["enq_message"];
date_default_timezone_set("Asia/Kolkata");
$CurrentTime = time();
$DateTime = strftime("%B-%d-%Y %H:%M:%S",$CurrentTime);
if(empty($enq_name) || empty($enq_email) || empty($enq_phone) || empty($enq_message)){
Redirect_to("index.php?error=1");
}else{
$mail = new PHPMailer();
try{
$mail->IsSMTP();
$mail->Mailer = "smtp";
// $mail->SMTPDebug = 2;
$mail->SMTPAuth = TRUE;
$mail->SMTPSecure = "ssl";
$mail->Port = 465;
$mail->Host = "mail.supremecluster.com";
// $mail->CharSet = "UTF-8";
$mail->Username = GUSER;
$mail->Password = GPWD;
$mail->isHTML(true);
$mail->setFrom($enq_email,$enq_name);
$mail->addAddress($recever1);
$mail->Subject = 'Enquery Mail from - '. $enq_name;
$mail->Body = '<table class="table" cellspacing="0">
<thead>
<tr>
<th colspan="2">Enquery Mail from - '. $enq_name .'</th>
</tr>
</thead>
<tbody>
<tr>
<td colspan="2">'. '<p>Dear Sir / Madam, I have some enqueries as follows :</p></br>' .'</td>
</tr>
<tr>
<td>Email:</td>
<td>'. $enq_email .'</td>
</tr>
<tr>
<td>Phone No:</td>
<td>'. $enq_phone .'</td>
</tr>
<tr>
<td>City:</td>
<td>'. $sendercity .'</td>
</tr>
<tr>
<td>Message:</td>
<td>'. $enq_message .'</td>
</tr>
<tr>
<td>Date of Enquery:</td>
<td>'. $DateTime .'</td>
</tr>
</tbody>
</table>';
$mail->send();
$success_msg = "Your Message Sent Successfully: ";
}catch(phpmailerException $e){
echo $e->errorMessage();
}catch(Exception $e){
echo $e->getMessage();
}
}
}
?>
<?php include 'header.php'; ?>
<div style="height:50vh;margin-top: 268px; background:#ddd;" class="d-flex justify-content-center align-items-center">
<?php
if(isset($success_msg)){
?>
<div class="alert alert-success" role="alert">
<?php
echo $success_msg . $enq_name;
?>
</div>
<?php
}else{
?>
<div class="alert alert-danger" role="alert">
<?php
echo "Something went wrong";
?>
</div>
<?php
}
?>
</div>
<?php include 'footer.php'; ?>
It's showing me that the email sent successfully, but I'm not getting
any mail.
I've contacted my server helpline, they're saying that certain IPs were blocked. But now I've allowed these IPs from the CPanel. But still, the mails are not sent
I really need help on this :)
Thanks for taking the time to read.
PHPMailer doesn't throw exceptions by default – you have to ask for them by passing true to the constructor, as in $mail = new PHPMailer(true);. Without that you have to check the return values from methods like send() to find out if they worked.
Errors are stored in the ErrorInfo property – see any of the code examples provided with PHPMailer to see how to handle errors correctly.
You can also set $mail->SMTPDebug = 2; to see what your mail server is saying. Beyond that, read the PHPMailer troubleshooting guide.
My final Working Code is:
function Redirect_to($New_Location){
header("Location:" . $New_Location);
exit;
}
if(isset($_POST['Submitenq'])){
require('phpmailer/PHPMailerAutoload.php');
define ('GUSER','courses#cadcentreju.org');
define ('GPWD','mailpass');
$recever1 = 'courses#cadcentreju.org';
$enq_name = $_POST["enq_name"];
$enq_email = $_POST["enq_email"];
$enq_phone = $_POST["enq_phone"];
$enq_message = $_POST["enq_message"];
date_default_timezone_set("Asia/Kolkata");
$CurrentTime = time();
$DateTime = strftime("%B-%d-%Y %H:%M:%S",$CurrentTime);
if(empty($enq_name) || empty($enq_email) || empty($enq_phone) || empty($enq_message)){
Redirect_to("index.php?error=1");
}else{
$mail = new PHPMailer(true);
try{
$mail->IsSMTP();
$mail->Mailer = "smtp";
// $mail->SMTPDebug = 2;
$mail->SMTPAuth = TRUE;
$mail->SMTPSecure = "none";
$mail->Port = 25;
$mail->Host = "mail.supremecluster.com";
// $mail->CharSet = "UTF-8";
$mail->Username = GUSER;
$mail->Password = GPWD;
$mail->isHTML(true);
$mail->setFrom($enq_email,$enq_name);
$mail->From = GUSER;
$mail->FromName = $enq_name;
$mail->addAddress($recever1);
$mail->Subject = 'Enquiry Mail from - '. $enq_name;
$mail->Body = '<table class="table" cellspacing="0">
<thead>
<tr>
<th colspan="2">Enquiry Mail from - '. $enq_name .'</th>
</tr>
</thead>
<tbody>
<tr>
<td colspan="2">'. '<p>Dear Sir / Madam, I have some enquiries. My Details are as follows :</p></br>' .'</td>
</tr>
<tr>
<td>Email:</td>
<td>'. $enq_email .'</td>
</tr>
<tr>
<td>Phone No:</td>
<td>'. $enq_phone .'</td>
</tr>
<tr>
<td>Message:</td>
<td>'. $enq_message .'</td>
</tr>
<tr>
<td>Date and TIME of Enquery:</td>
<td>'. $DateTime .'</td>
</tr>
</tbody>
</table>';
$mail->send();
$success_msg = "Your Message Sent Successfully: ";
}catch(phpmailerException $e){
echo $e->errorMessage();
}catch(Exception $e){
echo $e->getMessage();
}
I decided to send mail from my own server instead of Gmail server:
So I changed:
$mail->SMTPSecure = "ssl";
to
$mail->SMTPSecure = "none";
Most Important thing to remember that:
$mail->Username = GUSER;
And
$mail->From = GUSER;
MUST BE SAME
AND
Also,
We have to pass true to the constructor:
$mail = new PHPMailer(true)
// Argument true in constructor enables exceptions
Go to your Gmail Account -> Security
Find "Access less secure app". Turn it ON and Run your PHP file again.
The Mail should be sent.

phpmailer with AddAttachment and dkim, i get error : dkim=neutral (body hash did not verify)

I can send email with phpmailer and dkim with pass result.
but if AddAttachment file is present ,
i got : dkim=neutral (body hash did not verify)
<?php
$message = "<html><head>
<meta http-equiv='Content-Type' content='text/html; charset=utf-8'>
</head>
<body>
<table width='650' border='0' cellspacing='0' cellpadding='0'>
<tr>
<td class='style22' >TEST TEST</td>
</tr>
<td bgcolor='#0066FF' class='style22'>Description </td><td>SOME TEXT</td>
</tr>
</table></body></html>";
use PHPMailer\PHPMailer\PHPMailer;
require 'phpmailer6/vendor/autoload.php';
$file = "phpmailer6/1420069.pdf";
$mail = new PHPMailer(true);
$mail->setFrom('contact#mydomain.fr', 'First Last');
$mail->addAddress('paul25241#gmail.com', 'Paul');
$mail->Subject = 'PHPMailer mail() test';
$mail->msgHTML($message);
$mail->AddAttachment($file); // attachment
$mail->DKIM_domain = 'mydomain.fr';
$mail->DKIM_private = 'phpmailer6/private.key';
$mail->DKIM_selector = 'default';
$mail->DKIM_passphrase = '';
$mail->DKIM_identity = $mail->From;
if (!$mail->send()) {
echo "Mailer Error: " . $mail->ErrorInfo;
} else {
echo "YEAR !!! Message sent!";
}
?>
`
authentication-Results: mx.google.com;
dkim=neutral (body hash did not verify)

Codeigniter email function fails to send rendered html code in yahoo and livemail

We use the CI mail library in our codeigniter site. It sends emails in proper format in gmail, but in hotmail and yahoo it just shows the html code
we call the html template in file with this:
emailer_temp.php
<!DOCTYPE>
<html>
<head>
<title>Registration Confirmation Letter</title>
<style><body>
<table width="100%" cellspacing="0" cellpadding="0" border="0" style="background:rgb(233, 234, 234) none repeat scroll 0% 0% / auto padding-box border-box;"><tbody><tr><td><div style="margin:0 auto;width:1089px;padding:0px">
<table class="main mce-item-table" width="100%" cellspacing="0" cellpadding="0" border="0" align="center" data-types="background,padding,border-radius,image-settings" data-last-type="image-settings">
<tbody>
<tr>
<td align="center" class="image image-full element-content element-contenteditable active" style="padding:0;">
<img class="content-image " style="width: 1089px; height: 287px;" src="<?=base_url()."assets/emailer/register.png";?>">
</td>
</tr>
</tbody>
</table>
</body>
</html>
call template in controller
if($ResponseCode=="0"){
if(checkonlinepayment($MerchantRefNo,$Amount)==1){
$data->user = $this->user_model->get_user_profile($userid);
$data->accuser = $this->user_model->get_user_accommodation($userid);
$data->userpayacc = $this->user_model->get_paydataacc($PaymentID);
$this->sendtomail($data->user[0]->email,"Registration Confirmation Letter",$data,"emails/emailer_temp.php");
$mobileno = $data->user[0]->mobileno;
$this->sendacctosms($mobileno);
}
}
use sendtomail function in controller
function sendtomail($userEmail,$subject,$data,$templates){
$config['protocol'] = 'sendmail';
$config['smtp_host'] = 'mail.mysite.com';
$config['smtp_port'] = '25';
$config['smtp_timeout'] = '1';
$config['smtp_crypto'] = 'tls';
$config['smtp_user'] = 'support#mysite.com';
$config['smtp_pass'] = 'admin!##321';
$config['charset'] = 'utf-8';
$config['mailtype'] = 'html';
$config['priority'] = '1';
$config['wordwrap'] = TRUE;
$this->load->library('email',$config);
$this->email->from('support#mysite.com', '2018');
$list = array($userEmail, 'mysite#gmail.com', 'mysite#mysite.in');
$this->email->to($list);
//$this->email->to($userEmail); // replace it with receiver mail id
$this->email->subject($subject);
$this->email->set_newline("\r\n");
$this->email->set_header('MIME-Version', '1.0; charset=utf-8'); //must add this line
$this->email->set_header('Content-type', 'text/html'); //must add this line
$body = $this->load->view($templates,$data,true);
$this->email->message($body);
$this->email->set_newline("\r\n");
$this->email->send();
}
So the question is: why is this code sending the html code as text instead of a rendered message in Yahoo and Hotmail? It works with gmail!
most likely it is a $this->email->set_header() problem
you are using:
$this->email->set_header('MIME-Version', '1.0; charset=utf-8');
note: you are using a semi-colon ';' within your MIME declaration.
it should be:
$this->email->set_header('MIME-Version=1.0', 'charset=utf-8');

Unable to send email content using PHPMailer

I am creating an e-commerce website that sends email about order detail after user have checked out. I've succeeded in sending email using PHPMailer. However, the content of email I've sent is being escaped.
How do I ensure that the order detail is being processed properly like the image below?
This is the phpmailer code:
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
<title>PHPMailer - SMTP test</title>
</head>
<body>
<?php
//SMTP needs accurate times, and the PHP time zone MUST be set
//This should be done in your php.ini, but this is how to do it if you don't have access to that
date_default_timezone_set("Asia/Singapore");
require '../PHPMailerAutoload.php';
include ('../test.php');
//Create a new PHPMailer instance
$mail = new PHPMailer();
//Tell PHPMailer to use SMTP
$mail->isSMTP();
//Enable SMTP debugging
// 0 = off (for production use)
// 1 = client messages
// 2 = client and server messages
$mail->SMTPDebug = 2;
//Ask for HTML-friendly debug output
$mail->Debugoutput = 'html';
//Set the hostname of the mail server
$mail->Host = "smtp.gmail.com";
//enable this if you are using gmail smtp, for mandrill app it is not required
$mail->SMTPSecure = 'ssl';
//Set the SMTP port number - likely to be 25, 465 or 587
$mail->Port = 465;
//Whether to use SMTP authentication
$mail->SMTPAuth = true;
//Username to use for SMTP authentication
$mail->Username = "GMAIL.COM";
//Password to use for SMTP authentication
$mail->Password = "PASSWORD";
//Set who the message is to be sent from
$mail->setFrom('popo#shop.com', 'POPO ECOMMERCE');
//Set an alternative reply-to address
$mail->addReplyTo('popo#shop.com', 'POPO ECOMMERCE');
//Set who the message is to be sent to
$mail->addAddress($email, $user);
//Set the subject line
$mail->Subject = 'Order Details';
//Read an HTML message body from an external file, convert referenced images to embedded,
//convert HTML into a basic plain-text alternative body
$mail->msgHTML(file_get_contents('order.php'), dirname(__FILE__));
//Replace the plain text body with one created manually
//$mail->AltBody = 'This is a plain-text message body';
//Attach an image file
//$mail->addAttachment('images/phpmailer_mini.png');
$mail->XMailer = ' ';
//send the message, check for errors
if (!$mail->send()) {
echo "Mailer Error: " . $mail->ErrorInfo;
} else {
echo "Message sent!";
}
?>
</body>
</html>
Message code:
<?php
include("../include/db.php");
$user= $_SESSION['id'];
?>
<?php
echo
"<div style='width: 640px; font-family: Arial, Helvetica, sans-serif; font-size: 15px;'>
<h1>Order Details</h1>
";
echo
"<p>Dear <b style='color:blue;'>$user</b>, you have ordered the following products from our website: popo.
Below are the details of your order. We will be shipping the products to your address in two weeks.
<br><br>
Thank you for using POPO.
<Br><br><br>
Order Details: <br></p>";
echo '
<table width = "1093" align="center" bgcolor="silver">
<tr align="center">
<th>S.N</th>
<th>Product ID</th>
<th>Invoice ID</th>
<th>QTY</th>
</tr>';
$get_pro =$db->prepare( 'select Product_ID,invoice_id,qty from orders where userid = ?');
$get_pro->bind_param('s',$user);
$get_pro->execute();
$get_pro->bind_result($pro_title,$pro_id,$pro_qty);
$i =0 ;
while ($get_pro->fetch())
{
$i++;
?>
<?php
echo "
<tr align='center'>
<td> $i</td>
<td> $pro_title</td>
<td> $pro_id</td>
<td>$pro_qty</td>
</tr>";
?>
<?php } ?>
<?php echo "</table>"?>
file_get_content() does not execute php script. You need to replace:
$mail->msgHTML(file_get_contents('order.php'), dirname(__FILE__));
by
ob_start();
include "order.php";
$message = ob_get_clean();
$mail->msgHTML($message);
dont load the order.php with file_get_contents() cause this will not execute the php code!
include the file like this:
ob_start();
include("order.php");
$message = ob_get_contents();
ob_end();
$mail->msgHTML($message);
Try replacing the messege code to this:
<?php
include("../include/db.php");
$user = $_SESSION['id'];
echo "<div style='width: 640px; font-family: Arial, Helvetica, sans-serif; font-size: 15px;'>
<h1>Order Details</h1>";
echo "<p>Dear <b style='color:blue;'>$user</b>, you have ordered the following products from our website: popo.
Below are the details of your order. We will be shipping the products to your address in two weeks.
<br>
<br>
Thank you for using POPO.
<Br><br><br>
Order Details: <br></p>";
echo '
<table width = "1093" align="center" bgcolor="silver">
<tr align="center">
<th>S.N</th>
<th>Product ID</th>
<th>Invoice ID</th>
<th>QTY</th>
</tr>';
$get_pro = $db->prepare('select Product_ID,invoice_id,qty from orders where userid = ?');
$get_pro->bind_param('s',$user);
$get_pro->execute();
$get_pro->bind_result($pro_title,$pro_id,$pro_qty);
$i = 0;
while ($get_pro->fetch())
{ $i++;
echo "<tr align='center'>
<td> $i</td>
<td> $pro_title</td>
<td> $pro_id</td>
<td>$pro_qty</td>
</tr>";
break;
}
echo "</table>";
?>
And on the other file:
$mail->msgHTML(file_get_contents('order.php'), dirname(__FILE__));
To:
ob_start();
include("order.php");
$message = ob_get_contents();
ob_end();
$mail->msgHTML($message);

NO Html Data is mailed Using Php Mailer Library

what I Need:
when user click on button mail with html content should recipent recived.
My problem:
No Html Content is Send in mail.
here is my code mail.php
require 'PHPMailerAutoload.php';
$message = '
<html>
<head>
<title>ES Html Report</title>
</head>
<body>
<table>
<tr>
<th>Project Name</th>
<th>TODo</th>
<th>Priority</th>
<th>Due on</th>
<th>Assignee</th>
<th>Created</th>
<th>Updated</th>
<th>Completed</th>
<th>Assignee Status</th>
<th>Status</th>
</tr>
<tr>
<td>aaaa</td>
</tr>
<tr>
<td>Sally</td
</tr>
<td>1</td>
</tr>
<tr>
<td>ankit</td>
</tr>
<tr>
<td>1-09-89</td>
</tr>
<tr>
<td>1-08-77</td>
</tr>
<tr>
<td>177th</td>
</tr>
<tr>
<td>ok</td>
</tr>
<tr>
<td>gg</td>
</tr>
<tr>
<td>1710th</td>
</tr>
</table>
</body>
</html>
';
$mail = new PHPMailer();
$mail->isSendmail();
$mail->setFrom('af15#gmail.com', 'First Last');
//$mail->addReplyTo('af#ankrus.com', 'First Last');
$mail->addAddress('aef#anus.com', 'John Doe');
$mail->Subject = $subject ;
$msg = 'my html and php code that format the mail';
$body= preg_replace('/\[\]/','',$msg);
$mail->msgHTML($body);
$mail->msgHTML($message)
$mail->AltBody = 'This is a plain-text message body';
if (!$mail->send()) {
echo "Mailer Error: " . $mail->ErrorInfo;
} else {
echo "Message sent!";
}
*Problem Arrises when only text is mailed is ok But html content is Not mailed using Phpmailer library.
*in this code i have send text its send with no error but problem in sending html
$msg = 'my html and php code that format the mail';
$body= preg_replace('/\[\]/','',$msg);
$mail->msgHTML($body);
$data='<table border=1px solid>'.'<tr>'.'<td>'.'EMPLOYEE NAME'.'<td>'.'TO DATE'.'</td>'.'<td>'.'FROM DATE'.'</td>'.'<td>'.'LEAVETYPE'.'</td>'.'<td>'.'REASON'.'</td>.';
You Write Html Tags In Adding Way.
if you have any doubt ask me.
my Full code is
$mail->MsgHTML("$data");
include "classes/class.phpmailer.php"; // include the class name
$pa="SELECT DISTINCT PARENT_ID FROM ORGCHART";
$pa2=odbc_exec($conn,$pa);
while(odbc_fetch_row($pa2))
{
$parentid=odbc_result($pa2,"PARENT_ID");
$c=better_odbc_num_rows($conn,$parent);
$leave2=odbc_exec($conn,$parent);
$lv='';
$cv='';
$ov='';
$hr="<table border=1px solid>"."<tr>"."<td>"."EMPLOYEE NAME"."<td>"."TO DATE"."</td>"."<td>"."FROM DATE"."</td>"."<td>"."LEAVETYPE"."</td>"."<td>"."REASON"."</td>.";
while(odbc_fetch_row($leave2))
{
$todate=odbc_result($leave2,"TODATE");
$todate=date('d-M-Y',strtotime($todate));
$fromdate=odbc_result($leave2,"FROMDATE");
$fromdate=date('d-M-Y',strtotime($fromdate));
$lv.="<tr>"."<td>".odbc_result($leave2,"FIRSTNAME").
"</td>"."<td>".$todate."</td>"."<td>".$fromdate."</td>"."<td>".
odbc_result($leave2,"LEAVETYPE")."</td>".
"<td>".odbc_result($leave2,"REASON")."</td>"."</tr>"."</br>";
}
if($c>0)
{
$ema="SELECT EMAIL FROM EMPLOYEE WHERE EMP_ID=$parentid";
$ema=odbc_exec($conn,"$ema");
$email=odbc_result($ema,"EMAIL");
$mail = new PHPMailer(); // create a new object
$mail->IsSMTP(); // enable SMTP
$mail->SMTPDebug = 1; // debugging: 1 = errors and messages, 2 = messages only
$mail->SMTPAuth = true; // authentication enabled
$mail->SMTPSecure = 'tls'; // secure transfer enabled REQUIRED for hotMail
//$mail->SMTPSecure = 'ssl';// secure transfer enabled REQUIRED for GMail
$mail->Host = "smtp.gmail.com";
$mail->Port = 587; // or 587
$mail->STARTTLS = 1;
$mail->IsHTML(true);
$mail->Username = "";
$mail->Password = "";
$mail->SetFrom("");
$mail->Subject = "eLeave";
$mail->Body = "eLeave Tracking System";
$mail->MsgHTML("$hr.$lv");
$mail->AddAddress("");
if(!$mail->Send()){
echo "Mailer Error: " . $mail->ErrorInfo;
}
else{
echo "Message has been sent";
}
}
}
?>

Categories