How to send array via email? - php

I have problem to send array from database via email. I´m sure may people have got the same problem. I don´t know how to explain more but here is some script.
$sql="SELECT * FROM tb_xxx WHERE id_prd = '$ref_id_prd'";
$result=mysql_db_query($dbname,$sql);
while ($rs=mysql_fetch_array($result)) {
$ref_id_prd=$rs[ref_id_prd];
$prd=$rs[prd];
$price=$rs[price];
text="$prd <br>$price";
}
$recipient = $iemail;
$subject = "my subject";
$headers = "From: xxx#xxx.com \n";
$headers .= "Reply-To: xxx#xxx.com \n";
$headers .= "MIME-Version: 1.0 \n";
$headers .= "Content-Type: text/html; charset=ISO-8859-1 \n";
$msg = $text;
mail($recipient, $subject, $message, $headers);

You need to accumulate all the array values into a single string for the message body.
$text = "";
while ($rs = mysql_fetch_array($result)) {
$ref_id_prd=$rs[ref_id_prd];
$prd=$rs[prd];
$price=$rs[price];
// Use .= to append to the current value
$text .= "$prd <br>$price\n";
}
To send it, use $text as the message body:
mail($recipient, $subject, $text, $headers);
Note, you will need to do additional formatting on the line below to get it looking the way you want in your HTML email:
$text .= "$prd <br>$price\n";
For example, you could make a list of products:
$text = "<ul>\n";
// inside the while loop...
$text .= "<li>$prd: $price</li>\n";
// After the loop, close the list
$text .= "</ul>"
Update: How to build it into an HTML table:
$text = "";
// Open the table:
$text .= "<table>\n";
// Table header...
$text .= "<thead><tr><th>Product</th><th>Price</th></tr></thead>\n";
// Open the table body
$text .= "<tbody>\n";
while ($rs = mysql_fetch_array($result)) {
$ref_id_prd=$rs[ref_id_prd];
$prd=$rs[prd];
$price=$rs[price];
// Build table rows...
$text .= "<tr><td>$prd</td><td>$price</td></tr>";
}
// Close the table
$text .= "</table>";

Replace your $message variable with $msg
mail($recipient, $subject, $msg, $headers);

Related

Replacing Commas with <br /> and render correctly in sent emails

I have an array that might contain one or multiple items and I want to be able to email it on form submit but have it display each item on a new line, the items are separated by commas.
i.e. the array looks like this 6-7,4-7,2-5,
I have this so far:
$in = $register_order['product_id_array'];
$out = str_replace(',', '<br />', $in);
but the email renders out like:
6-7<br />4-7<br />2-5<br />
and I'd like it to render like:
6-7
4-7
2-5
Thank you!
If it is actually printing out the tag <br />, then you need to set the content-type header to text/html. Or, if the <br /> tag is the only HTML in the email, simply replace it with \r\n - make sure \r\n is in double quotes instead of single.
In order to send HTML emails with PHP do the following :
$to = 'email#example.com';
$subject = 'Hello there this is my email';
$header = "From: " . $name . "\r\n";
$header .= "Reply-To: ". $email . "\r\n";
$header .= "CC: email#example.com\r\n";
$header .= "MIME-Version: 1.0\r\n";
$header .= "Content-Type: text/html; charset=UTF-8\r\n";
$content = '<html><body>';
$content .= 'hello' . '<br />' . 'hello';
$content .= '</body></html>';
mail($to, $subject, $content, $header);
The all important part lies in the header section of the mail. The content type informs that it has to be read as HTML content.
$in = $register_order['product_id_array'];
$out = str_replace(',', '!n', $in);
or
$in = $register_order['product_id_array'];
$out = str_replace(',', '/r/n', $in);
try this code

Trouble with PHPMAIL..Any advice?

