Use HTML formatting in email sent from PHP - php

How can I send HTML formatting through a PHP script? For some reason, it always shows up as <b>Example</b> instead of Example. I'm sure I have to include HTML headers somewhere, I just don't know what needs to be done. I'm a complete PHP nubcake. :)
Here's my PHP script: (rather long, sorry!)
<?php
if(!$_POST) exit;
$name = $_POST['name'];
$email = $_POST['email'];
$phone = $_POST['phone'];
$subject = $_POST['subject'];
$comments = $_POST['comments'];
$verify = $_POST['verify'];
if(trim($name) == '') {
echo '<div class="error_message">You must enter your name.</div>';
exit();
} else if(trim($name) == 'Name') {
echo '<div class="error_message">You must enter your name.</div>';
exit();
}
else if(trim($email) == '') {
echo '<div class="error_message">Please enter a valid email address.</div>';
exit();
} else if(trim($email) == 'Email') {
echo '<div class="error_message">Please enter a valid email address.</div>';
exit();
} else if(!isEmail($email)) {
echo '<div class="error_message">Invalid e-mail address, please try again.</div>';
exit();
}
if(trim($subject) == '') {
echo '<div class="error_message">Please enter a subject.</div>';
exit();
} else if(trim($subject) == 'Subject') {
echo '<div class="error_message">Please enter a subject.</div>';
exit();
}
if($error == '') {
if(get_magic_quotes_gpc()) {
$comments = stripslashes($comments);
}
$address = "mynamehere#mydomainnamehere.com";
$e_subject = '' . $subject . '.';
$e_body = "<b>Name:</b> $name \n\n<b>Subject:</b> $subject \n\n<b>Email:</b> $email \n\n<b>Message:</b> $comments";
$e_content = "";
$e_reply = "";
$msg = $e_body . $e_content . $e_reply;
if(mail($address, $e_subject, $msg, "From: $email\r\nReply-To: $email\r\nReturn-Path: $email\r\n")) {
echo "<div id='success_page'>";
echo "<h1>Email Sent Successfully.</h1>";
echo "<p>Thank you <strong>$name</strong>, your message has been sent!</p>";
echo "</div>";
//echo "</fieldset>";
} else {
echo 'ERROR!';
}
}
function isEmail($email) { // Email address verification, do not edit.
return(preg_match("/^[-_.[:alnum:]]+#((([[:alnum:]]|[[:alnum:]][[:alnum:]-]*[[:alnum:]])\.)+(ad|ae|aero|af|ag|ai|al|am|an|ao|aq|ar|arpa|as|at|au|aw|az|ba|bb|bd|be|bf|bg|bh|bi|biz|bj|bm|bn|bo|br|bs|bt|bv|bw|by|bz|ca|cc|cd|cf|cg|ch|ci|ck|cl|cm|cn|co|com|coop|cr|cs|cu|cv|cx|cy|cz|de|dj|dk|dm|do|dz|ec|edu|ee|eg|eh|er|es|et|eu|fi|fj|fk|fm|fo|fr|ga|gb|gd|ge|gf|gh|gi|gl|gm|gn|gov|gp|gq|gr|gs|gt|gu|gw|gy|hk|hm|hn|hr|ht|hu|id|ie|il|in|info|int|io|iq|ir|is|it|jm|jo|jp|ke|kg|kh|ki|km|kn|kp|kr|kw|ky|kz|la|lb|lc|li|lk|lr|ls|lt|lu|lv|ly|ma|mc|md|mg|mh|mil|mk|ml|mm|mn|mo|mp|mq|mr|ms|mt|mu|museum|mv|mw|mx|my|mz|na|name|nc|ne|net|nf|ng|ni|nl|no|np|nr|nt|nu|nz|om|org|pa|pe|pf|pg|ph|pk|pl|pm|pn|pr|pro|ps|pt|pw|py|qa|re|ro|ru|rw|sa|sb|sc|sd|se|sg|sh|si|sj|sk|sl|sm|sn|so|sr|st|su|sv|sy|sz|tc|td|tf|tg|th|tj|tk|tm|tn|to|tp|tr|tt|tv|tw|tz|ua|ug|uk|um|us|uy|uz|va|vc|ve|vg|vi|vn|vu|wf|ws|ye|yt|yu|za|zm|zw)$|(([0-9][0-9]?|[0-1][0-9][0-9]|[2][0-4][0-9]|[2][5][0-5])\.){3}([0-9][0-9]?|[0-1][0-9][0-9]|[2][0-4][0-9]|[2][5][0-5]))$/i",$email));
}
?>

