Send email with a template using php

Viewed 91075

How can I send an email using php then add a template design in the email? I'm using this:

$to = "someone@example.com";  
$subject = "Test mail";  
$message = "Hello! This is a simple email message.";  
$from = "someonelse@example.com";  
$headers = "From: $from";  
mail($to,$subject,$message,$headers);  
echo "Mail Sent.";  

And it works fine! The problem is just how to add a template.

11 Answers

Yes you can send email using a email template like

$to_email = 'xyz@xzy.com';

// Set content-type header for sending HTML email 
$headers = "MIME-Version: 1.0" . "\r\n"; 
$headers .= "Content-type:text/html;charset=UTF-8" . "\r\n"; 

ob_start();
    require __DIR__.'/email_template.php';
$htmlContent = ob_get_clean();
 
$subject = 'Test Emails';
// Send email 
if( mail( $to_email , $subject, $htmlContent, $headers ) ) {
     echo 'send';
} else { 
echo 'error'; } 

The benefit of this you can also pass variable as you directly use them in your email template file.

If you are using phpmailer then try this on

// Content
$mail->isHTML(true); 
$mail->Subject = 'Newsletter Mail';
$mail->Body = file_get_contents('mail.html');
if (!$mail->send()) {
    echo 'Mailer Error: ' . $mail->ErrorInfo;
}

And if you are using php mail then just need to add

$body= file_get_contents('mail.html');
$headers = 'MIME-Version: 1.0'."\r\n";
$header.="Content-Type: text/html;\n\tcharset=\"iso-8859-1\"\n";
$header .="From:<no-reply@youremail.com>\r\n";

And if you are using CI(Codeigniter) then in my case I'm created mail helper of ci but rest work same

$message = $this->load->view('front/invoice_email',$data, TRUE); //"Hi, 9999999999 \r\n".";
if(!empty($adminEmail)) {
  send_user_mail($adminEmail, $message, $subject);
}

try this

<?php
$to = "somebody@example.com, somebodyelse@example.com";
$subject = "HTML email";

$message = "
<html>
<head>
<title>HTML email</title>
</head>
<body>
<p>This email contains HTML Tags!</p>
<table>
<tr>
<th>Firstname</th>
<th>Lastname</th>
</tr>
<tr>
<td>John</td>
<td>Doe</td>
</tr>
</table>
</body>
</html>
";

// Always set content-type when sending HTML email
$headers = "MIME-Version: 1.0" . "\r\n";
$headers .= "Content-type:text/html;charset=UTF-8" . "\r\n";

// More headers
$headers .= 'From: <webmaster@example.com>' . "\r\n";
$headers .= 'Cc: myboss@example.com' . "\r\n";

mail($to,$subject,$message,$headers);
?>
Related