<?php
if ($_POST['friends-email']) {
$name = "Sender's Name";
$email = "sender#domain.com";
$recipient = preg_replace("/[^a-z0-9 !?:;,.\/_\-=+##$&\*\(\)]/im", "", $_POST['friends-email']);
$recipient = preg_replace("/(content-type:|bcc:|cc:|to:|from:)/im", "", $recipient);
$mail_body = "Default Description";
$subject = "Default Subject";
$header = "From: " . $name . " <" . $email . ">\r\n";
mail($recipient, $subject, $mail_body, $header);
echo 'Thank you for recommending <br /> us!';
} else {
echo '<form action="" method="post" name="send2friend" id="send2friend">
Friends Email*:
<input name="friends-email" id="friends-email" type="text" />
<input type="submit" value="continue" />
</form>';
}
?>
Not sure why this isn't working, I get the "thank you message" but the email is not delivered when I test using my own emails.
Just stating the obvious, but where you have put $email = "sender#domain.com";, you are actually changing that to a variable right?
Do you have all PHP errors turned on and displaying?
error_reporting(E_ALL);
ini_set('display_errors', '1');
Use PHP interactive mode (php -a)to deploy an email
$to = 'dummymailing#mailinator.com'; $subject = 'the subject'; $message = 'hello'; $headers = 'From: webmaster#example.com' . "\r\n"; mail($to, $subject, $message, $headers);
Then go here to check that it's received. This is just to check that it's not a problem with your email client - i.e. it's not blocking the email.
If you're still having problems, it could be something to do with the system's sendmail function. This post on serverfault provides a lot of detailed advice on debugging the sendmail function.
Have you tried the mail function with hardcoded values, to check phpmail is set up right?
Then if that works, replace each value one at a time, and you will find your bug. I am guessing it is you regular expression replace however.
Try enclosing the mail delivery in an if statement
Related
This question already has answers here:
PHP mail function doesn't complete sending of e-mail
(31 answers)
Closed 6 years ago.
I'm attempting to run an email form, which takes text from the user's input forms and send them to my desired email (seen as $myemail in the php below).
<form method="post" name="contact_form" action="Contact.php">
Your Name: <input type="text" required name="name">
Email Address: <input type="text" required name="email">
Message: <textarea required name="message"></textarea>
<input type="submit" value="Submit">
</form>
<?php
$errors = '';
$myemail = 'enterDesiredEmail';
if(empty($_POST['name']) || empty($_POST['email']) || empty($_POST['message'])) {
$errors .= "\n Error: all fields are required";
}
$name = null;
$email_address = null;
$message = null;
$name = $_POST["name"];
$email_address = $_POST["email"];
$message = $_POST["message"];
if (!preg_match("/^[_a-z0-9-]+(\.[_a-z0-9-]+)*#[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,3})$/i",$email_address)) {
$errors .= "\n Error: Invalid email address";
}
if( empty($errors)) {
$to = $myemail;
$email_subject = "Contact form submission: $name";
$email_body = "You have received a new message. ".
" Here are the details:\n Name: $name \n ".
"Email: $email_address\n Message \n $message";
$headers = "From: $myemail\n";
$headers .= "Reply-To: $email_address";
mail($to,$email_subject,$email_body,$headers);
}
?>
I spat the above code out onto a webpage and uploaded the file to my server. Upon accessing the webpage online, filling in content to the form, and clicking sbmit, the page refreshed with the inputs and textarea clear as expected. When I checked the email I had set, no message was received. What could I do to correct this code so that the desired email address actually receives a message?
Many thanks.
Some pointers that may well solve your issue without specifically telling you what the cause of this issue actually is:
1) Use Error Logging.
2) Check that you have a valid mail server setup on your server. As stated in comments by Jason K.
3) Use a mailing library such as PHPMailer. It sidesteps a huge amount of the headache.
4) Check your emails are valid with the correct code, principly using filter_var rather than obtuse regexes.
Also check emails are Sanitized (FILTER_SANITIZE_EMAIL) as well.
5) If not using or setting up a library such as PHPMailer or SwiftMailer then you need to check your mail headers are exactly correct.
BONUS
There seems to be some conflicting accounts of what to use for email line endings [including headers], but I would suggest PHP_EOL or \r\n (the same thing on Linux servers). \n is not suitable. As stated in comments by Barmar.
Good luck
You should try to use a library such as PHPMailer. Themail() function is sometimes not flexible enough to achieve what you need in most cases. Also the mail() function requires a local mail server. In addition, PHPMailer offers a lot of addons such as the ability to set up attachments or the ability to send HTML emails to your users. Using a library like this also means that you emails will be sent out almost all the time since it it tested and used by a lot of people.
You can find a tutorial for using PHPMailer here: https://www.sitepoint.com/sending-emails-php-phpmailer/
Example code taken from the website using PHPMailer:
<?php
require_once "vendor/autoload.php";
//PHPMailer Object
$mail = new PHPMailer;
//From email address and name
$mail->From = "from#yourdomain.com";
$mail->FromName = "Full Name";
//To address and name
$mail->addAddress("recepient1#example.com", "Recepient Name");
$mail->addAddress("recepient1#example.com"); //Recipient name is optional
//Address to which recipient will reply
$mail->addReplyTo("reply#yourdomain.com", "Reply");
//CC and BCC
$mail->addCC("cc#example.com");
$mail->addBCC("bcc#example.com");
//Send HTML or Plain Text email
$mail->isHTML(true);
$mail->Subject = "Subject Text";
$mail->Body = "<i>Mail body in HTML</i>";
$mail->AltBody = "This is the plain text version of the email content";
if(!$mail->send())
{
echo "Mailer Error: " . $mail->ErrorInfo;
}
else
{
echo "Message has been sent successfully";
}
?>
You need to interpolate the actual $email variable inside the double quote from :
$headers = "From: $myemail\n"; to
$headers = "From: ${myemail}"."\r\n";
If you Specify additional headers, like From, Cc, and Bcc. The additional headers should be separated with a CRLF (\r\n).
This is an example from php doc:
`<?php
$to = 'nobody#example.com';
$subject = 'the subject';
$message = 'hello';
$headers = 'From: webmaster#example.com' . "\r\n" .
'Reply-To: webmaster#example.com' . "\r\n" .
'X-Mailer: PHP/' . phpversion();
mail($to, $subject, $message, $headers);
?>
Happy coding!
Forgive me, I am new at this and the different php I have tried hasn't really worked at all. I've found examples for Natural Language forms, but none with working PHP and I'm familiar with PHP when used with traditional forms, but I'm having problems putting the two together.
The general form layout goes like this:
My name is [your name].
Today, I am [whatchya gonna do?].
I'm doing this because [c'mon,why?].
It's important that I [what you said you'd do] because [the big picture].
Shoot me an email with my awesome new declaration at [your email]
Button 1 (sends email)
Button 2 (copies all text and input fields to clipboard -- not as important right now)
Button 1, I want to send a copy to myself with a hard coded email address and also send a copy to the user with the email address they've entered.
This is a little messy right now, as I am simply trying to get it to work... again, I have no included PHP because at this point -- I've confused myself so much that I don't know what to include.
<form method="post" action="todayiam.php">
<div class="naturallanguageform">
<div class="nlfinner">
<p class="line">
<span class="copy">My name is </span>
<span class="inputcontainer"><input class="textinput" name="name" value="" placeholder="[your name]">.</span>
<span class="copy">Today, I am </span>
<span class="inputcontainer"><input class="textinput" name="todayiam" value="" placeholder="[whatchya gonna do?]">.</span>
<span class="copy">I'm doing this because </span>
<span class="inputcontainer"><input class="textinput" name="why" value="" placeholder="[c'mon, why?]">.</span>
<span class="copy"> It's important that I </span>
<span class="inputcontainer"><input class="textinput" name="whatusaid" value="" placeholder="[what you said you'd do]"></span>
<span class="copy"> because </span>
<span class="inputcontainer"><input class="textinput" name="because" value="" placeholder="[the big picture]">.</span>
</p>
<span class="copy">Shoot me an email with my awesome new declaration at</span>
<span class="inputcontainer"><input class="textinput" name="email" value="" placeholder="[your email]"></span>
<p class="line">
<button class="button">Send to E-mail</button>
</p>
<p class="line">
<button class="button">Copy to post in comments</button>
</p>
</div>
</div>
</form>
Any assistance will be greatly appreciated.
Update:
<?php
// from the form
$name = trim(strip_tags($_POST['name']));
$email = trim(strip_tags($_POST['email']));
$message = htmlentities($_POST['todayiam']);
// set here
$subject = "Contact form submitted!";
$to = 'email#gmail.com';
$body = <<<HTML
$message
HTML;
$headers = "From: $email\r\n";
$headers .= "Content-type: text/html\r\n";
// send the email
mail($to, $subject, $body, $headers);
// redirect afterwords, if needed
header('Location: index.html');
?>
Another update
I have changed $headers = "From: $email\r\n"; to $headers = "From: email#gmail.com" . "\r\n" ; to set a static from address (my support email) and the email is still identifying as from CGI Mailer. I have verified that it's not a caching issue and the correct files are being used.
<?php
if (isset($_POST['name'], $_POST['todayiam'], $_POST['why'], $_POST['whatusaid'], $_POST['because'], $_POST['email']) {
// We enter this statement only if all the fields has been properly defined, this to avoid getting undefined index
$name = $_POST['name'];
$todayIam = $_POST['todayiam'];
$why = $_POST['why'];
$whatYouSaid = $_POST['whatusaid'];
$because = $_POST['because'];
$email = $_POST['email'];
// We define the variables for using in mail()
$to = 'email#gmail.com';
$to .= ', '.$email; // You wanted them to recieve a copy
$subject = "Contact form submitted!";
// You can put a lot more headers, check out the mail() documentation
$headers = "From: email#gmail.com" . "\r\n" ;
$headers .= "Content-type: text/html\r\n";
// Compose a $message from all the variables
$message = "My name is $name. ";
$message .= "Today, I am $todayIam.";
$message .= "I'm doing this because $why.";
$message .= "It's important that I $whatYouSaid";
$message .= "because $because.";
if (mail($to, $subject, $message, $header)) {
// Mail was successfully sent! Do something here
}
}
?>
Before you posted your answer, I was working on this script:
<?php
// from the form
$name = trim(strip_tags($_POST['name']));
$email = trim(strip_tags($_POST['email']));
$message = htmlentities($_POST['todayiam']);
// set here
$subject = "Contact form submitted!";
$to = 'email#gmail.com';
$body = <<<HTML
$message
HTML;
$headers = "From: $email\r\n";
$headers .= "Content-type: text/html\r\n";
// send the email
mail($to, $subject, $body, $headers);
// redirect afterwords, if needed
header('Location: index.html');
?>
The $email = trim(strip_tags($_POST['email'])); field was pulling the user's email and using it for the sent from as noted in the $header... so it was working fine. With the new script, that you posted, I can't get it to work with my hard coded email OR the user's email as the FROM. Initially, I really wanted to understand what the differences were between the script, why one worked and the other didn't, but now... I'd really just like my email to be hard coded as the FROM. I'll worry about the differences later. As I said before, I really have tried to get this to work in many different forms... I am sure it's something simple that I am over looking as a novice to PHP. Thanks.
Right, so after a bit of discussion from comments, I decided to post an answer instead, giving a bit more detail where it's more readable.
Your PHP code is missing the combination of all fields into $message. This can easily be done, as you can put a variable inside a string in PHP. I'll show you how. I'm also going to show you how you can avoid undefined indexes.
<?php
if (isset($_POST['name'], $_POST['todayiam'], $_POST['why'], $_POST['whatusaid'], $_POST['because'], $_POST['email']) {
// We enter this statement only if all the fields has been properly defined, this to avoid getting undefined index
$name = $_POST['name'];
$todayIam = $_POST['todayiam'];
$why = $_POST['why'];
$whatYouSaid = $_POST['whatusaid'];
$because = $_POST['because'];
$email = $_POST['email'];
// We define the variables for using in mail()
$to = 'email#gmail.com';
$to .= ', '.$email; // You wanted them to recieve a copy
$subject = "Contact form submitted!";
// You can put a lot more headers, check out the mail() documentation
$headers = "From: $email\r\n";
$headers .= "Content-type: text/html\r\n";
// Compose a $message from all the variables
$message = "My name is $name. ";
$message .= "Today, I am $todayIam.";
$message .= "I'm doing this because $why.";
$message .= "It's important that I $whatYouSaid";
$message .= "because $because.";
if (mail($to, $subject, $message, $header)) {
// Mail was sucsessfullly sent! Do something here
}
}
?>
I'm using a simple web form and some PHP script to send the completed form to my email. When I hit "Submit" I get the PHP text "Thanks, we'll be in touch shortly" but I'm not getting the email with submitted form info. Not sure what's the problem.
from the HTML doc:
<div class='' "letstalk_form">
<form method="get" action="contact.php" name="contact" id="contact">
<p>
<label for="txtfname">Name:</label><input type="text" tabindex="1" name="txtfname" id="txtfname" class="clsTextBox">
</p>
<p>
<label for="txtcompany">Company:</label><input type="text" tabindex="2" name="txtcompany" id="txtcompany" class="clsTextBox">
</p>
<p>
<label for="txtemail">E-mail:</label><input type="text" tabindex="3" name="txtemail" id="txtemail" class="clsTextBox">
</p>
<p>
Message:<textarea name="comments" id="comments" rows="2" cols="20"></textarea>
</p>
<p class="submit">
<input type="submit" value="Submit">
</p>
</form>
</div>
and the PHP
$msg = "Sender Name:\t$txtfname\n";
$msg .= "Sender Company:\t$txtcompany\n";
$msg .= "Sender E-mail:\t$txtemail\n";
$msg .= "Comments:\t$comments\n\n";
$recipient = "receiversemail#somewhere.com";
$subject = "from PI Website";
$mailheaders = "From: Lets Do Business <> \n";
$mailheaders .= "Reply-To: $txtemail\n\n";
mail($recipient, $subject, $msg, $mailheaders);
echo "<HTML><HEAD><TITLE>Form Sent!</TITLE></HEAD><BODY>";
echo "<H3 align=center>Thank You, $txtfname</H3>";
echo "<P align=center>Your submission was sent successfully.<br />
I will be contacting you soon.</P>";
echo "</BODY></HTML>";
?>
</div>
I've used this is the past and worked great. Is there something I overlooked? Thanks for you help!
EDIT: I ended up using the link Turgut Dursun provided (html-form-guide.com/contact-form/php-email-contact-form.html ) to set up the form. Works great. Thanks.
Are you assigning the $_GET[] values from the form to variables prior to this portion of your code?
$msg = "Sender Name:\t$txtfname\n";
$msg .= "Sender Company:\t$txtcompany\n";
$msg .= "Sender E-mail:\t$txtemail\n";
$msg .= "Comments:\t$comments\n\n";
$recipient = "abosiger#embarqmail.com";
$subject = "from PI Website";
$mailheaders = "From: Lets Do Business <> \n";
$mailheaders .= "Reply-To: $txtemail\n\n";
mail($recipient, $subject, $msg, $mailheaders);
If not, you need to either initialize your $_GET[] values to individual variables:
$txtfname = $_GET['textfname'];
for each variable sent through get. Or you can access them directly from the $_GET array through the following syntax:
$msg = "Sender Name:\t" . $_GET['txtfname'] . "\n";
Let me know if this helps.
<?php
$to = "someone#example.com";
$subject = "Test mail";
$message = "Hello! This is a simple email message.";
$from = "someonelse#example.com";
$headers = "From:" . $from;
mail($to,$subject,$message,$headers);
echo "Mail Sent.";
?>
change it like this.
The problem probably comes from a bad configuration of the mail function. You have to configure it properly.
Also, you should provide an email in the "From" header.
if message sent and no mails is receieved, this authenticating issues from your domain
... your script might works fine
The two main ways to do this is either using PHPMail() or SMTP. PHPMail() is open and used by trojans and viruses. Most clients have infected files which just send mails using PHPMail(), because it doesn't authenticate. It doesn't check if the email being sent is actually coming from the domain and this puts a lot of strain on the mail server, making legitimate mails wait in queue for a long time.
If you already have a script using PHPMail() function it is very simple to change it to SMTP, you just need to change like 5 lines of your code and add an email address and password (already created in cpanel) into the code, and it will send emails just fine.
if ($_POST['submit']){
$from = "slick#meetslick.com"; //enter your email address
$to = "slickbozz#gmail.com"; //enter the email address of the contact your sending to
$subject = "Contact Form"; // subject of your email
$headers = array ('From' => $from,'To' => $to, 'Subject' => $subject);
$text = ''; // text versions of email.
$html = "<html><body>Name: $name <br> Email: $email <br>Message: $message <br></body></html>"; // html versions of email.
$crlf = "\n";
$mime = new Mail_mime($crlf);
$mime->setTXTBody($text);
$mime->setHTMLBody($html);
//do not ever try to call these lines in reverse order
$body = $mime->get();
$headers = $mime->headers($headers);
$host = "localhost"; // all scripts must use localhost
$username = "support#meetslick.com"; // your email address (same as webmail username)
$password = " here "; // your password (same as webmail password)
$smtp = Mail::factory('smtp', array ('host' => $host, 'auth' => true,
'username' => $username,'password' => $password));
$mail = $smtp->send($to, $headers, $body);
if (PEAR::isError($mail)) {
echo("<p>" . $mail->getMessage() . "</p>");
}
else {
echo("<p>Message successfully sent!</p>");
// header("Location: http://www.meetslick.com/");
}
}
I hope this will be helpful to someone one day.
I'm trying to solve this puzzle here. The contact form on this page (http://www.b3studios.co.uk/) uses AJAX and PHP. I copied all the code and trying to make it work (reverse engineering PHP). I'm not sure how the PHP file should look like to handle the data given by AJAX. I tried the following PHP file:
<?php
$sender = $email;
$receiver = “test#email.com”;
$email_body = “Name: $name \nEmail: $email \nMessage: $message”;
if( mail( $receiver, $subject, $email_body, “From: $sender\r\n” .
“Reply-To: $sender \r\n” . “X-Mailer: PHP/” . phpversion()) )
{
echo “Success! Your message has been sent. Thank You.”;
}
else
{
echo “Your message cannot be sent.”;
}
?>
After pressing "Send Message" it gets stuck at sending message....
Any suggestions to troubleshoot would be greatly appreciated.
I am pretty sure you copied the code with those ugly double quotes “ (MSWord quotes), you should chage to "
try
<?php
$sender = $email;
$receiver = "test#email.com";
$email_body = "Name: $name \nEmail: $email \nMessage: $message";
if( mail( $receiver, $subject, $email_body, "From: $sender\r\n" . "Reply-To: $sender \r\n" . "X-Mailer: PHP/" . phpversion()) )
{
echo "Success! Your message has been sent. Thank You.";
} else {
echo "Your message cannot be sent.";
}
?>
I have a mail sending functionality in php code, I want to use define to set to address and from address.How can this be done.
The code is
<?php
$subject = 'Test email';
$message = "Hello World!\n\nThis is my first mail.";
$headers = "From: $from\r\nReply-To: webmaster#example.com";
//send the email
$mail = #mail( $to, $subject, $message, $headers );
?>
How to define $to and $from. Thanks in Advance for help
Unless it is absolutely imperative, I would recommend using a good old fashioned variable for this particular task, not a constant.
If you do want to use a constant:
define('MAIL_TO', 'mailto#gmail.com');
define('MAIL_FROM', 'mailfrom#gmail.com');
$subject = 'Test email';
$message = "Hello World!\n\nThis is my first mail.";
$headers = "From: " . MAIL_FROM . "\r\nReply-To: webmaster#example.com";
$mailResult = mail(MAIL_TO, $subject, $message, $headers);
FYI:
// Constants can also be retrieved with the constant() function
$mailTo = constant('MAIL_TO');
// ...which is the same as...
$mailTo = MAIL_TO;
With use of constants:
$mailTo = 'mailto#gmail.com';
$mailFrom = 'mailfrom#gmail.com';
$subject = 'Test email';
$message = "Hello World!\n\nThis is my first mail.";
$headers = "From: " . $mailFrom . "\r\nReply-To: webmaster#example.com";
$mailResult = mail($mailTo, $subject, $message, $headers);
Here's a very basic example. I'll leave it up to you to do validation.
HTML:
<form action="path/to/your/script.php" method="post">
<input type="text" name="from" />
<input type="submit" value="Send" />
</form>
PHP:
In PHP, you'll want to use $_REQUEST, $_POST or $_GET depending on the action parameter of the form in your HTML. If you're not sure, use $_REQUEST. The value that goes in the square brackets is the name of attribute of the input from your HTML.
define('TO_ADDRESS', 'user#example.org');
$headers = "From: " . $_REQUEST['from'] . "\r\nReply-To: webmaster#example.com";
$mail = mail(TO_ADDRESS, $subject, $message, $headers);