You need to add a content-type to your $additional_headers parameter:
$headers = "From: $email\r\n";
$headers .= "Reply-To: $email\r\n";
$headers .= "Return-Path: $email\r\n";
$headers .= "MIME-Version: 1.0\r\n";
$headers .= "Content-type: text/html; charset=iso-8859-1\r\n";
if(mail($address, $e_subject, $msg, $headers)) {
My recommendation would be to do as another poster says and use an external sending service or something like Zend_Mail which makes it easy to specify HTML and Plain Text versions (some of us really hate HTML email ;))

This may not be related to your real issue but your regex is HUGE and Pointless :/
preg_match("/^[-_.[:alnum:]]+#((([[:alnum:]]|[[:alnum:]][[:alnum:]-]*[[:alnum:]]).)+(ad|ae|aero|af|ag|ai|al|am|an|ao|aq|ar|arpa|as|at|au|aw|az|ba|bb|bd|be|bf|bg|bh|bi|biz|bj|bm|bn|bo|br|bs|bt|bv|bw|by|bz|ca|cc|cd|cf|cg|ch|ci|ck|cl|cm|cn|co|com|coop|cr|cs|cu|cv|cx|cy|cz|de|dj|dk|dm|do|dz|ec|edu|ee|eg|eh|er|es|et|eu|fi|fj|fk|fm|fo|fr|ga|gb|gd|ge|gf|gh|gi|gl|gm|gn|gov|gp|gq|gr|gs|gt|gu|gw|gy|hk|hm|hn|hr|ht|hu|id|ie|il|in|info|int|io|iq|ir|is|it|jm|jo|jp|ke|kg|kh|ki|km|kn|kp|kr|kw|ky|kz|la|lb|lc|li|lk|lr|ls|lt|lu|lv|ly|ma|mc|md|mg|mh|mil|mk|ml|mm|mn|mo|mp|mq|mr|ms|mt|mu|museum|mv|mw|mx|my|mz|na|name|nc|ne|net|nf|ng|ni|nl|no|np|nr|nt|nu|nz|om|org|pa|pe|pf|pg|ph|pk|pl|pm|pn|pr|pro|ps|pt|pw|py|qa|re|ro|ru|rw|sa|sb|sc|sd|se|sg|sh|si|sj|sk|sl|sm|sn|so|sr|st|su|sv|sy|sz|tc|td|tf|tg|th|tj|tk|tm|tn|to|tp|tr|tt|tv|tw|tz|ua|ug|uk|um|us|uy|uz|va|vc|ve|vg|vi|vn|vu|wf|ws|ye|yt|yu|za|zm|zw)$|(([0-9][0-9]?|[0-1][0-9][0-9]|[2][0-4][0-9]|[2][5][0-5]).){3}([0-9][0-9]?|[0-1][0-9][0-9]|[2][0-4][0-9]|[2][5][0-5]))$/i",$email)
^^ That's madness :/
try something a little more simpler:
return filter_var($email, FILTER_VALIDATE_EMAIL);

