How to include a call to a file in PHP mail() function - php

I have the following function for sending an email:
function send_email($email){
$subject = "TITLE";
$message = "HERE IS THE MESSAGE";
// 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: <emaily>' . "\r\n";
mail($email,$subject,$message,$headers);
}
Instead of $message being a string, I want to call in the file email.html which holds my template.
I have added this:
require 'email.html';
But how can I call in the file?
$message = [call in email.html here]

Require is used when you want to call functions within another php file, or when you want to include some data to an HTTP response.
For this problem, file_get_contents('email.html') is the preferred option. This would be the method I would use:
function send_email($email){
$subject = "Subject of your email";
$message = "";
if(file_exists("email_template.html")){
$message = file_get_contents('email_template.html');
$parts_to_mod = array("part1", "part2");
$replace_with = array($value1, $value2);
for($i=0; $i<count($parts_to_mod); $i++){
$message = str_replace($parts_to_mod[$i], $replace_with[$i], $message);
}
}else{
$message = "Some Default Message";
/* this likely won't ever be called, but it's good to have error handling */
}
// 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: <doNotReply#myDomain.com>' . "\r\n";
$headers .= "To: <$email>\r\n";
$header .= "Reply-To: doNotReply#myDomain.com\r\n";
mail($email,$subject,$message,$headers);
}
I modified your code a little bit and added in both the file_get_contents and file_exists. file_exists confirms that the file is there. If it's not, it avoids the potential error from trying to read it in and can be changed to use some default. My next addition was a for loop. In the $parts_to_mod array, enter in the default values from the template that need to be replaced. In the $replace_with array, put in the unique values that you want to replace parts of the template with.
As an example where I use this, I have a template URL for one of my programs that says id=IDENTIFIER&hash=THEHASH so in my program, my parts_to_mod says $parts_to_mod = array("IDENTIFIER", "THEHASH"); and my replace_with says $replace_with = array($theUsersIdentifier, $theUsersHash);. It then enters the for-loop and replaces the those values in parts_to_modify with the values in replace_with.
Simple concepts and they make your code much shorter and easier to maintain.
Edit:
Here is some sample code:
Let's the say the template is:
<span>Dear PUTNAMEHERE,</span><br>
<div>PUTMESSAGEHERE</div>
<div>Sincerely,<br>PUTSENDERHERE</div>
So, in your php code you'd say:
$parts_to_mod = array("PUTNAMEHERE", "PUTMESSAGEHERE", "PUTSENDERHERE");
$replace_with = array($name, $theBodyOfYourEmail, $whoYouAre);

just use file_get_contents('email.html') This method returns a string with the file contents

You can use this function to call custom email template.
function email($fields = array(),$name_file, $from, $to) {
if(!empty($name_file)) {
$mail_tem_path = 'templates/mails/mail--'.$name_file.'.php'; //change path of files and type file.
if(file_exists($mail_tem_path)) {
$headers = "MIME-Version: 1.0". "\r\n";
$headers .= "Content-Type: text/html;charset=UTF-8". "\r\n";
// Additional headers
$headers .= "From:".$fields["subject_from"]." <$from>". "\r\n";
$headers .= "Content-Transfer-Encoding: 8Bit". "\r\n";
$message = file_get_contents($mail_tem_path);
$message = preg_replace("/\"/", "'", $message);
foreach ($fields as $field) {
// Replace the % with the actual information
$message = str_replace('%'.$field["name"].'%', $field["value"], $message);
}
$send = mail($to, $fields["subject"], $message, $headers);
} else {
$send = mail($to, "Error read mail template", "Contact with admin to repair this action.");
}
} else {
$send = mail($to, "Error no exist mail template", "Contact with admin to repair this action.");
}
return $send;
}
Template html
<html>
<body>
TODO write content %value_on_array%
</body>
</html>
Array and execute function.
$fields = array(
"subject" => "tienda_seller_subject",
"subject_from" => "tienda_email_subject_from",
0 => array(
"name" => "value_on_array",
"value" => "result before change"
),
);
//email($fields = array(),$name_file, $from, $to);
email($fields, 'admin', 'owner#email.com', 'client#email.com');
Result

Related

