Variables inserted into email message from database - php

So I am sending an email in codeigniter where the message is coming from the database.
What I am wanting to do, is put the posted variables into the html formatted email in the database.
For sending the email I have the following in my controller:
$this->load->library('email');
$this->load->model('cms');
$message = $this->cms->Order_Email();
$this->email->from('info#candykingdom.org', 'Candy Kingdom');
$this->email->to($this->input->post('billingEmail'));
$this->email->subject('Order Confirmation');
$this->email->message($message->content);
$this->email->send();
Now a portion of my email that comes from the database is:
<td>
<p>Hi</p>
<p>Sometimes all you want is to send a simple HTML email with a basic design.</p>
<h1>Really simple HTML email template</h1>
...
I am trying to make the <p>Hi</p> line turn into: <p>Hi John,</p> I have tried changing that line to the following:
<p>Hi <?php echo $this->input->post('billingFname'); ?>,</p>
as well as:
<p>Hi '.$this->input->post('billingFName").',</p>
But in the completed and sent email it displays just like the above in the email. Without replacing the php with the actual variable.
So what I am asking is, what do I type in the stored email message to make the php code replace the php with the actual variable?
For examples, let's use John as $this->input->post('billingFName');
Just a thought
Maybe this would be better achieved with a templating library? like this:
https://github.com/philsturgeon/codeigniter-template

A common approach I've seen is using vars you substitute via str_replace:
The html of your email has some vars you know to substitute, as #USERNAME#. In your db you store
<td>
<p>Hi #USERNAME#</p>
<p>Sometimes all you want is to send a simple HTML email with a basic design.</p>
<h1>Really simple HTML email template</h1>
Then, you change #USERNAME# via a str_replace when you get it from the DB:
$message->content = str_replace( '#USERNAME#', $var_with_username, $message->content );
You may even use arrays in your str_replace, to subsitute as many vars as you want, check http://www.php.net/manual/en/function.str-replace.php#refsect1-function.str-replace-examples for more info.

Related

How to send email to two different email address in codeigniter

I am trying to send an email to two different email address using codeigniter email library.
$mail_array = array($email_address, 'example#yahoo.com');
$this->email->to($mail_array);
I have created an array which contains two email address.
The problem here is that the mail is sent only to one email address which is $email_address and not the other.
Can you guys help me on this.
Looks like your code is just fine but as to method accept an array or comma separated string, try change to comma separated string:
$this->email->to("$email_address, example#yahoo.com");
Note: Make you using real email instead of example#yahoo.com and see the documentation in case you missing anything.
Try the following code:
$mail_array = array($email_address, 'example#yahoo.com');
foreach($mail_array as $email) {
$this->email->to($email);
}
You can add second email to CC like,
$this->email->cc('email#email.com');
In CodeIgniter, sending email is not only simple, but you can configure it on the fly or set your preferences in a config file.
$this->email->to()
Sets the email address(s) of the recipient(s). Can be a single e-mail,
a comma-delimited list or an array:
$this->email->to('someone#example.com');
$this->email->to('one#example.com, two#example.com, three#example.com');
$this->email->to(
array('one#example.com', 'two#example.com', 'three#example.com') );
For more reference see this link - http://www.codeigniter.com/user_guide/libraries/email.html#class-reference
Hope this will help you !!

Sending Html page as body of Mail in php with variable values

I have an html page uploaded on my server as payment_receipt.html;
I am using phpmailer to send an emai. This receipt i have to send as body of the Email.
Simply
$Content = file_get_contents("somefile.html"))
can do the trick.
However i need to set values like Amount, Client name etc.
They are placed inside html as
<div class="customerName">Dear{Customer Name}</div>
<div class="confirmation">This email confirms your purchase of following services:</div>
Etc.
How can i set these values in my html before sending it as a body of mail.?
If you always know what the strings you need to replace will be, run a str_replace or similar on $Content
$Content = str_replace('{Customer Name}', $replacement_variable, $Content);
You can do it like this with multiple variables
$newText = str_replace(["{Name}", "{Adress}"], ["Charles", "Street X"], $oldText);