You need an HTML header. Add this:
$headers = "MIME-Version: 1.0" . "\r\n";
$headers .= "Content-type:text/html;charset=iso-8859-1" . "\r\n";
$headers .= "From: $email\r\nReply-To: $email\r\nReturn-Path: $email\r\n";
Then in your send mail line rewrite it like this:
if(mail($address, $e_subject, $msg, $headers))
Also, if I were you I would make it more cross-platform compatible. Newlines in *nix systems is "\n" and in Mac's its "\r". I've never actually worked on a Mac server so I use this to set a New Line define:
if(strtoupper(substr(PHP_OS, 0, 3)) === 'WIN')
define('EOL', "\r\n");
else
define('EOL', "\n");
And in my headers I use EOL instead of ."\r\n" so it looks like this:
$headers = "MIME-Version: 1.0" . EOL
$headers .= "Content-type:text/html;charset=iso-8859-1" . EOL;
$headers .= "From: $email".EOL."Reply-To: $email".EOL."Return-Path: $email".EOL.EOL;
Also, end your headers with TWO newlines to prevent header injection attacks.

You'll need some html headers, sure, at least
<html>
<body>
Your data
</body>
</html>
and set a correct mime type

Rather than trying to get all of the details of sending emails correctly (getting past spam filters etc) you can use a library such as http://swiftmailer.org/. It handles setting all of the appropriate headers etc for you.
I have no relation to swiftmailer. I've just used it and liked it.

Related

Changing form php sendmail to SMTP?

We created this contact form a long time ago, but we have recently had issues with our sendmail, now i need to change this to use SMTP and that i haven't done before. Is it much work or just a matter of changing few lines? Any tips are welcome.
You can see our whole script here, it's very simple...
<?php
if(!$_POST) exit;
function tommus_email_validate($email) {
return filter_var($email, FILTER_VALIDATE_EMAIL) && preg_match('/#.+\./', $email);
}
$name = $_POST['name']; $email = $_POST['email']; $phone = $_POST['phone']; $comments = $_POST['comments'];
if(trim($name) == '') {
exit('<div class="error_message">You must enter your name.</div>');
} else if(trim($name) == 'Name') {
exit('<div class="error_message">You must enter your name.</div>');
} else if(trim($email) == '') {
exit('<div class="error_message">Please enter a valid email address.</div>');
} else if(!tommus_email_validate($email)) {
exit('<div class="error_message">You have entered an invalid e-mail address.</div>');
} else if(trim($comments) == 'Tell us what you think!') {
exit('<div class="error_message">Please enter your message.</div>');
} else if(trim($comments) == '') {
exit('<div class="error_message">Please enter your message.</div>');
} else if( strpos($comments, 'href') !== false ) {
exit('<div class="error_message">Please leave links as plain text.</div>');
} else if( strpos($comments, '[url') !== false ) {
exit('<div class="error_message">Please leave links as plain text.</div>');
} if(get_magic_quotes_gpc()) { $comments = stripslashes($comments); }
$address = 'hello#basicagency.com';
$e_subject = 'You\'ve been contacted by ' . $name . '.';
$e_body = "You have been contacted by $name from your contact form, their additional message is as follows." . "\r\n" . "\r\n";
$e_content = "\"$comments\"" . "\r\n" . "\r\n";
$e_reply = "You can contact $name via email, $email (or by phone if supplied: $phone)";
$msg = wordwrap( $e_body . $e_content . $e_reply, 70 );
$headers = "From: $email" . "\r\n";
$headers .= "Reply-To: $email" . "\r\n";
$headers .= "MIME-Version: 1.0" . "\r\n";
$headers .= "Content-type: text/plain; charset=utf-8" . "\r\n";
$headers .= "Content-Transfer-Encoding: quoted-printable" . "\r\n";
if(mail($address, $e_subject, $msg, $headers)) {
echo "<fieldset><div id='success_page'><p>Thank you $name, your message has been submitted to us.</p></div></fieldset>";
}
You can use a package for handling e-mails, such as PHPMailer, just use the included methods to build your message, instead of the $headers variable. Once you have downloaded PHPMailer and have it somewhere accessable by your script, replace this:
$headers = "From: $email" . "\r\n";
$headers .= "Reply-To: $email" . "\r\n";
$headers .= "MIME-Version: 1.0" . "\r\n";
$headers .= "Content-type: text/plain; charset=utf-8" . "\r\n";
$headers .= "Content-Transfer-Encoding: quoted-printable" . "\r\n";
if(mail($address, $e_subject, $msg, $headers)) {
echo "<fieldset><div id='success_page'><p>Thank you $name, your message has been submitted to us.</p></div></fieldset>";
}
with something like this:
require '/path/to/PHPMailer/PHPMailerAutoload.php';
$mail = new PHPMailer;
$mail->isSMTP();
// SMTP server details
$mail->Host = "mail.example.com";
$mail->Port = 25;
$mail->SMTPAuth = true;
$mail->Username = "yourname#example.com";
$mail->Password = "yourpassword";
// message details
$mail->setFrom($email, $email);
$mail->addReplyTo($email, $email);
$mail->addAddress($address, $address);
$mail->Subject = $e_subject;
$mail->Body = $msg;
// send
if($mail->send()) {
echo "<fieldset><div id='success_page'><p>Thank you $name, your message has been submitted to us.</p></div></fieldset>";
}
else{
echo 'Mailer Error: ' . $mail->ErrorInfo;
}

