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!
Related
I am trying to send email from a web page hosted on a shared platform over at fasthosts. I cannot for the life of me get this to work, I had a much more extensive script which checked the validity of email etc, but now I've been reduced to using the basic example from fasthosts and it is still not working.
Please could someone take a look and let me now where I am going wrong...
<?php
// You only need to modify the following two lines of code to customise your form to mail script.
$email_to = "contact#mywebsite.co.uk"; // Specify the email address you want to send the mail to.
$email_subject = "Feedback from website"; // Set the subject of your email.
// This is the important ini_set command which sets the sendmail_from address, without this the email won't send.
ini_set("contact#mywebsite", $email_from);
// Get the details the user entered into the form
$name = $_POST["name"];
$email = $_POST["email"];
$message = $_POST["message"];
// Validate the email address entered by the user
if(!filter_var($email_from, FILTER_VALIDATE_EMAIL)) {
// Invalid email address
die("The email address entered is invalid.");
}
// The code below creates the email headers, so the email appears to be from the email address filled out in the previous form.
// NOTE: The \r\n is the code to use a new line.
$headers = "From: " . $email_from . "\r\n";
$headers .= "Reply-To: " . $email_from . "\r\n"; // (You can change the reply email address here if you want to.)
// Now we can construct the email body which will contain the name and message entered by the user
$message = "Name: ". $name . "\r\nEmail: " . $email . "\r\nMessage: " . $message ;
// Now we can send the mail we've constructed using the mail() function.
// NOTE: You must use the "-f" parameter on Fasthosts' system, without this the email won't send.
$sent = mail($email_to, $email_subject, $message, $headers, "-f" . $email_from);
// If the mail() function above successfully sent the mail, $sent will be true.
if($sent) {
$output = json_encode(array('type'=>'message', 'text' => 'Hi '.$name .' Thank you for contacting us.'));
die($output);
} else {
$output = json_encode(array('type'=>'error', 'text' => 'Could not send mail! Please check your PHP mail configuration.'));
die($output);
}
?>
I'm having an issue with a contact form. The email message is correctly sent but in my inbox appears as "From: anonymous#web.godns.net" and not "From: web#mywebsite.com", and goes directly to SPAM.
I've been looking for similar issues but no one gives the specific answer. I guess if the code is having a syntax mistake or it's a server problem.
This is the PHP file:
<?php
// Check for empty fields
if(empty($_POST['name']) || empty($_POST['email']) || empty($_POST['phone']) || empty($_POST['message']) || !filter_var($_POST['email'], FILTER_VALIDATE_EMAIL)) {
http_response_code(500);
exit();
}
$name = strip_tags(htmlspecialchars($_POST['name']));
$email = strip_tags(htmlspecialchars($_POST['email']));
$phone = strip_tags(htmlspecialchars($_POST['phone']));
$message = strip_tags(htmlspecialchars($_POST['message']));
// Create the email and send the message
$to = "myemail#gmail.com";
$subject = "Mensaje Web de >> $name";
$body = "Recibiste mensaje a través del formulario en la web.\n"."Estos son los datos:\n\nNombre y Apellido: $name\n\nEmail: $email\n\nTeléfono: $phone\n\nTexto del mensaje:\n$message";
$headers= "From: web#mywebsite.com" . "\r\n" .
"Reply-To: $email \r\n" .
'X-Mailer: PHP/' . phpversion();
if(!mail($to, $subject, $body, $headers))
http_response_code(500);
?>
Does anyone figure out what's wrong here?
Thank you,
Alejandra | aleare.design
It may solve your problem or not but it's always a good idea to set a proper sender address. In good old mail() that needs to be done with the $additional_parameters parameter and the syntax is -f followed by an email address with no display name:
mail($to, $subject, $body, $headers, '-fweb#mywebsite.com')
Additionally, make sure that your local SMTP server allows sending messages in the name of web#mywebsite.com. If it doesn't, perhaps you need to get another server and make use of authentication, something that mail() doesn't allow.
In any case, it's really hard to get email right with this function since you need to do everything by yourself and email protocol is not trivial. For instance, I think your code is vulnerable to email headers injection. It's easier to just use a third-party library like Swift Mailer or PHPMailer.
P.S. What are you trying to accomplish with strip_tags(htmlspecialchars())? This will just make user input unreadable for not obvious gain.
This might help you, I don't get it why you put so many text in the header
// Create the email and send the message
$to = "youremail#yourdomain.com"; // Add your email address inbetween the " " replacing username#yourdomain.com - This is where the form will send a message to.
$subject = "Website Contact Form: $name";
$body = "You have received a new message from your website contact form.\n\n"."Here are the details:\n\nName: $name\n\nEmail: $email\n\nPhone: $phone\n\nMessage:\n$message";
$header = "From: noreply#adamar.com\n"; // This is the email address the generated message will be from. We recommend using something like noreply#yourdomain.com.
$header .= "Reply-To: $email"; // this is to automatically reply to your correspondent email rather than your noreply email, I separate it from your header.
also mind to change the variable $headers to $header? Maybe it might help. Wish all the best of it. Cheers!
So this is my first post, I try to tell what my issue's are.
I have bought a domain name that I want to sell.
So I code a simple HTML website with some CSS stuff.
OK. I also have a form in my HTML, that contains this:
<input type="text" placeholder="Amount" name="amount">
<input type="text" placeholder="Name" required name="name">
<input type="text" placeholder="Email Address" required name="email">
<div class="validation">
<button class="btn" name="submit">Send request</button>
$email_to = "email#email.com";
$amount = $_POST["amount"];
$name = $_POST["name"];
$email = $_POST["email"];
$email_subject = "Domeiname";
$headers = "From: " . $email . "\n";
$headers .= "Reply-To: " . $email . "\n";
ini_set("sendmail", $email);
$sent = mail($email_to, $email_subject, $amount, $headers, "-f" .$email);
if ($sent)
{
header("Location: https:mywebsite.com");
} else {
echo "There has been an error sending your comments. Please try later.";
}l
It's working and I receive emails. So my question is, is it safe? Is it vulnerable to hackers?
(I also receive in my Gmail, that this email can be spam/not from me).
Am I doing something wrong?
EDIT: Found another issue: In my email, I only receive the "amount" status and not the "name + email".
There are a number of libraries that will take all the hard work of securely sending email from you - such as swiftmailer.
<?php
require_once 'lib/swift_required.php';
// Sendmail
$transport = Swift_SendmailTransport::newInstance('/usr/sbin/sendmail -bs');
// Create the Mailer using your created Transport
$mailer = Swift_Mailer::newInstance($transport);
// Create a message
$message = Swift_Message::newInstance('Wonderful Subject')
->setFrom(array('john#doe.com' => 'John Doe'))
->setTo(array('receiver#domain.org', 'other#domain.org' => 'A name'))
->setBody('Here is the message itself')
;
// Send the message
$result = $mailer->send($message);
You may also find it very valuable to sign up for a service such as Mailgun and also setup your code to use their servers to actually send the email (there are libraries would setup as a 'transport' to send the message to them via HTTP, and then they email it to the final destination). There are a number of such 'ESP' (Email Service Providers), and many offer a substantial free-tier, so it won't cost you anything for even thousands of emails per month.
It looks as though you are sending an E-mail when a form is submitted. This is perfectly secure; there is no way a hacker could manipulate who the E-mail gets sent to; PHP is server-side code. Thus, $email_to = "email#email.com"; cannot get manipulated from the form itself, as it is hard-coded into your PHP.
Obviously, the $_POST data variables get passed through from the form, so their contents can be manipulated by the form -- though this is required in order for you to be able to retrieve the visitor's name and E-mail address.
PHPMailer did have a recent vulnerability in it, where an attacker could breach your website by entering a certain 'From' E-mail address, but this has since been patched. You still need to allow the user to enter their E-mail address, or you won't know who to reply to.
However, a user would still be able to create additional headers based on you not validating that the 'From' address is an actual valid E-mail address. You should validate this, and only send the E-mail if it is found to be valid:
if (!filter_var($email, FILTER_VALIDATE_EMAIL) === false) {
$sent = mail($email_to, $email_subject, $amount, $headers, "-f" .$email);
}
Note that you're also not actually doing anything with the $name variable. Assuming you're trying to make it display the person's name in the 'FROM' field in the E-mail, you need to pass it as:
$headers = "From: " . $name . " <" . $email . ">\n";
So that it gets rendered as From: Person <email#email.com>.
Hope this helps! :)
Im new to this PHP stuff so please excuse my ignorance
Im after having just one input text box in my flash website where a person just enters there email address and at the click of a button it sends an email to me to a pre defined email address with a predefined subject heading and the email address that was entered in the body of the email
Anyone know of any links or can give some help
all the ones i have found want names email subject message and so on
Any help is appreciated
Mark
EDIT
ok I have the following
In flash I have an input text converted to a movieclip called "addy". Inside the movie clip which has the inputbox which has the variable name "emailaddy"
A Button called "email"
The code i Have running when "email" is clicked is
on (release) {
form.loadVariables("email.php", "POST");
}
the email.php script is as follows
<?php
$sendTo = "mark#here.co.uk";
$subject = "Subscribe to Website";
$headers = "From: Website";
$headers .= "<" . $_POST["addy"] . ">\r\n";
$headers .= "Reply-To: " . $_POST["addy"] . "\r\n";
$headers .= "Return-Path: " . $_POST["addy"];
$message = "Please Subscribe me to Website";
mail(recipient, subject, message, other headers);
mail($sendTo, $subject, $message, $headers);
?>
when I click the button nothing happens
what im after is when the button is clicked for and email to be sent in the following format
To: "mark#here.co.uk"
From: email address specified in text field "addy"
Subject: "Subscribe to Website";
body: "Please subscribe me to Website"
Your help is greatly appreciated
mark
The following code might help:
<?php
$user_mail=$_POST["mail"]; //or $user_mail=$_GET["mail"]; Set to your convenience!
$to_mail="abcde#xyz.com"; //Change to your email address
$message="New user's Email: ".$user_mail; //Change to your requirements
$subject="New user registered"; //Change to your preferred subject
$from="registration#yourwebsite.com"; //Change to your website mail id
mail($to_mail,$subject,$message,"From: $from\n");
To know more about the mail function, please see the documentation.
Well in depth you can do like this
<?php
if($_POST){
$userEmail = $_POST0["emailaddy"]; // textbox variable name comes here
$to = 'abc#xyz.com'; //write down here your email
$subject = 'Subscribe to website'; // your subject goes here
$message = 'Please Subscribe me to Website'; // Mail body message
$headers = 'From: ' . $userEmail . "\r\n" .
'Reply-To: ' . $userEmail . "\r\n" .
'Return-Path: ' . $userEmail; //can send x-Mailer also
mail($to, $subject, $message, $headers);
}else{
echo "Invalid Request";
return false;
}
Don't forget to check first $_POST is happened or not. No need to send Return-path instead of this use x-Mailer which sound good for other mail service providers.
To know more about this read documentation here.
If you want to connect to an SMTP server ,like Postfix or gmail there is a neat php library called PhpMailer.
It is well documentated, so you should be good to go by googleing it :)
This is the first time I've used PHP at all and I'm having trouble implementing a mail form of all things, I can't seem to get this working. Below is my code, I'd be most appreciative if somebody could point me in the right direction in terms of debugging.
<?php
$job_number = $_POST['job_number'];
$completion_time = $_POST['completion_time'];
$email = $_POST['email'];
$formcontent = "From: $email \n \n Job Number: $job_number \n \n Completion Time: $completion_time \n";
$recipient = "data#rak.co.uk";
$subject = "Repeat Order";
$mailheader = "From: $email \r\n";
mail(
$recipient,
$subject,
$formcontent,
$mailheader
)
or die(
"
Error!
"
);
echo( "
<div style='font-size:24px; margin-top: 100px; text-align: center;'>
Thank You!
"
. " - " .
" <a href='home.html' style='color: #1ca03e;'>
Return Home
</a>
</div>
"
);
?>
Thank you,
Cameron
edit: Some more info, the server supports PHP mail scripts as it had one on there before (according to the friend I'm building this for), the error I've had while internal testing is that the mail is being sent but without any of the '$formcontent' content... Only the titles (aka: From:, Job Number:, Completion Time:)
edit edit: if it helps here is a staging server I have it up on at the moment (don't hate me for poor web-design... it's a work in progress) http://temp.fullaf.com/cameron/rak/repeat.html
You can get the swiftmailer package on their site here -> http://swiftmailer.org/
require_once 'swiftmailer/lib/swift_required.php';
function new_mail($subject, $content, $recipients, $from)
{
// Create the message
$message = Swift_Message::newInstance();
// Give the message a subject
$message->setSubject($subject);
// Set the From address with an associative array
$message->setFrom($from);
// Set the To addresses with an associative array
$message->setTo($recipients);
// Give it a body
$message->setBody($content);
$transport = Swift_MailTransport::newInstance();
$mailer = Swift_Mailer::newInstance($transport);
$result = $mailer->send($message);
}
$job_number = $_POST['job_number'];
$completion_time = $_POST['completion_time'];
$email = $_POST['email'];
$message = "From: $email \n \n Job Number: $job_number \n \n Completion Time: $completion_time \n";
$recipients = array('data#rak.co.uk' => 'Your name of choice');
$subject = "Repeat Order";
$from = array($email => 'Name of choice.');
new_mail($subject, $message, $recipients, $from);
I'm currently not in the position where I can access a ftp server to test this specific snippet but try it out. If there are any problems let me know.
Your code is working and sending email without any issues.
Check your email mail Spam box. Some times, the email will go to Spam box.
You are using this "data#rak.co.uk" email address as recipient email. So don't use the same email address for sender email address. Use another email address as sender email.
Make sure, Your email address "data#rak.co.uk" is receiving emails properly, when send email from other email accounts such as yahoo and gmail.
Please make sure, you have setup the mail server properly in your server.