Parsing values in php

so I have a table in which I have email templates, and these email templates can be later fetched for sending emails.
The structure is :-
for_status subject message
int text text
An example entry is :-
for_status = 1,
subject = Transaction Status Changed,
message = Hi $user->firstname, this is a test message.
Ok, so the problem is, when I send the email with the current message and subject, it displays in the email Hi $user->firstname, this is a test message
Instead of showing, Hi thefirstname here, this is a test message.
I'm fetching user details successfully on the same page in the $user variable.
What's going wrong here?
When you say "table of email templates", is the actual text of the email template in some sort of database?
If this is the case and you have $user->firstname in the database, I'm pretty sure its going to spit that out directly.
You need something whats called placeholders. You need to decide what to have as a place holder, I personally use the following:
{%first_name%}, this is a test message.
Then in your PHP code you just have an array of placeholders & values like this:
$arr = array(
'{%first_name%}' => $user->firstname,
);
//and now replace the body
$body = str_replace(array_keys($arr), $arr, $body);
There is a better way of doing this by using already written libraries or using Regular Expression to correctly parse, but I will leave that up to you to figure it out.
PHP will only perform the substitution for you on strings you have coded into your own PHP files, not those that have come from a database or any other source. If it did, that would be a massive security risk!
You will need to perform substitution on your template yourself.
// $message is: Hi %{userFirstName}, this is a test message.
$message = str_replace('%{userFirstName}', $user->firstname, $message);

How to input table html to PHP email code

This is my current code:
and I want to add a number of tables to change the design of the email, I am very new to PHP and ZEND any help would be great thanks.
As Mike Brant said, you can create your HTML then copy in inline. However you will then need to ensure that the email is sent with the proper mime-type so that the user's email reader knows to render as HTML and not as plain text. It isn't that hard, but I found that the PEAR mail and mail_mime libraries really make it even easier and more obvious what's being done. There are also some 3rd party email apis, for example I've had good success on one project using http://swiftmailer.org/
The best way to start is to just layout your email in HTML the way you want it and then just copy into your HEREDOC section and replace the content with the variables.
Create one (zend)layout for your e-mails like you do it for your website. Best with html 4.0 doctype. Avoid CSS. Most E-Mail Clients cannot render it correctly. If you have to use CSS, embed it into style-tags (no external content) and embed the style-Tag into the body. (most web-mailers are dropping the head-section).
Now create views for every mail-type you want to send (e.g.: registration, pw-lost,...)
assign the variables to the view and render it into the layout. Render the Layout into Zend-Email Object.
If you want to manage the content, subject, sender,... over an administration-area, just create a table with the following colums:
type (can be registration, pw-Lost...)
Subject
From
To (for mails which are adressed to the admin e.g.: when users post comments)
CC
Bcc
Html-Text (the Text of the e-Mail with Place-Holders for personalzation)
Text (optional plain text containing Place-Holders) you can pack this text additionaly to you html-Mail or just send html or Text Depending on the user settings.
Some extra-colums for attachments (optional)
Now you can adminster the different Mails and drop your views (not the layout).
At least create a mail-class which you can access in that way:
$mail = new My_Mail(My_Mail::PW_LOST);
$mail->bind($userData); // will replace the placeholders in the text
$mail->addTo(...);
$mail->send(); // will replace the placeholders in the text, renders the layout, Sends the mail.
Code-Sample:
I can provide code samples on saturday if you are interested
You can use the Zend_Mail class (Zend/Mail.php) to send emails. The details are in the code sample below:
$mail = new Zend_Mail();
$mail->setBodyText($bodyText);
$mail->setBodyHtml($bodyHtml);
$mail->setFrom($senderAddress, $senderLabel);
$mail->addTo($recipientAddress, $recipientLabel);
$mail->setSubject($subject);
$mail->send();
A question you might have is how the email (text and html) contents are assigned to $bodyText and $bodyHtml. You can create a couple of phtml files one for html content and the other for text. See the code below on how to achieve this:
$this->view->fullname = "John Abc";
$this->view->emaildata = $data //Possibly an array of data from the db
$bodyText = $this->view->render('emails/htmlemail.phtml')
$bodyHtml = $this->view->render('emails/textemail.phtml')
Note: This snippet should be above the previous one.
Hope this answers your questions. Happy coding :)