google captcha nocaptcha in html form

I am trying to figure out how to add the new google recaptcha to my form. I have followed all the steps and documentation but the verification fails. Please help with adding the correct lines to my php file.
<?php
if(!$_POST) exit;
// Email address verification, do not edit.
function isEmail($email) {
return(preg_match("/^[-_.[:alnum:]]+#((([[:alnum:]]|[[:alnum:]][[:alnum:]-]*[[:alnum:]])\.)+(ad|ae|aero|af|ag|ai|al|am|an|ao|aq|ar|arpa|as|at|au|aw|az|ba|bb|bd|be|bf|bg|bh|bi|biz|bj|bm|bn|bo|br|bs|bt|bv|bw|by|bz|ca|cc|cd|cf|cg|ch|ci|ck|cl|cm|cn|co|com|coop|cr|cs|cu|cv|cx|cy|cz|de|dj|dk|dm|do|dz|ec|edu|ee|eg|eh|er|es|et|eu|fi|fj|fk|fm|fo|fr|ga|gb|gd|ge|gf|gh|gi|gl|gm|gn|gov|gp|gq|gr|gs|gt|gu|gw|gy|hk|hm|hn|hr|ht|hu|id|ie|il|in|info|int|io|iq|ir|is|it|jm|jo|jp|ke|kg|kh|ki|km|kn|kp|kr|kw|ky|kz|la|lb|lc|li|lk|lr|ls|lt|lu|lv|ly|ma|mc|md|me|mg|mh|mil|mk|ml|mm|mn|mo|mp|mq|mr|ms|mt|mu|museum|mv|mw|mx|my|mz|na|name|nc|ne|net|nf|ng|ni|nl|no|np|nr|nt|nu|nz|om|org|pa|pe|pf|pg|ph|pk|pl|pm|pn|pr|pro|ps|pt|pw|py|qa|re|ro|ru|rw|sa|sb|sc|sd|se|sg|sh|si|sj|sk|sl|sm|sn|so|sr|st|su|sv|sy|sz|tc|td|tf|tg|th|tj|tk|tm|tn|to|tp|tr|tt|tv|tw|tz|ua|ug|uk|um|us|uy|uz|va|vc|ve|vg|vi|vn|vu|wf|ws|ye|yt|yu|za|zm|zw)$|(([0-9][0-9]?|[0-1][0-9][0-9]|[2][0-4][0-9]|[2][5][0-5])\.){3}([0-9][0-9]?|[0-1][0-9][0-9]|[2][0-4][0-9]|[2][5][0-5]))$/i",$email));
}
if (!defined("PHP_EOL")) define("PHP_EOL", "\r\n");
$name = $_POST['name'];
$email = $_POST['email'];
$comments = $_POST['comments'];
if(trim($name) == '') {
echo '<div class="error_message">Attention! You must enter your name.</div>';
exit();
} else if(trim($email) == '') {
echo '<div class="error_message">Attention! Please enter a valid email address.</div>';
exit();
} else if(!isEmail($email)) {
echo '<div class="error_message">Attention! You have enter an invalid e-mail address, try again.</div>';
exit();
} else if(trim($comments) == '') {
echo '<div class="error_message">Attention! Please enter your message.</div>';
exit();
}
if(get_magic_quotes_gpc()) {
$comments = stripslashes($comments);
}
// Configuration option.
// Enter the email address that you want to emails to be sent to.
// Example $address = "joe.doe#yourdomain.com";
//$address = "joe.doe#yourdomain.com";
$address = "joe.doe#yourdomain.com";
// Configuration option.
// i.e. The standard subject will appear as, "You've been contacted by John Doe."
// Example, $e_subject = '$name . ' has contacted you via Your Website.';
$e_subject = 'You\'ve been contacted by ' . $name . '.';
// Configuration option.
// You can change this if you feel that you need to.
// Developers, you may wish to add more fields to the form, in which case you must be sure to add them here.
$e_body = "You have been contacted by $name with regards to $subject, their additional message is as follows." . PHP_EOL . PHP_EOL;
$e_content = "\"$comments\"" . PHP_EOL . PHP_EOL;
$e_reply = "You can contact $name via email, $email or via phone $phone";
$msg = wordwrap( $e_body . $e_content . $e_reply, 70 );
$headers = "From: $email" . PHP_EOL;
$headers .= "Reply-To: $email" . PHP_EOL;
$headers .= "MIME-Version: 1.0" . PHP_EOL;
$headers .= "Content-type: text/plain; charset=utf-8" . PHP_EOL;
$headers .= "Content-Transfer-Encoding: quoted-printable" . PHP_EOL;
if(mail($address, $e_subject, $msg, $headers)) {
// Email has sent successfully, echo a success page.
echo "<fieldset>";
echo "<div id='success_page'>";
echo "<h1>Email Sent Successfully.</h1>";
echo "<p>Thank you <strong>$name</strong>, your message has been submitted to us.</p>";
echo "</div>";
echo "</fieldset>";
} else {
echo 'ERROR!';
}
Honestly, you should have just wrote an HTML file and put <?php ?> in it to write the necessary PHP code and everything else, in HTML. Google reCAPTCHA requires you to:
Use the script tag inside the head tag to include their JS code.
Use a form to put your reCAPTCHA in.
Submit a POST request to https://www.google.com/recaptcha/api/siteverify with 2 parameters - secret and response
And all of them need HTML. I suggest you to rebuild your form in HTML and use PHP when necessary, like verifying the email and stuff, but you really do need HTML.