Having trouble executing a select and send to all email address in a script.
// Get Employee's Email Address
$getEmail = "SELECT empEmail AS theEmail FROM employees";
$emailres = mysqli_query($mysqli, $getEmail) or die('-1'.mysqli_error());
$col = mysqli_fetch_assoc($emailres);
$theEmail = $col['theEmail'];
// the message
$message = '<html><body>';
$message .= '<h3>New Site Notifications</h3>';
$message .= '<p>'.$noticeTitle.'</p>';
$message .= '<p>'.$noticeText.'</p>';
$message .= '<p>'.$messageText.'</p>';
$message .= '<hr>';
$message .= '<p>'.$emailLoginLink.'</p>';
$message .= '<p>Thank you<br>Bliss Door Supervisors</p>';
$message .= '</body></html>';
$headers = "From: ".$siteName." <".$businessEmail.">\r\n";
$headers .= "Reply-To: ".$businessEmail."\r\n";
$headers .= "MIME-Version: 1.0\r\n";
$headers .= "Content-Type: text/html; charset=ISO-8859-1\r\n";
// use wordwrap() if lines are longer than 70 characters
//$msg = wordwrap($msg,70);
// send email
mail($theEmail," New Site Notification",$message,$headers);
//End Send Mail
For some reason, it only emails the first email in the database but not the other 10+ witihin.
Can anyone see where i'm going wrong? or assist.
Many thanks
Spike
Fetch only pulls one row at a time. Move the fetch into a loop like...
// Get Employee's Email Address
$getEmail = "SELECT empEmail AS theEmail FROM employees";
$emailres = mysqli_query($mysqli, $getEmail) or die('-1'.mysqli_error());
while($col = mysqli_fetch_assoc($emailres)){ //start loop here so each email address is pulled
$theEmail = $col['theEmail'];
// the message
$message = '<html><body>';
$message .= '<h3>New Site Notifications</h3>';
$message .= '<p>'.$noticeTitle.'</p>';
$message .= '<p>'.$noticeText.'</p>';
$message .= '<p>'.$messageText.'</p>';
$message .= '<hr>';
$message .= '<p>'.$emailLoginLink.'</p>';
$message .= '<p>Thank you<br>Bliss Door Supervisors</p>';
$message .= '</body></html>';
$headers = "From: ".$siteName." <".$businessEmail.">\r\n";
$headers .= "Reply-To: ".$businessEmail."\r\n";
$headers .= "MIME-Version: 1.0\r\n";
$headers .= "Content-Type: text/html; charset=ISO-8859-1\r\n";
// use wordwrap() if lines are longer than 70 characters
//$msg = wordwrap($msg,70);
// send email
mail($theEmail," New Site Notification",$message,$headers);
//End Send Mail
}//end loop
Reference: http://php.net/manual/en/mysqli-result.fetch-assoc.php
Returns an associative array that corresponds to the fetched row
From their example:
$query = "SELECT Name, CountryCode FROM City ORDER by ID DESC LIMIT 50,5";
if ($result = $mysqli->query($query)) {
/* fetch associative array */
while ($row = $result->fetch_assoc()) {
printf ("%s (%s)\n", $row["Name"], $row["CountryCode"]);
}

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

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

Php Email Mysql Fetch Array

I have this script to send an email containing information from my database. The user can have 1+ items in the database with it's location. So when I empty the rows that match the user the amount of emails sent equals the number of rows they have. So if they have 8 items in the database it send 8 emails. Each adds an item. So the first email has one item, the second with two items, and so on. I am trying to find a simple way to make it get all the information before sending the email so the customer only gets one email. The logical way would be to echo the information but I can't do that with a php variable. I didn't include the query and database connection in the code below. Any help would be loved.
while ($row = mysql_fetch_array($query)) {
$Items .= $row['Items']. " - Aisle " .$row['Loc']. "<p> </p>";
$to = "example#example.com";
$from = "example#example.com";
$subject = "Test";
$message = "$Items";
$headers = "MIME-Version: 1.0 \r\n";
$headers .= "Content-type: text/html; charset=iso-8859-1 \r\n";
$headers .= "From: example#example.com";
mail($to, $subject, $message, $headers);
}
Just move send function out of cycle:
while ($row = mysql_fetch_array($query)) {
$Items .= $row['Items']. " - Aisle " .$row['Loc']. "<p> </p>";
}
if ($Items != '') {
$to = "example#example.com";
$from = "example#example.com";
$subject = "Test";
$message = "$Items";
$headers = "MIME-Version: 1.0 \r\n";
$headers .= "Content-type: text/html; charset=iso-8859-1 \r\n";
$headers .= "From: example#example.com";
mail($to, $subject, $message, $headers);
}
When you iterate over the items, you should only build a message and not the entire email.. It's hard to do much more than the following without knowing more about your query. I'll give it a shot anyway:
$message = '';
while ($row = mysql_fetch_array($query)) {
$Items = $row['Items']. " - Aisle " .$row['Loc']. "<p> </p>";
$message .= "$Items";
}
$headers = "MIME-Version: 1.0 \r\n";
$headers .= "Content-type: text/html; charset=iso-8859-1 \r\n";
$headers .= "From: example#example.com";
mail($to, $subject, $message, $headers);
Note: I wouldn't implement this code as is. It's meant to serve as an example on how to structure your code.
Your concatenation is wrong, you should first declare your variable as empty outside your loop
$Items = '';
Then start your loop and get all data you need concatenating your variable
while ($row = mysql_fetch_array($query))
{
$Items .= $row['Items']. " - Aisle " .$row['Loc']. "<p> </p>";
}
Now you are ready for send email, outside your loop or you will end up with one email for each cicle. So your code would look like this
$Items = '';
while ($row = mysql_fetch_array($query))
{
$Items .= $row['Items']. " - Aisle " .$row['Loc']. "<p> </p>";
}
$from = "example#example.com";
$subject = "Test";
$message = "$Items";
$headers = "MIME-Version: 1.0 \r\n";
$headers .= "Content-type: text/html; charset=iso-8859-1 \r\n";
$headers .= "From: example#example.com";
mail($to, $subject, $message, $headers);
Then I would like you to remember that mysql_* functions are deprecated so i would advise you to switch to mysqli or PDO

How to send emails to a users friends when the user takes a specific action?

I am using this script below, which works. The only thing is it sends an email to the first email id it gets. The rest are being ingnored. So how do i send email to all the emails. When i tested just the script that is pulling emails, it works, it shows all the emails.
Code:
$sql = "SELECT STRAIGHT_JOIN DISTINCT email from
friend_email_ids WHERE my_id='$id'";
$result = mysql_query($sql);
$query = mysql_query($sql) or die ("Error: ".mysql_error());
if ($result == "")
{
echo "";
}
echo "";
$rows = mysql_num_rows($result);
if($rows == 0)
{
print("");
}
elseif($rows > 0)
{
while($row = mysql_fetch_array($query))
{
$email = $row['email'];
print("");
}
}
$headers = "MIME-Version: 1.0\r\n";
$headers .= "Content-Type: text/html; charset=ISO-8859-1\r\n";
$headers .= "From: $usermail\r\n";
$subject = "$full_name added";
$message = "<html><body>";
$message .= "Hello, <br><br>$full_name posted someth<br><br>";
$message .= "<a href=www.domain.com/signup.php?t=&sign=>Click here.</a><br><br>";
$message .= "</body></html>";
mail("$email", "Subject: $subject",
$message, "$headers" );
echo "";
You are overwriting your $email variable each time through the loop. Instead, you want to create an array, and add the email to the array each time through the loop. When finished, join the email addresses in the array with commas before sending the mail.
So before your loop (maybe after the $rows = ... statement), initialize a new array, like this:
$rows = mysql_num_rows($result);
$emails = array(); /* Add this line */
Then each time through the loop, add the email to the array:
while($row = mysql_fetch_array($query)) {
array_push($emails, $row['email']);
/* ... */
}
Finally, join them with commas in your email send:
mail(implode(',', $emails), "Subject: $subject", $message, $headers);
Alternatively, you can send one separate email to each user like this:
foreach ($emails as $email) {
mail($email, "Subject: $subject", $message, $headers);
}
Try this:
<?php
$headers = "MIME-Version: 1.0\r\n";
$headers .= "Content-Type: text/html; charset=ISO-8859-1\r\n";
$headers .= "From: $usermail\r\n";
$subject = "$full_name added";
$message = "<html><body>";
$message .= "Hello, <br><br>$full_name posted someth<br><br>";
$message .= "<a href='www.domain.com/signup.php?t=&sign='>Click here.</a><br><br>";
$message .= "</body></html>";
$sql = "SELECT DISTINCT email from friend_email_ids WHERE my_id='$id'";
$result = mysql_query($sql) or die ("Error: ".mysql_error());
while($row = mysql_fetch_array($result))
{
mail($row['email'], $subject, $message, $headers);
// for debugging purposes, uncomment the following line
// echo $row['email']
}
Changes:
cleaned up PHP code (removed unused instructions, remove second query which doesn't do anything, removed string vars in " etc.)
corrected HTML link in the email message (it had no quotes on the href attribute)
loop through results to send email for each $row
Here i am attaching code for sending multiple mails and integrating it with your existing code.
You just need to copy paste this code in your page and upload it on some server to test for its workability. I have already tested on my server and it gives multiple mails.
$email = array();
$sql = "SELECT STRAIGHT_JOIN DISTINCT email from friend_email_ids WHERE my_id = '".$id."' ";
$result = mysql_query($sql);
$query = mysql_query($sql) or die ("Error: ".mysql_error());
while($row = mysql_fetch_assoc($query))
{
$email[] = $row['email'];
}
/*
echo "<pre>";
print_r($email);
exit;
*/
$headers = "MIME-Version: 1.0\r\n";
$headers .= "Content-Type: text/html; charset=ISO-8859-1\r\n";
$headers .= "From: $usermail\r\n";
$subject = "$full_name added";
$message = "<html><body>";
$message .= "Hello, <br><br>$full_name posted this mail<br><br>";
$message .= "<a href='www.aadinathtech.com/index.php'>Click here.</a><br><br>";
$message .= "</body></html>";
foreach($email as $key=>$val) {
mail($val, "Subject: $subject", $message, "$headers" );
echo "<br />Mail has been sent to $val<br /><br />";
}
Please revert me back if you still find any problem.
You need to do a small modification by moving the last block of code inside your loop.
Try this:
$rows = mysql_num_rows($result);
if($rows == 0)
{
print("");
}
elseif($rows > 0)
{
while($row = mysql_fetch_array($query))
{
$email = $row['email'];
$headers = "MIME-Version: 1.0\r\n";
$headers .= "Content-Type: text/html; charset=ISO-8859-1\r\n";
$headers .= "From: $usermail\r\n";
$subject = "$full_name added";
$message = "<html><body>";
$message .= "Hello, <br><br>$full_name posted someth<br><br>";
$message .= "<a href=www.domain.com/signup.php?t=&sign=>Click here.</a><br><br>";
$message .= "</body></html>";
mail("$email", "Subject: $subject",
$message, "$headers" );
print("");
}
}
echo "";

Categories