php mail returns FALSE while error_get_last() returns NULL

Like the title says, mail returns FALSE to I call error_get_last() and it returns a NULL. The email is never received. The thing is, nearly identical code in another page on this site has no problem sending an HTML email, so the server must be okay.
I searched and found this question "PHP mail() returns false but no error is logged", but the answer doesn't seem to apply in my case.
My php code is:
<?php
$MSG_Info = array(
'', // 0 = Sender's name
'', // 1 = Sender's email address
'', // 2 = Subject of the message
'');// 3 = The message itself
$MSG_SendTo ='XXXX#yahoo.com';
function GetMessageText()
{
global $MSG_Info;
return
"<blockquote>".
"Name: ".$MSG_Info[0]."<br />".
"Email: ".$MSG_Info[1]."<br />".
"Subject: ".$MSG_Info[2]."<br />".
"Message: ".wordwrap($MSG_Info[3], 70, "\r\n")."<br />".
"</blockquote>";
}
function GetHTMLHeader()
{
return
'<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">'.
'<html>'.
'<head>'.
'<meta http-equiv="Content-Type" content="text/html;charset=utf-8">'.
'<title>Marguerite Gabe Braun</title>'.
'</head>'.
'<body>'.
'<p><font size="+2" color="#0000AA">'.
'<i>A Message from Marguerite’s Web Site</font></i></p>';
}
function SendMessageEmail($Dest)
{
global $MSG_Info, $MSG_SendTo;
$from = $MSG_SendTo;
$subject = $MSG_Info[2];
$message = GetHTMLHeader();
switch ($Dest)
{
case 1:
$to = $MSG_SendTo;
$replyto = $MSG_Info[1];
$message .= "<p>".$MSG_Info[0]." has sent you a message from your web site.</p>\n";
break;
case 2:
$to = $MSG_Info[1];
$replyto = $MSG_SendTo;
$message .= "<p>Here is the message you sent to Marguerite Gabe Braun from her web site.</p>\n";
break;
default:
$to = $MSG_SendTo;
$replyto = $MSG_SendTo;
$message .= "<p>".$MSG_Info[0]." has sent you a message from your web site.</p>\n";
}
$message .= "<p>".GetMessageText()."</p>\n"."</body></html>";
$headers = "MIME-Version: 1.0" . PHP_EOL;
$headers .= "Content-type: text/html; charset=iso-8859-1" . PHP_EOL;
$headers .= "From: " . $from . PHP_EOL;
$headers .= "Reply-To: " . $replyto . PHP_EOL;
// Send the email.
error_reporting(E_ALL);
$MSG_Result = mail($to, $subject, $message, $headers);
if ($MSG_Result)
{
$MSG_Error = NULL;
}
else
{
$MSG_Error = error_get_last();
}
return $MSG_Error;
}
?>
I've inserted all kinds of code (not shown here) to verify that I'm not screwing up the email addresses, that mail() is indeed returning FALSE, and error_get_last() is returning NULL, that the correct information is being passed in POST, etc.
Thanks in advance.
Edit.
Brute force debugging, commenting out one line at a time, narrowed it down the the line in the header where I specify "From:". If I comment out that line the mail sends and it says it is from the webmaster at my site.
So I test more and it looks like the word "From:", or any line that starts with that, is removed from my message. So strange. See the code below. The code for $message for the Reply-to lines, the line with three "froms" in it, and the simple $from line show in the message in my email. All others are missing. Or maybe this is clearer. Message lines 2, 5, 6, 7, 8, and 10 show in my message. The others, which all start with "From:", do not. It's the dangest thing.
<?php
$message .= "From: ".$from."\r\n";
$message .= "Reply-To: ".$replyto."\r\n";
$message .= "From: "."\r\n";
$message .= "FROM: "."\r\n";
$message .= "From, from, FROM: "."\r\n";
$message .= "Reply-To: ".$replyto."\r\n";
$message .= $from."\r\n";
$message .= "Reply-To: ".$replyto."\r\n";
$message .= "From: ".$from."\r\n";
$message .= "Reply-To: ".$replyto."\r\n";
$message .= "<p>".GetMessageText()."</p>\n"."</body></html>";
// This commented-out code is used on another page and with works correctly.
// $headers = "MIME-Version: 1.0\r\n";
// $headers .= "Content-type: text/html; charset=iso-8859-1\r\n";
// $headers .= "From: ".$from."\r\n";
// $headers .= "Reply-To: ".$replyto."\r\n";
$headers = "MIME-Version: 1.0" . PHP_EOL;
$headers .= "Content-type: text/html; charset=iso-8859-1" . PHP_EOL;
// $headers .= "From: " . $from . PHP_EOL;
$headers .= "Reply-To: " . $replyto . PHP_EOL;
// Send the email.
$MSG_Result = mail($to, $subject, $message, $headers);
if ($MSG_Result)
{
$MSG_Error = NULL;
}
else
{
$MSG_Error = error_get_last();
if ($MSG_Error == NULL) {$MSG_Error[0] = "Unknown mail() error.";}
}
return $MSG_Error;
}
?>

