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

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);

Related

How to add unsubscribe link in mail when using Bcc

I am using the following code in controller to send newsletters to subscribers
$body = $model->letter_content;
$to_email = 'admin#site.in';
for($i=0;$i<count($msg_to);$i++){
$maitto = $msg_to[$i];
if($maitto != '')
$headers .= 'Bcc:'.$maitto."\r\n";
}
mail($to_email,$subject,$body,$headers);
the variable '$msg_to' contains all subscriber list as array.
The variable '$body' has the saved static newsletter body..
I am sending the mail to admin and adding all subscribers as 'Bcc' as I dont want to use mail function inside the for loop to send individually to all subscribers.
Now I want to add a link in the mail to allow subscribers to unsubscribe..If i was sending mail individually inside the for loop i could have used something like this inside loop before mail() function
$body .= 'UNSUBSCRIBE'
But since here i am using 'Bcc' is there any other way to do it.
Thank you.
You basically have two options in this case:
You could have the unsubscribe link take them to a page where they enter their email address.
You can find a way to start looping through each user to send the email individually, like you said you don't want to do.
One email can only have one set of content. Therefore, no matter how many people you send it to they all will get the same email.
If you really feel strongly about using the BCC field for everyone, option one will work fine.

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);

php strip html tags and it's data and insert into mysql

I am currently working on a php project that connects to imap and insert emails into MySQL. I added UI to reply to the email by which it canned them together. I am having one issue. If I send an email to someone it send all data fine, if the person reply it reinserts everything again. I would like to just insert the person reply and strip out the rest of the message. how can I do this? Any suggestions?
I tried wrapping the entire insert with < section > tag and tried to use preg_replace to
ignore all it's content but no luck.
This is what my insert looks like
$message=strip_tags($message, "<br><p><u><span><hr>");
$message=preg_replace("/(<br\ ?\/?>)+/", "<br/>", $message);
$message= preg_replace('/<section[^>]*>([\s\S]*?)<\/section[^>]*>/', '', $message);
$message=clean("<br/><hr><u>Received On $rep_date / $from_email</u><br/>$message");
mysql_query("UPDATE USER SET INFO = CONCAT('$message',INFO) WHERE ID='$id'");
The Data stored in MySQL looks like this
<section> <p>Test data</p> etc </section>
This works but just it reinserts everything. Any suggestions?
Is this what you're looking for?
$start = strpos($message,'<section>')+9;
$end = strpos($message,'<section/>');
$content = strip_tags(substr($message,$start,$end),"<br><p><u><span><hr>");
PS: Don't forget to sanitize!

Variables inserted into email message from database

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.

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 :)

Categories