I have an email template which i am saving in database. My problem is some part of message are variable means these data are coming from current user data.
For Example My Template is
$message="This is test for $username. I am sending mail to $email."
here $username and $email is coming from current users and it is varying from user to user.
So problem is how to save it in database so i can use it as variable on php page later.
anybody have any idea please help me.your help would be appreciated.
If you really need to store whole template in database, you can save it using your own created constants e.g. [USERNAME], [EMAIL] and then in php script just use str_replace() on them.
$messageTemplate = 'This is test for [USERNAME]. I am sending mail to [EMAIL].';
$message = str_replace(array('[USERNAME]', '[EMAIL]'), array($username, $email), $messageTemplate);
But you can also divide this string and concatenate it with variables from database as follows:
$message = 'This is test for ' . $username . '. I am sending mail to ' . $email . '.';
You can use something like this:
$input = "This is test for {username}. I am sending mail to {email}.";
$tokens = array("username" => $username, "email" => $email);
$tmp = $input;
foreach($tokens as $key => $token)
{
$tmp = str_replace("{".$key."}", $token, $tmp);
}
echo $tmp;
The variables in the string will not be evaluated as variables automatically just because you are adding it to your php scope. You need to eval the string in order for the variables to be replaced:
$username = 'test';
$email = 'test#test.com';
$str = "This is a test for $username. I am sending mail to some person $email.";
echo $str. "\n";
// This is a test for $username. I am sending mail to some person $email.
eval("\$str = \"$str\";");
echo $str. "\n";
// This is a test for test. I am sending mail to some person test#test.com.
For more information, see http://php.net/manual/en/function.eval.php
Related
I got a plugin (kind of sign up form), that offers developers some actions/hooks to add their own stuff. Inside the plugin the function is called like this:
// Allow devs to hook in
do_action( 'after_record_action', $result, $data, $format );
I guess that $data is an array storing the form data. After a visitor uses the signup form I want to send a mail containing $data using wp_mail()
How can I execute the following script using after_record_action? Do I need to add this inside my functions.php?
// get data from $data[] array
$data['email'] = $email;
$data['key'] = $key;
// use $data to create a personalized mail
$to = $email;
$subject = "Wordpress Test";
$content = "Hi, this us your key:" . $key . "Enjoy using it!";
// send mail using wp_mail
$status = wp_mail($to, $subject, $content);
I appreciate any help in combining these, as I am not too experienced using php.
Add following code into your currently active theme's functions.php file:
add_action('after_record_action', 'marian_rick_custom_action', 10, 3);
function marian_rick_custom_action ($result, $data, $format){
// get data from $data[] array
$email = $data['email'];
$key = $data['key'];
// use $data to create a personalized mail
$to = $email;
$subject = "Wordpress Test";
$content = "Hi, this us your key:" . $key . "Enjoy using it!";
// send mail using wp_mail
$status = wp_mail($to, $subject, $content);
}
if you are interested, how all this really works, check the official docs here
I am working on a massmail script which sends an e-mail to every e-mail id present in a particular database.
But there is some issue.
Like I have following database:
id email link
1 a#bc.com bc.com
2 b#cd.com cd.com
And suppose the mail content is : 'Testing this script'
The scripts sends email to a#bc.com perfectly but second time it sends the email, i.e to b#cd.com the content gets doubled.
I mean the second recipient receives an e-mail like this :
Testing this script
Testing this script
The third recipient receives an e-mail with the content repeat three times and the fourth one receives it with four times and so on.
The script grabs e-mail addresses from the email field in the database and sends e-mail to them.
My Code:
<?
include "header.php";
include "config2.php";
$subject="Massmail";
$headers .= "Content-type:text/html;charset=iso-8859-1" . "\r\n";
mysql_connect($server, $db_user, $db_pass)
or die ("Database CONNECT Error");
$resultquery = mysql_db_query($database, "select * from $table");
while ($query = mysql_fetch_array($resultquery))
{
$mailto=$query[$table_email];
$domain=$query[$table_link];
$domain2 = str_replace(array('http://','HTTP://','Http://'), '',$domain);
$handle = fopen("http://$domain2","r") or die("Unable to open link ( $domain ). <a href='javascript:history.go(-1);'>Go back</a> and please try again ");
$contents = '';
while (!feof($handle)) {
$contents .= fread($handle, 8192);
$contents = str_replace('window.location = "/abc.html"','window.location = ""',$contents);
$contents = mb_convert_encoding($contents, "HTML-ENTITIES", "auto");
}
$i = md5(uniqid(rand(), true)) . '.' . html;
$fh = fopen("/home/host/public_html/content/$i", "w");
fwrite($fh, $contents);
fclose($fh);
$filename = '/files/$i';
$message1 .= "Testing Mail Script Version 2";
mail($mailto, $subject, $message1, $headers, "-f" . 'noreply#domain.com');
echo 'Mail sent to '.$mailto.'<br>';
sleep($seconds);
}
include "footer.php";
?>
I have tried to echo the mail that has to be sent and I get this:
To: a#bc.com
Subject: Massmail
Message:
Testing mail script
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
to: b#cd.com
Subject: Massmail
Message:
Testing mail scriptTesting mail script
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
Your help will be greatly appreciated. Thanks in advance
In the code line: $message1 .= "Testing Mail Script Version 2"; the period is a concatenate, so each time you loop it, you duplicate the message another time.
Agreed. Sounds like your loop is not functioning correctly? If you can't post the full code, try to post an abstraction for us to diagnose your issue.
If you cant, I would look into looping based on the number of email address you have, not some arbitrary counter. That might help you out.
Suppose this is your table. With id, email, link, message structured as:
id email message
1 a#test.com hello, how are you doing..
2 b#test.com hey, dude this is me..
3 c#test.com we are sending you this...
Now, let's assume you have 100 records. What I would do is (assuming $result is a mysql array returning all the results from mysql ex SELECT * FROM mail...)
I would try:
for($i=0; $i <= count($result); $i++){
$send = mail($result['to'], $result['subject'],
$result['message'], $result['headers']);
if(!$send){
echo 'e-mail, sending has stopped';
break;
}
else{
echo 'all e-mails are sent successfully'; }
}
Never mind, I fixed it. #Pirion's post helped me. I changed
$message1 .= "Testing Mail Script Version 2";
to
$message = "Testing Mail Script Version 2";
And everything worked perfectly. Thank You So Much Guys For Helping Me Out.
I am trying to use email piping with PHP.
I have it working except I can't get the 'To' field.
I am using the following PHP code:
#!/usr/bin/php -q
<?php
// read from stdin
$fd = fopen("php://stdin", "r");
$email = "";
while (!feof($fd))
{
$email .= fread($fd, 1024);
$to1 = explode ("\nTo: ", $email);
$to2 = explode ("\n", $to1[1]);
$to = str_replace ('>', '', str_replace('<', '', $to2[0]));
}
fclose($fd);
mail('email#example.com','From my email pipe!','"' . $to . '"');
?>
If I use a email address (for example: john#smith.com) and send a email to my email address that is forwarded to my PHP piping script (pipe.php) I want it to be able to get who the email was sent to.
For Example:
john#smith.com emails my forwarding email that goes to my PHP piping script (bob#example.com) I want it to return just the bob part only without the #example.com
What happens now is that it returns the whole email address such as "bob#example.com" and I want it to only return bob (without any talking marks).
I have tried using this:
$to = $to.split("#");
but I seem to get an error that says: split() expects at least 2 parameters.
That gets sent to the person who sent the email.
Does anyone know how to do this or know what I might be doing wrong?
This is my first time using Piping in PHP, so if I am doing something wrong please let me know.
Ended up using:
$to1 = explode ("\nTo: ", $email);
$to2 = explode ("\n", $to1[1]);
$to = str_replace ('>', '', str_replace('<', '', $to2[0]));
list($toa, $tob) = explode('#', $to);
then changed the mail to:
mail('email#example.com','From my email pipe!','"' . $toa . '"');
I am using Postmark to send emails.
But postmark allows you to set a URL to process bounced emails.
I want to use this, but don't know how to get and handle the data.
My API works but I don't know how to retrieve the data postmark sends to my API.
<?php
class BackendBillingAPI
{
public static function postmarkBounceHook()
{
$log = new SpoonLog('custom', PATH_WWW . '/backend/cache/logs/billing');
// logging when we are in debugmode
if(SPOON_DEBUG) $log->write('Billing post (' . serialize($_POST) . ') triggered.');
if(SPOON_DEBUG) $log->write('Billing get (' . serialize($_GET) . ') triggered.');
if(SPOON_DEBUG) $log->write('Billing _REQUEST (' . serialize($_REQUEST) . ') triggered.');
}
}
Any thoughts/ideas?
You'd need to parse the json data inside the POST, and you can't rely on _POST apparently (since this is not a multipart form, see this for more info)
Here's a simple code that grabs a few parameters from the postmark bounce and generates an email. You can grab the parameters and do whatever else you need to of course
<?php
$form_data = json_decode(file_get_contents("php://input"));
// If your form data has an 'Email Address' field, here's how you extract it:
$email_address = $form_data->Email;
$details = $form_data->Details;
$type = $form_data->Type;
// Assemble the body of the email...
$message_body = <<<EOM
Bounced Email Address: $email_address
Details: $details
Type: $type
EOM;
if ($email_address) {
mail('ENTER YOUR EMAIL ADDRESS',
'Email bounced!',
$message_body);
}
?>
I'm using PHP for sending an e-mail. The values in the e-mail are depending on the inputs of a form. But for some reason, the mail is suddenly not sending. It did before. What's wrong with my code?
Orders are placed correctly in the database, so no error there.
if ($order->addOrder($_DB)) {
$user = "SafetyCam.be";
$verzonden = FALSE;
$firstname = $_POST['firstname'];
$lastname = $_POST['lastname'];
$address = $_POST['address'];
$zip = $_POST['zip'];
$place = $_POST['place'];
$country = $_POST['country'];
$phone = $_POST['phone'];
$email = $_POST['email'];
$twogig = $_POST['vn_qty'];
$fourgig = $_POST['ja_qty'];
$total = $_POST['total'];
$totaal = (($twogig * 50) + ($fourgig *80) + 2.5);
$headers = 'From: info#something.be';
$to = 'me#gmail.com';
$subject = 'Bevestiging bestelling';
$message = 'Hello $firstname,
You placed the following order on our website.
- $twogig x 2GB SafetyCams ordered
- $fourgig x 4GB SafetyCams ordered
+ shippingcosts (2,5 EUR)
The total cost for this order amounts to $totaal EUR.
Your products will be delivered as quickly as possible after receipt of your payment.
Please transfer the order amount of $totaal EUR into account X.
After payment, the products will be sent to the following address:
$firstname $lastname
$address
$zip $place
$country
We hope you will be very happy with your purchase.
Sincerely yours";
if (mail($to, $subject, $message, $headers)) {
$verzonden = TRUE;
$feedback = '<div class="feedbackheader">Thanks</div><br / >';
} else {
$verzonden = FALSE;
$feedback = '<div class="feedbackheader">Error!</div>'; }
}
else {
$feedback = '<div class="feedbackheader">Error!</div>';
}
}
Why do you open your mail $message with a single quote and end it in a double quote.
You should open and end with both double quotes, especially since you use PHP variables inside.
$message = 'Hello $firstname"; //Wrong
$message = "Hello $firstname"; // Works
You've opened the "message" string with an apostrophe ' but tried to close it with a quotation mark ". The SO syntax highlighter gives it away!
You have started your variable $message = 'Hello $firstname, with single quote and end it with double quote, what you need to do is just make
$message = "Hello $firstname
if you put it in single quote php wont scan your variable content for varible like $firstname
Your $message variable starts the string with a ' but ends it with a ", so all the code after it is included in the variable until another ' which happens when your defining $feedback.
Basically you are not closing the string, and therefore your entire code is being changed. If you are using color coding you should have seen this (I can see it from your question).
Also, if you are using single quotes, you cannot use inline variables.
$var = 1;
echo '$var'; // ouput: $var;
echo "$var"; // output: 1
You start your message-string with a single quote (') and try to end it with a double quote, thus your logic is parsed incorrectly.
I use SwiftMailer:
require_once('../lib/swiftMailer/lib/swift_required.php');
function sendEmail(){
//Sendmail
$transport = Swift_SendmailTransport::newInstance('/usr/sbin/sendmail -bs');
//Create the Mailer using your created Transport
$mailer = Swift_Mailer::newInstance($transport);
$body="Dear $fname,\n\nYour job application was successful. \n\nYours,\n\nEamorr\n\n\n\n\n\n\n";
//Create a message
$message = Swift_Message::newInstance('Subject goes here')
->setFrom(array($email => "no-reply#yourdomain.com"))
->setTo(array($email => "$fname $lname"))
->setBody($body);
//Send the message
$result = $mailer->send($message);
}