PHP Mail Function waits and not working with foreach loop

I am trying to send mail to all users that have no created reports in one month, also trying to send mail to this users with foreach loop and with mail function, when i refresh one by one then it sends mail one by one, then it works. i want to send mail to all this users in one time.
$from = "xxx#xxx.com";
$subject = "";
$headers = "";
$inc = 0;
foreach($query->result_array() as $row)
{
$inc++;
$to = $row['us_email'];
$to_date = $row['report_date'];
if($to_date != "0000-00-00")
{
$subject = "Hello! (Reports Are Not Created).";
//begin of HTML message
$message = "1 month above you should create reports.";
}
else if($to_date == "0000-00-00")
{
$subject = "Hello! (Generate Reports).";
//begin of HTML message
$message ="generate reports to get more.";
}
$headers = "MIME-Version: 1.0" . "\r\n";
$headers .= "Content-type: text/html; charset=iso-8859-1" . "\r\n";
$headers .= "To: User <".$to.">, Admin <".$from.">" . "\r\n";
$headers .= "From: Complete Online Marketing <".$from.">" . "\r\n";
$headers .= "Reply-To: Recipient Name <".$from.">";
$headers .= "Cc: [email]".$from."[/email]" . "\r\n";
$headers .= "Bcc: [email]".$from."[/email]" . "\r\n";
// now lets send the email.
if(mail($to, $subject, $message, $headers))
{
echo $inc.") ".$row['us_firstname']." ".$row['us_lastname']." - Sending Success...\n";
$ins = array('report_mail'=>'0');
$this->db->update('se_user', $ins, array('us_id' => $row['us_id']));
}
else
{
echo $inc.") ".$row['us_firstname']." ".$row['us_lastname']." - Sending Fail...\n";
}
}

Include a HTML Email Template into PHP Code