PHP Contact Form not Sending?

Ive got a contact form that isnt sending but is outputting that the message is sent? Can anybody see a problem?
<?php
$name = $_POST['name'];
$email = $_POST['email'];
$subject = $_POST['subject'];
$message = $_POST['message'];
$to = "myemail#email.co.uk";
//begin of HTML message
$message = "
From : $name,
Email: $email,
Subject: $subject,
Message: $message ";
//end of message
// To send the HTML mail we need to set the Content-type header.
$headers = "MIME-Version: 1.0\r\n";
$headers .= "Content-type: text/html; charset=iso-8859-1\r\n";
$headers .= "From: Website Enquiry";
if (isset($_POST['name'])) {
// now lets send the email.
mail($to, $subject, $message, $headers);
header('Location: ' . $_SERVER['HTTP_REFERER'] . '?e=Thankyou, we will be in touch shortly.');
} else {
header('Location: ' . $_SERVER['HTTP_REFERER'] . '?e=There was an error sending your message, Please try again.');
}
?>
The "From" header should have a syntactically correct email address. You also need to check the return value of the "mail" function.
$header .= "From: Website Enquiry <enquiry#website.com>";
PS: Please improve your code formatting.
Try to enter an email at From: in $headers.
Like $headers .= "From: youremail#provider.com" or
$headers .= "From: Website Enquiry <youremail#provider.com>"
And you should change it to
if(mail(...)) {
//success
}
else {
//email failed
}

