There are a lot of other posts about this. I have gone through several and tried arrays and inputting emails in the $to field and the like but my form keeps only sending if I specify one email. What am I doing wrong? I'm a PHP noob too.
<?php
// EVALUATION FORM
$your_email = 'email1#address.com, email2#address.com';
session_start();
$errors = '';
$name = '';
$visitor_email = '';
$phone = '';
if (isset($_POST['submit'])) {
$name = $_POST['name'];
$visitor_email = $_POST['email'];
$phone = $_POST['phone'];
///------------Do Validations-------------
if (empty($name) || empty($visitor_email)) {
$errors .= "\n Form was not submitted. Please fill out all the fields. ";
}
if (IsInjected($visitor_email)) {
$errors .= "\n Bad email value!";
}
if (empty($_SESSION['6_letters_code']) || strcasecmp($_SESSION['6_letters_code'], $_POST['6_letters_code']) != 0) {
//Note: the captcha code is compared case insensitively.
//if you want case sensitive match, update the check above to
// strcmp()
$errors .= "\n The captcha code does not match!";
}
if (empty($errors)) {
//send the email
$to = $your_email;
$subject = "Free Injury Evaluation form submission from Northwest Injury Centers";
$from = $your_email;
$ip = isset($_SERVER['REMOTE_ADDR']) ? $_SERVER['REMOTE_ADDR'] : '';
$body = "$name submitted the Free Injury Evaluation form:\n\n" . "Name: $name\n" . "Email: $visitor_email \n" . "Phone: $phone \n" . "IP: $ip\n";
$headers = "From: $from \r\n";
$headers .= "Reply-To: $visitor_email \r\n";
mail($to, $subject, $body, $headers);
header('Location: thankyou.php');
}
}
// Function to validate against any email injection attempts
function IsInjected($str)
{
$injections = array(
'(\n+)',
'(\r+)',
'(\t+)',
'(%0A+)',
'(%0D+)',
'(%08+)',
'(%09+)'
);
$inject = join('|', $injections);
$inject = "/$inject/i";
if (preg_match($inject, $str)) {
return true;
} else {
return false;
}
}
?>
You can provide multiple recipients, however you can only provide one sender. Since you are using $your_email both for $to and $from, you're trying to send an email with multiple senders.
This will work:
$email_to = "jhewitt#amleo.com,some#other.com,yet#another.net";
Fore readability sake in the code use an array and implode it to a comma separated string:
$recipients = array(
"youremailaddress#yourdomain.com",
// more emails
);
$email_to = implode(',', $recipients); // your email address
$email_subject = "Contact Form Message"; // email subject line
$thankyou = "thankyou.htm"; // thank you page
You can add cc to your mail header,
$headers .= 'Cc: someemail#domain.com' . "\r\n";
This will send a copy to the above mentioned email along with to email address.
Related
This question already has answers here:
PHP mail function doesn't complete sending of e-mail
(31 answers)
Closed 5 years ago.
So I have a simple php file that gets data from a form and is supposed to email me. It works on my own system when I was testing it on localhost. But, when I deployed it on ubuntu using apache2, it didn't work. the file may not be pretty, my first attempt to email with php, but i've included the php file below. I know it gets to the mail() method and fails, it activates the (!$mail) conditional, but I can't ever print $mail or any errors so I have no clue what is wrong. any ideas? The cluster of echoes was my attempt to print some kind of error message with no luck. Also, I actually send it to my email address, I just changed it for this example
<?php
if(!isset($_POST['submit'])){
echo "error; you need to submit the form!";
}
$visitor_name = $_POST['name'];
$visitor_message = $_POST['message'];
//incase the email isn't provided
if(empty($_POST['email'])){
$visitor_email = 'n/a';
} else {
$visitor_email = $_POST['email'];
}
//incase the phone isn't provided
if(empty($_POST['phone'])){
$visitor_phone = 'n/a';
} else {
$visitor_email = $_POST['email'];
}
//incase the phone isn't provided
if(empty($_POST['phone'])){
$visitor_phone = 'n/a';
} else {
$visitor_phone = $_POST['phone'];
}
if(empty($visitor_name) || empty($visitor_message))
{
echo "Name and message are mandatory!";
exit;
}
//a function created below for security purposes
if(IsInjected($visitor_email))
{
echo "Bad email value!";
exit;
}
// **************************** CODE FOR EMAIL BODY BELOW *****************************************
$email_body = '<html><body>';
$email_body .= "<h2> You've recieved a new message from: $visitor_name, they need a building </h2>";
$email_body .= '<h4> Here is the message: </h4>';
$email_body .= "<p> $visitor_message </p>";
$email_body .= "<h4> Their contact info is below</h4>";
$email_body .= "<ul> <li> email: $visitor_email </li>";
$email_body .= "<li> phone: $visitor_phone </li></ul>";
$email_body .= '</body></html>';
// **************************** END OF CODE FOR EMAIL BODY ****************************************
$to = 'j#example.com';
$subject = "Building Form Submission: $visitor_name Needs a building\r\n";
$headers = "From: building-form#ArchitectureAdvertisingWebsite.com \r\n";
$headers .= 'MIME-Version: 1.0' . "\r\n";
$headers .= "Content-Type: text/html; charset=ISO-8859-1\r\n";
if($visitor_email != 'n/a'){
$headers .= "Reply-To: $visitor_email \r\n";
}
$mail = mail($to, $subject, $email_body, $headers);
print_r ($mail);
echo "end test";
if (!$mail){
echo "Message not sent, there was an error. Please contact Jerrod at .....";
$errorMessage = error_get_last();
echo "There was an error: $errorMessage";
echo "Below the error is printed : ";
print_r(error_get_last());
} else {
echo "Message sent";
header('Location: end.html');
}
// Function to validate against any email injection attempts
function IsInjected($str)
{
$injections = array('(\n+)',
'(\r+)',
'(\t+)',
'(%0A+)',
'(%0D+)',
'(%08+)',
'(%09+)'
);
$inject = join('|', $injections);
$inject = "/$inject/i";
if(preg_match($inject,$str))
{
return true;
}
else
{
return false;
}
}
?>
Emails sent directly by a PHP script in this way typically get marked as junk or spam by the major email providers. If you start sending them in any quantity, your email address (and possibly domain) will end up on Spamhaus and other blacklists.
If you need to send individualized emails like your example above, consider using a service like SendGrid or Amazon Simple Email Service.
This question already has answers here:
sending email via php mail function goes to spam [duplicate]
(6 answers)
How do you make sure email you send programmatically is not automatically marked as spam?
(24 answers)
Closed 5 years ago.
Please check the following PHP mail function code. Is it correct or not? My mails are going into spam. In the following code, I am getting mail, but mails are landing in spam. If I check original text in gmail then it show dmare fail.
<?php
$your_email = 'yjangir15#gmail.com';
$errors = '';
$name = '';
$visitor_email = '';
$phone = '';
$user_message = '';
if(isset($_POST['submit']))
{
$name = $_POST['name'];
$visitor_email = $_POST['email'];
$phone = $_POST['phone'];
$user_message = $_POST['query'];
///------------Do Validations-------------
if(empty($name)||empty($visitor_email)||empty($phone))
{
$errors .= "\n Name, Email ID and Phone Number. ";
}
if(IsInjected($visitor_email))
{
$errors .= "\n Bad email value!";
}
if(empty($_SESSION['6_letters_code'] ) ||
strcasecmp($_SESSION['6_letters_code'], $_POST['6_letters_code']) != 0)
{
$errors .= "\n Wrong Captcha Code!!!";
}
if(empty($errors))
{
//send the email
$to = $your_email;
$subject="New Admission Enquiry";
$from = $visitor_email;
$ip = isset($_SERVER['REMOTE_ADDR']) ? $_SERVER['REMOTE_ADDR'] : '';
$body ='
<title>A student $name submitted the admission enquiry</title>
<h1>A student ' . $name . ' submitted the admission enquiry</h1>
<p>Here are the Details!</p>
<table>
<tr>
<td><b>Name:</b></td><td>' . $name . '</td>
</tr>
<tr>
<td><b>Email Address:</b></td><td>' . $visitor_email . '</td>
</tr>
<tr>
<td><b>Contact No:</b></td><td>' . $phone . '</td>
</tr>
<tr>
<td valign="top"><b>Query:</b></td><td>' . $user_message . '</td>
</tr>
<tr>
<td><b>IP Address:</b></td><td>' . $ip . '</td>
</tr>
</table>
';
$seprator = md5(time());
$eol = PHP_EOL;
$headers = "From: " .($from) . "\r\n";
$headers .= "Reply-To: ".($from) . "\r\n";
$headers .= "Return-Path: ".($from) . "\r\n";;
$headers .= "MIME-Version: 1.0\r\n";
$headers .= "Content-Type: text/html; charset=ISO-8859-1\r\n";
$headers .= "X-Priority: 3\r\n";
$headers .= "X-Mailer: PHP". phpversion() ."\r\n";
mail($to, $subject, $body, $headers);
header('Location: thankyou.php');
}
}
function IsInjected($str)
{
$injections = array('(\n+)',
'(\r+)',
'(\t+)',
'(%0A+)',
'(%0D+)',
'(%08+)',
'(%09+)'
);
$inject = join('|', $injections);
$inject = "/$inject/i";
if(preg_match($inject,$str))
{
return true;
}
else
{
return false;
}
}
?>
First off, since many of the variables used in your script are user-generated, you should sanitize input variables to avoid malicious code from users.
There can be a lot of reasons why your emails end up in the spam folder. The two most important ones being what email server you are using (proper configuration, sender reputation etc.) and the content of the email. In your case, you are sending an email in html format but your markup is incomplete, lacking html, and body tags to wrap your current markup. Setting a charset in your email markup is also a good idea to ensure correct rendering of characters in the recipient side. Avoid using ISO-8859-1, instead use UTF-8 if possible.
I suggest you check out an email library for sending out these emails instead of the php mail() function. Have a look at the popular PHPMailer library.
There are also cloud based email services like Mailgun to consider as they have good sender reputation from start as compared to setting up an email server of your own.
About the "unwanted queries", you need to provide more details for us to be able to help you there.
I know the title is weird I cant for the life of me phrase it well lol.
I have done searches with multiple ways of phrasing the question and nothing shows up for this.
I have the email scripting working on the website im building and its fantastic! but when i edited the mail code to add extra message lines its made the sequence go wrong.
here is the code im using for the email message area:
<?php
require_once "Mail.php";
// load the variables form address bar
$name = $_REQUEST["name"];
$subject = 'Customer Feedback';
$message = $_REQUEST["message"];
$from = $_REQUEST["from"];
$compname = $_REQUEST["companyName"];
$ph = $_REQUEST["phone"];
$acp = $_REQUEST['allowCommentPublish'];
$marketing = $_REQUEST['incmarketing'];
$verif_box = $_REQUEST["verif_box"];
// Checking the check boxes and marking as appropriate
if(isset($_POST['allowCommentPublish']))
{
$acp = 'Yes';
}
else
{
$acp = 'No';
}
if(isset($_POST['incmarketing']))
{
$marketing = 'Yes';
}
else
{
$marketing = 'No';
}
// Optional data checker
if($compname == '')
{
$compname = 'N/A';
}
if($ph == '')
{
$ph = 'N/A';
}
// remove the backslashes that normally appears when entering " or '
$name = stripslashes($name);
$message = stripslashes($message);
$subject = stripslashes($subject);
$acp = stripcslashes($acp);
$marketing = stripcslashes($marketing);
$from = stripslashes($from);
// check to see if verificaton code was correct
if(md5($verif_box).'a4xn' == $_COOKIE['tntcon'])
{
// if verification code was correct send the message and show this page
$ToEmail = "email#email.com";
$message = "Name: ".$name."\n".$message;
$message = "From: ".$from."\n".$message;
$message = "Comments: ".$message."\n".$message;
$message = "Allow feedback to be Published: ".$acp."\n".$message;
$message = "[ OPTIONAL DATA ]"."\n".$message;
$message = "Company Name: ".$compname."\n".$message;
$message = "Phone Number: ".$ph."\n".$message;
$message = "Allow extra Marketing? ".$marketing."\n".$message;
$headers = array ('From' => $from,
'To' => $ToEmail,
'Subject' => 'Feedback: '.$subject);
$smtp = Mail::factory('smtp', array ('host' => 'smtp.vic.exemail.com.au', 'auth' => false));
$mail = $smtp->send($ToEmail, $headers, $message);
// delete the cookie so it cannot sent again by refreshing this page
setcookie('tntcon','');
header("Location: /feedback_sent.php");
exit;
}
else
{
// if verification code was incorrect then return to contact page and show error
header("Location:".$_SERVER['HTTP_REFERER']."?subject=$subject&from=$from&message=$message&wrong_code=true");
exit;
}
?>
In my mind this should spit out the message body as this:
Name: name here
From: Email address
Comments: Message here
Allow feedback to be published: response
[ OPTIONAL DATA ]
Company Name: Company
Phone Number: Phone
Allow extra Marketing:
This should be how its seen in the email right?
What im actually getting is this:
Allow feedback to be Published: response
[ OPTIONAL DATA ]
Company Name: company
Phone Number: phone
Allow extra Marketing? Response
From: Email address
Name: name here
Comments: Message here
Is this normal? or have i inadvertently snuffed it somewhere along the lines and its messing with my head as payment?
Thanks for any help on this.
EDIT: Updated code.
<?php
// -----------------------------------------
// The Web Help .com
// -----------------------------------------
// remember to replace your#email.com with your own email address lower in this code.
require_once "Mail.php";
// load the variables form address bar
$name = $_REQUEST["name"];
$subject = 'Customer Feedback';
$comment = $_REQUEST["message"];
$from = $_REQUEST["from"];
$compname = $_REQUEST["companyName"];
$ph = $_REQUEST["phone"];
$acp = $_REQUEST['allowCommentPublish'];
$marketing = $_REQUEST['incmarketing'];
$verif_box = $_REQUEST["verif_box"];
// Checking the check boxes and marking as appropriate
if(isset($_POST['allowCommentPublish']))
{
$acp = 'Yes';
}
else
{
$acp = 'No';
}
if(isset($_POST['incmarketing']))
{
$marketing = 'Yes';
}
else
{
$marketing = 'No';
}
// Optional data checker
if($compname == '')
{
$compname = 'N/A';
}
if($ph == '')
{
$ph = 'N/A';
}
// remove the backslashes that normally appears when entering " or '
$name = stripslashes($name);
$comment = stripslashes($comment);
$subject = stripslashes($subject);
$acp = stripcslashes($acp);
$marketing = stripcslashes($marketing);
$from = stripslashes($from);
// check to see if verificaton code was correct
if(md5($verif_box).'a4xn' == $_COOKIE['tntcon'])
{
// if verification code was correct send the message and show this page
$ToEmail = "jim#digital2go.com.au";
$message = "Name: ".$name."\n".$message;
$message .= "From: ".$from."\n".$message;
$message .= "Comments: ".$comment."\n".$message;
$message .= "Allow feedback to be Published: ".$acp."\n".$message;
$message .= "[ OPTIONAL DATA ]"."\n".$message;
$message .= "Company Name: ".$compname."\n".$message;
$message .= "Phone Number: ".$ph."\n".$message;
$message .= "Allow extra Marketing? ".$marketing."\n".$message;
$headers = array ('From' => $from,
'To' => $ToEmail,
'Subject' => 'Feedback: '.$subject);
$smtp = Mail::factory('smtp', array ('host' => 'smtp.vic.exemail.com.au', 'auth' => false));
$mail = $smtp->send($ToEmail, $headers, $message);
// delete the cookie so it cannot sent again by refreshing this page
setcookie('tntcon','');
header("Location: /feedback_sent.php");
exit;
}
else
{
// if verification code was incorrect then return to contact page and show error
header("Location:".$_SERVER['HTTP_REFERER']."?subject=$subject&from=$from&message=$message&wrong_code=true");
exit;
}
?>
Make your message "continue" in the order you wish by doing this:
$message = "Name: ".$name."\n".$message;
$message .= "From: ".$from."\n".$message;
$message .= "Comments: ".$message."\n".$message;
$message .= "Allow feedback to be Published: ".$acp."\n".$message;
$message .= "[ OPTIONAL DATA ]"."\n".$message;
$message .= "Company Name: ".$compname."\n".$message;
$message .= "Phone Number: ".$ph."\n".$message;
$message .= "Allow extra Marketing? ".$marketing."\n".$message;
I'm trying to send a mail using the php mail() function
but for some reason I don't get, additional headers are ignored.
This is my code:
$errors = '';
$myemail = 'my#email.com';
$myemail_bcc = 'my_bbc#email.com';
if(empty($_POST['nome']) || empty($_POST['email']))
{
$errors .= "Error: You must fill Name and Email fields";
}
$name = $_POST['nome'];
$email_address = $_POST['email'];
$telefono = $_POST['telefono'];
$message = $_POST['messaggio'];
if (!preg_match(
"/^[_a-z0-9-]+(\.[_a-z0-9-]+)*#[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,3})$/i",
$email_address))
{
$errors .= "<br />Error: You must use a valid email address";
}
// spediamo la mail
if( empty($errors))
{
$to = $myemail;
$email_subject = "New Request from: $name";
$email_body = "User data:.\n\n";
$email_body .= "Nome: $name \nEmail: $email_address \nTelefono: $telefono \n";
$email_body .= "Messaggio: \n$message";
$headers = "From: John Smith <$myemail>\r\n";
$headers .= "Reply-To: $name <$email_address>\r\n";
$headers .= "Bcc: $myemail_bcc";
mail($to,$email_subject,$email_body,$headers);
}
I've tried to vary the way I declare headers without names, just with emails:
$headers = "From: $myemail \r\n";
$headers .= "Reply-To: $email_address\r\n";
$headers .= "Bcc: $myemail_bcc";
and even just on one line
$headers = "From: $myemail\r\nReply-To: $name <$email_address>\r\nBcc: $myemail_bcc";
But in no case the mail is sento to the Bcc address, and the "reply" function in client email does not use the Reply-to address.
where am I wrong?
I'm very new to PHP and am using a basic template 'send-mail' form on a contact page.
It's been requested that I send the email out to multiple email addresses when the "Submit" button is clicked. I've searched around & haven't quite found what I needed. What code do I need to add into the form below in order to send this out to multiple email addresses?
<?php
$mail_to = 'daniel30293#gmail.com'; // specify your email here
// Assigning data from the $_POST array to variables
$name = $_POST['sender_name'];
$mail_from = $_POST['sender_email'];
$phone = $_POST['sender_phone'];
$web = $_POST['sender_web'];
$company = $_POST['sender_company'];
$addy = $_POST['sender_addy'];
$message = $_POST['sender_message'];
// Construct email subject
$subject = 'Web Prayer Request from ' . $name;
// Construct email body
$body_message = 'From: ' . $name . "\r\n";
$body_message .= 'E-mail: ' . $mail_from . "\r\n";
$body_message .= 'Phone: ' . $phone . "\r\n";
$body_message .= 'Prayer Request: ' . $message;
// Construct email headers
$headers = 'From: ' . $name . "\r\n";
$headers .= 'Reply-To: ' . $mail_from . "\r\n";
$mail_sent = mail($mail_to, $subject, $body_message, $headers);
if ($mail_sent == true){ ?>
<script language="javascript" type="text/javascript">
alert('Your prayer request has been submitted - thank you.');
window.location = 'prayer-request.php';
</script>
<?php } else { ?>
<script language="javascript" type="text/javascript">
alert('Message not sent. Please, notify the site administrator admin#bondofperfection.com');
window.location = 'prayer-request.php';
</script>
<?php
}
?>
Your help is greatly appreciated.
You implode an array of recipients:
$recipients = array('jack#gmail.com', 'jill#gmail.com');
mail(implode(',', $recipients), $submit, $message, $headers);
See the PHP: Mail function reference - http://php.net/manual/en/function.mail.php
Receiver, or receivers of the mail.
The formatting of this string must comply with ยป RFC 2822. Some examples are:
user#example.com
user#example.com, anotheruser#example.com
User <user#example.com>
User <user#example.com>, Another User <anotheruser#example.com>
Just add multiple recipients comma seperated in your $mail_to variable like so:
$mail_to = 'nobody#example.com,anotheruser#example.com,yetanotheruser#example.com';
See
mail() function in PHP
Here is a simple example:
<?php
// Has the form been submitted?
// formSubmit: <input type="submit" name="formSubmit">
if (isset($_POST['formSubmit'])) {
// Set some variables
$required_fields = array('name', 'email');
$errors = array();
$success_message = "Congrats! Your message has been sent successfully!";
$sendmail_error_message = "Oops! Something has gone wrong, please try later.";
// Cool the form has been submitted! Let's loop through the required fields and check
// if they meet our condition(s)
foreach ($required_fields as $fieldName) {
// If the current field in the loop is NOT part of the form submission -OR-
// if the current field in the loop is empty, then...
if (!isset($_POST[$fieldName]) || empty($_POST[$fieldName])) {
// add a reference to the errors array, indicating that these conditions have failed
$errors[$fieldName] = "The {$fieldName} is required!";
}
}
// Proceed if there aren't any errors
if (empty($errors)) {
$name = htmlspecialchars(trim($_POST['name']), ENT_QUOTES, 'UTF-8' );
$email = htmlspecialchars(trim($_POST['email']), ENT_QUOTES, 'UTF-8' );
// Email Sender Settings
$to_emails = "anonymous1#example.com, anonymous2#example.com";
$subject = 'Web Prayer Request from ' . $name;
$message = "From: {$name}";
$message .= "Email: {$email}";
$headers = "From: {$name}\r\n";
$headers .= "Reply-To: {$email}\r\n";
$headers .= 'X-Mailer: PHP/' . phpversion();
if (mail($to_emails, $subject, $message, $headers)) {
echo $success_message;
} else {
echo $sendmail_error_message;
}
} else {
foreach($errors as $invalid_field_msg) {
echo "<p>{$invalid_field_msg}</p>";
}
}
}