I have a really nice looking HTML Template that I now need to implement into my mailing system. I am currently using this to send emails:
$to = $dbuser;
$subject = "Welcome";
$from = "support#mysite.com";
$headers = "From: $from";
$server = "";
ini_set ("SMTP", $localhost);
$url="";
$msg="$url";
$body = Example Text!
mail($to, $subject, $body, $headers);
How would I include a HTML template (along side CSS) directly into the $body variable of my php email form?
I've done quite a bit of research but I can't find anything substantial.
Your missing the header required for the email client to interpret the message as HTML. Add the following to your headers:
$headers = "From: " . $from . "\r\n";
$headers .= "MIME-Version: 1.0" . "\r\n";
$headers .= "Content-type:text/html;charset=iso-8859-1" . "\r\n";
One way of doing this that I have used in the past is to create the page as you would normally (using html/php etc) and then use file_get_contents($url) like so:
$body = file_get_contents("http://mydomain.com/emailtemplates/template.php?name=John Doe&subject=Hello");
Because you are using http:// the php is executed rather than pulled into the template, simple but effective!
I also would advise you to use inline css and don't be afraid to use tables!
http://php.net/manual/en/function.mail.php - example #5
also remember that in HTML emails you're strongly advised to use inline CSS and old-school HTML formatting where possible to assure maximum compatibility with different email clients. Also no divs - just plain old good table-s
First of all you need to add some headers, in order for the HTML to display correctly.
Taken from the mail() PHP documentation, this is how you do it:
$headers .= 'Content-type: text/html; charset=iso-8859-1' . "\r\n";
After that, I'm assuming $body is where the text should be, so it's a matter of putting all the HTML between quotation marks (escaping every quotation mark in your HTML with a backwards slash), and that's pretty much it.
I wrote this for myself yesterday:
Create your html and put it in a file named "./email.html" Copy and
paste the code below to a php file in the same dir as the html file.
Modify the image names if you use them in the HTML just do so like so: src="cid:world.jpg"
And thats it...I think. =)
//attachment file paths/names
$files[0] = './world.jpg';
$files[1] = './world2.jpg';
$to = '';
$bcc = "";
$subject = '';
$from = "";
$htmlx = '';
$handle = #fopen("./email.html", "r");
if ($handle) {
while (($buffer = fgets($handle, 4096)) !== false) {
$htmlx .= $buffer;
}
if (!feof($handle)) {
echo "Error: unexpected fgets() fail\n";
}
fclose($handle);
}
$semi_rand = md5(time());
$mime_boundary = "==Multipart_Boundary_x".$semi_rand."x";
$headers = "From: $from \n";
$headers .= "Reply-To: $from \n";
$headers .= 'Bcc: '. $bcc . "\n";
$headers .= "MIME-Version: 1.0\n" . "Content-Type: multipart/mixed;\n" . ' boundary="'.$mime_boundary.'"'."\n";
$headers .= "X-Author: <Timothy Martens>\n";
$message = '--'.$mime_boundary."\n";
$message .= 'Content-Type: text/html; charset=UTF-8'."\n";
$message .= "Content-Transfer-Encoding: 7bit\n\n\n". $htmlx . "\n\n\n";
// preparing attachments
for($i=0;$i<count($files);$i++){
if(is_file($files[$i])){
$message .= "--".$mime_boundary."\n";
$fp = #fopen($files[$i],"rb");
$data = #fread($fp,filesize($files[$i]));
#fclose($fp);
$data = chunk_split(base64_encode($data));
$message .= "Content-Type: application/octet-stream; name=\"".basename($files[$i])."\"\n" .
"Content-Description: ".basename($files[$i])."\n" .
"Content-ID: <".basename($files[$i]).">\n".
"Content-Disposition: attachment;\n" . " filename=\"".basename($files[$i])."\"; size=".filesize($files[$i]).";\n" .
"Content-Transfer-Encoding: base64\n\n" . $data . "\n\n";
}
}
$message .= "--".$mime_boundary."--";
if (mail($to, $subject, $message, $headers)) {
echo 'Your message has been sent.'."\n";
} else {
echo 'There was a problem sending the email.'."\n";
}

$_POST a input value in two parts (explode?)