How to create a script that users can specify an email and send a user a pre-defined email?

So, basically, I'm creating a page where a user can visit, and enter in the following information:
1. Their First Name
2. Their Email
3. Recipient's Email
They then can send a pre-defined email, saying something like the following...
"Hello, {Recipient's email}. {First name} ({Email}) has just sent you a slurp! You can ignore this message, or slurp them back.
[Slurp Them Back] [Slurp Someone Else] [What's A Slurp?]"
The whole part about the Slurp is something that doesn't really matter, it's just the text from the pre-defined email. The text in {...} is taken from the fields on the page, and the text in [...] are just links.
Does anyone have any idea on how to do this? Even if you can't customize the email, and it would just be without the information from the site, help would be appreciated. Thanks.!
Here's an example of what I'm going for...
Example Layout
It's possible to do using the php mail function. You can take input for everything you specified, then use the example here. They show it in a basic and more advanced form.
Interestingly, the first chapter of Head First PHP describes almost exactly this scenario (except that the recipient is fixed). If you want to learn more about PHP you can look into the book; otherwise, their code is online at http://www.headfirstlabs.com/books/hfphp/ (actual code link: http://www.headfirstlabs.com/books/hfphp/code/HeadFirstPHPMySQL_code_ch01.zip)
Sending an email by itself can be done by using the mail() command
mail('to.address#host.com', 'subject', 'message', 'From: from.address#host.com');
The whole code would look something like this:
HTML:
<form action="slurping.php" method="post">
Your name: <input type="text" name="name" /><br />
Your email: <input type="text" name="email" /><br />
Recipient: <input type="text" name="recipient" /><br />
<input type="submit" />
</form>
PHP (slurp.php):
// order of parameters is: to, subject, message body, additional headers
mail(
$_POST['recipient'],
'You just got slurped',
'You\'ve been slurped by '.$_POST['name'].'. Slurp him/her back by visiting http://slurp.com/',
"From: {$_POST['email']}\r\n"
);
This will send out an email like it's coming from the senders email address to the recipient.
There's a lot missing there, though. What you normally want to include is:
Validation of input on the client side (javascript)
Validation of input on the serverside
Clear out and handle right encodings etc
If you want to do it properly however, so that a greater percentage of your users actually receive the email, you should use a 3rd party library to send out emails. I recommend PHP Mailer or Swift Mailer.
Those libraries provide an easy mechanism for you to include HTML in your emails, attachments, allow for easily connecting to SMTP servers and handle all escaping and encoding issues for you.
On top of that they encapsulate everything within an Object oriented approach, so if that's your cup of tea, you'll be happy. Se their websites for more info.
It's pretty funny, I wrote a blog post about the very issue of email deliverability (getting through spam filters) etc: http://arnorhs.com/2011/02/21/delivering-email-with-php/ - It might be helpful to you.
Cheers
On submit you can send a predefine email in php
following is the code sample
assumed that you will have a html page and following is the sample html code
Send Slurp
Enter Your Name:
Enter Your Email:
Enter Recipient's Email:
following is the php code in "="send_email.php"
if ($_SERVER["REQUEST_METHOD"] == "POST")
{
$your_name = $_POST['your_name'];
$your_email = $_POST['your_email'];
$recipients_email= $_POST['recipient_email'];
$email_subject = 'My Slurp';
$email_body = "Hello, $recipients_email. $your_name ($your_email) has just sent you a slurp! You can ignore this message, or slurp them back.
[Slurp Them Back] [Slurp Someone Else] [What's A Slurp?]";
echo $email_body;
// Send Email
mail($recipients_email, $email_subject, $email_body);
}
?>

Categories