PHP Form Review - Cc and Bcc not working

I have an html form the links to a PHP email. The form works well, but I am having trouble with the Cc and Bcc not coming through.
Here is the entire code. Please review and help me understand what I am getting wrong on the Cc and Bcc parts in the headers.
Thanks:
<?php
$emailFromName = $_POST['name'];
$emailFrom = $_POST['email'];
$emailFromPhone = $_POST['phone'];
$email9_11 = $_POST['9-10'];
$email10_11 = $_POST['10-11'];
$email11_12 = $_POST['11-12'];
$email12_1 = $_POST['12-1'];
if (empty($emailFromName)) {
echo 'Please enter your name.';
} elseif (!preg_match('/^([A-Z0-9\.\-_]+)#([A-Z0-9\.\-_]+)?([\.]{1})([A-Z]{2,6})$/i', $emailFrom) || empty($emailFrom)) {
echo 'The email address entered is invalid.';
} else {
$emailTo = "main#gmail.com" ;
$subject = "Family History Conference Registration";
if (!empty($emailFrom)) {
$headers = 'From: "' . $emailFromName . '" <' . $emailFrom . '>';
} else {
$headers = 'From: Family History Conference <noreply#domain.org>' . "\r\n";
$headers .= 'Cc: $emailFrom' . "\r\n";
$headers .= 'Bcc: myemail#domain.com' . "\r\n";
}
$body = "From: ".$emailFromName."\n";
$body .= "Email: ".$emailFrom."\n";
$body .= "Phone: ".$emailFromPhone."\n\n";
$body .= "I would like to attend the following classes.\n";
$body .= "9:10 to 10:00: ".$email9_11."\n";
$body .= "10:10 to 11:00: ".$email10_11."\n";
$body .= "11:10 to 12:00: ".$email11_12."\n";
$body .= "12:10 to 1:00: ".$email12_1."\n";
/* Send Email */
if (mail($emailTo, $subject, $body, $headers)) {
echo "<h2>Thank you for Registering</h2>
<h3>You have registered for the following classes</h3>
<p>9:10 to 10:00am: \"$email9_11\" <br />
10:10 to 11:00am: \"$email10_11\"<br />
11:10 to 12:00: \"$email11_12\"<br />
12:10 to 1:00: \"$email12_1\"</p>
<p>We look forward to seeing you October 31, 2010</p>";
} else {
echo 'There was an internal error while sending your email.<br>';
echo 'Please try again later.';
}
}
?>
You're using single quotes
$headers .= 'Cc: $emailFrom' . "\r\n";
PHP won't interpret variables inside single quotes, you must use double quotes
$headers .= "Cc: $emailFrom\r\n";

Why is this mail going straight to SPAM box?

I am using the following script to send mail
<?
extract($_POST);
$subject = "Feedback from ".$name." (".$email.", Ph: ".$phone.")";
$mail = #mail($send,$subject,$content);
if($mail) { echo "Your feedback has been sent"; }
else { echo "We are sorry for the inconvienience, but we could not send your feedback now."; }
?>
But this is always ending up in the spam Folder. Why?
You have to use headers while you send mail, to prove that the mail arrives from a genuine source and not a bot.
Try this!
<?
extract($_POST);
$subject = "Feedback from ".$name." (".$email.", Ph: ".$phone.")";
$headers = 'MIME-Version: 1.0' . "\r\n";
$headers .= 'Content-type: text/html; charset=iso-8859-1' . "\r\n";
$headers .= 'From:'.$email."\r\n";
$headers .= 'Reply-To: '.$email;
$mail = #mail($feedback,$subject,$content,$headers);
if($mail) { echo "Your feedback is send"; }
else { echo "We are sorry for the inconvienience, but we could not send your feedback now."; }
?>

Categories