I'm really new to PHP, so this is probably a pretty dumb question.
I'm using PHP to submit an email form, and would like the email to contain the values of some of the form's inputs. Here's a stripped down version:
<?php
if(isset($_POST['submit'])) {
$to = 'address#gmail.com' ;
$subject = 'Subject';
$headers = 'MIME-Version: 1.0' . "\r\n";
$headers .= 'Content-type: text/html; charset=iso-8859-1' . "\r\n";
$message =
//here are the values that the email will send me
"<p>".$_POST('some-name')."</p>
<p>".$_POST('some-name')."</p>" ;
mail($to, $subject, $message, $headers);
header('Location: ../estimate.html');
} ?>
The value of input some-name is, say, 10-widgets posted from the form.
Here's the question: instead of listing "10-widgets" twice (as the above code will do), how do I list the first part in the first <p> (so it would be "10") and the second part in the second <p> (so it would be "widgets")?
Something like the following seems promising:
$wholeVal = $_POST('some-name');
$partVal = explode("-",$wholeVal);
and then, somewhere, $_POST($partVal[0]); and $_POST($partVal[1]);
But I don't know where this should take place, and anywhere I put it seems to make the whole thing break.
Thanks for your help.
First, you should access $_POST with brackets, like $_POST['some-name']. explode returns an array. So in your example, explode('-', '10-widgets')[0] will return '10' and explode('-', '10-widgets')[1] will return 'widgets'
So your code will be something like this:
<?php
if(isset($_POST['submit'])) {
$to = 'address#gmail.com' ;
$subject = 'Subject';
$headers = 'MIME-Version: 1.0' . "\r\n";
$headers .= 'Content-type: text/html; charset=iso-8859-1' . "\r\n";
$parts = explode('-', $_POST['some-name']);
//here are the values that the email will send me
$message =
"<p>".$parts[0]."</p>
<p>".$parts[1]."</p>";
mail($to, $subject, $message, $headers);
header('Location: ../estimate.html');
}
?>
I know you're looking for functionality at the moment but keep in mind that if you're splitting a string by a "-" it'd be really easy for a script kiddie (or even a well intentioned person for that matter) to use a hyphenated word and your script will break.
Just a heads up :D
Try that
$wholeVal = $_POST('some-name');
$list($ammount, $type) = explode("-",$wholeVal);
Then into your email:
$message = "<p>" . $ammount . "</p><p>" . $type . "</p>" ;
<?php
if(isset($_POST['submit'])) {
$to = 'address#gmail.com' ;
$subject = 'Subject';
$headers = 'MIME-Version: 1.0' . "\r\n";
$headers .= 'Content-type: text/html; charset=iso-8859-1' . "\r\n";
$message =
$wholeVal = $_POST('some-name');
$partVal = explode("-",$wholeVal);
//here are the values that the email will send me
"<p>".$partVal[0]."</p>
<p>".$partVal[1]."</p>" ;
mail($to, $subject, $message, $headers);
header('Location: ../estimate.html');
} ?>

Sending Web Page through Email in php

as in asp we have function to send complete web page in email, which basically save lot of time for developer in creating & sending email
see the following code
<%
Set myMail=CreateObject("CDO.Message")
myMail.Subject="Sending email with CDO"
myMail.From="xxx#example.com"
myMail.To="xxx#example.com"
myMail.CreateMHTMLBody "mywebpage.html",cdoSuppressNone
myMail.Send
set myMail=nothing
%>
as we know that CreateMHTMLBody will get data from mywebpage.html and send it as a body of email.
i want to know does any function like (CreateMHTMLBody) this is available in php ?
if Not can we crate any function if yes, please give me some hints.
Thanks
Example below:
<?
if(($Content = file_get_contents("somefile.html")) === false) {
$Content = "";
}
$Headers = "MIME-Version: 1.0\n";
$Headers .= "Content-type: text/html; charset=iso-8859-1\n";
$Headers .= "From: ".$FromName." <".$FromEmail.">\n";
$Headers .= "Reply-To: ".$ReplyTo."\n";
$Headers .= "X-Sender: <".$FromEmail.">\n";
$Headers .= "X-Mailer: PHP\n";
$Headers .= "X-Priority: 1\n";
$Headers .= "Return-Path: <".$FromEmail.">\n";
if(mail($ToEmail, $Subject, $Content, $Headers) == false) {
//Error
}
?>
To add to Erik's answer, if you want to import a local (or remote!) file instead of specifying the HTML in the code itself, you can do this:
// fetch locally
$message = file_get_contents('filename.html');
// fetch remotely
$message = file_get_contents('http://example.com/filename.html');
Use the output buffer functions of PHP and include the desired webpage. Example:
// Start output buffering
ob_start();
// Get desired webpage
include "webpage.php";
// Store output data in variable for later use
$data = ob_get_contents();
// Clean buffer if you want to continue to output some more code
// in which case it would make sense to use this functionality in the very beginning
// of your page when no other code has been processed yet.
ob_end_clean();
Here's how:
$to = 'joe#example.com';
$subject = 'A test email!';
// To send HTML mail, the Content-type header must be set
$headers = 'MIME-Version: 1.0' . "\r\n";
$headers .= 'Content-type: text/html; charset=iso-8859-1' . "\r\n";
// Put your HTML here
$message = '<html><body>hello world</body></html>';
// Mail it
mail($to, $subject, $message, $headers);
You've just sent HTML email. To load an external HTML file replace $message = '' with:
$message = file_get_contents('the_file.html');

Categories