84

I want to send an email with PHP when a user has finished filling in an HTML form and then emailing information from the form. I want to do it from the same script that displays the web page that has the form.

I found this code, but the mail does not send.

<?php 

if (isset($_POST['submit'])) {
    $to = $_POST['email']; 
    $subject = $_POST['name'];
    $message = getRequestURI();
    $from = "zenphoto@example.com";
    $headers = "From:" . $from;

    if (mail($to, $subject, $message, $headers)) {
        echo "Mail Sent.";
    }
    else {
        echo "failed";
    }
}

?>

What is the code to send an email in PHP?

Markus Amalthea Magnuson
  • 8,415
  • 4
  • 41
  • 49
fusi0n
  • 1,059
  • 3
  • 12
  • 21

8 Answers8

177

EDIT (#1)

If I understand correctly, you wish to have everything in one page and execute it from the same page.

You can use the following code to send mail from a single page, for example index.php or contact.php

The only difference between this one and my original answer is the <form action="" method="post"> where the action has been left blank.

It is better to use header('Location: thank_you.php'); instead of echo in the PHP handler to redirect the user to another page afterwards.

Copy the entire code below into one file.

<?php 
if(isset($_POST['submit'])){
    $to = "email@example.com"; // this is your Email address
    $from = $_POST['email']; // this is the sender's Email address
    $first_name = $_POST['first_name'];
    $last_name = $_POST['last_name'];
    $subject = "Form submission";
    $subject2 = "Copy of your form submission";
    $message = $first_name . " " . $last_name . " wrote the following:" . "\n\n" . $_POST['message'];
    $message2 = "Here is a copy of your message " . $first_name . "\n\n" . $_POST['message'];

    $headers = "From:" . $from;
    $headers2 = "From:" . $to;
    mail($to,$subject,$message,$headers);
    mail($from,$subject2,$message2,$headers2); // sends a copy of the message to the sender
    echo "Mail Sent. Thank you " . $first_name . ", we will contact you shortly.";
    // You can also use header('Location: thank_you.php'); to redirect to another page.
    }
?>

<!DOCTYPE html>
<head>
<title>Form submission</title>
</head>
<body>

<form action="" method="post">
First Name: <input type="text" name="first_name"><br>
Last Name: <input type="text" name="last_name"><br>
Email: <input type="text" name="email"><br>
Message:<br><textarea rows="5" name="message" cols="30"></textarea><br>
<input type="submit" name="submit" value="Submit">
</form>

</body>
</html> 

Original answer


I wasn't quite sure as to what the question was, but am under the impression that a copy of the message is to be sent to the person who filled in the form.

Here is a tested/working copy of an HTML form and PHP handler. This uses the PHP mail() function.

The PHP handler will also send a copy of the message to the person who filled in the form.

You can use two forward slashes // in front of a line of code if you're not going to use it.

For example: // $subject2 = "Copy of your form submission"; will not execute.

HTML FORM:

<!DOCTYPE html>
<head>
<title>Form submission</title>
</head>
<body>

<form action="mail_handler.php" method="post">
First Name: <input type="text" name="first_name"><br>
Last Name: <input type="text" name="last_name"><br>
Email: <input type="text" name="email"><br>
Message:<br><textarea rows="5" name="message" cols="30"></textarea><br>
<input type="submit" name="submit" value="Submit">
</form>

</body>
</html>

PHP handler (mail_handler.php)

(Uses info from HTML form and sends the Email)

<?php 
if(isset($_POST['submit'])){
    $to = "email@example.com"; // this is your Email address
    $from = $_POST['email']; // this is the sender's Email address
    $first_name = $_POST['first_name'];
    $last_name = $_POST['last_name'];
    $subject = "Form submission";
    $subject2 = "Copy of your form submission";
    $message = $first_name . " " . $last_name . " wrote the following:" . "\n\n" . $_POST['message'];
    $message2 = "Here is a copy of your message " . $first_name . "\n\n" . $_POST['message'];

    $headers = "From:" . $from;
    $headers2 = "From:" . $to;
    mail($to,$subject,$message,$headers);
    mail($from,$subject2,$message2,$headers2); // sends a copy of the message to the sender
    echo "Mail Sent. Thank you " . $first_name . ", we will contact you shortly.";
    // You can also use header('Location: thank_you.php'); to redirect to another page.
    // You cannot use header and echo together. It's one or the other.
    }
?>

To send as HTML:

If you wish to send mail as HTML and for both instances, then you will need to create two separate sets of HTML headers with different variable names.

Read the manual on mail() to learn how to send emails as HTML:


Footnotes:

  • In regards to HTML5

You have to specify the URL of the service that will handle the submitted data, using the action attribute.

As outlined at https://www.w3.org/TR/html5/forms.html under 4.10.1.3 Configuring a form to communicate with a server. For complete information, consult the page.

Therefore, action="" will not work in HTML5.

The proper syntax would be:

  • action="handler.xxx" or
  • action="http://www.example.com/handler.xxx".

Note that xxx will be the extension of the type of file used to handle the process. This could be a .php, .cgi, .pl, .jsp file extension etc.


Consult the following Q&A on Stack if sending mail fails:

Community
  • 1
  • 1
Funk Forty Niner
  • 74,450
  • 15
  • 68
  • 141
  • Is there a way I could use this mail_handler.php code on the HTML form if I had a php script that generated that page( like index.php) ?? – fusi0n Aug 22 '13 at 13:56
  • @fusi0n Sorry, I don't quite follow :( – Funk Forty Niner Aug 22 '13 at 13:58
  • 1
    @fusi0n Do you mean having the form and the handler in the same page instead of using 2 files? – Funk Forty Niner Aug 22 '13 at 14:12
  • @fusi0n That's what I thought. I edited my answer, reload the page to see it. – Funk Forty Niner Aug 22 '13 at 14:39
  • `code` `code` this is the php code I use, but I get Error: Error loading page. Any idea why is that? – fusi0n Aug 22 '13 at 14:41
  • I tried copying your code exactly and it says that the mail has been sent, but it does not arrive in my inbox. Any way I could check what happens or do you have any idea what could be wrong? – fusi0n Aug 22 '13 at 14:55
  • @fusi0n Did you change `$to = "email@example.com";` to be YOUR email address? – Funk Forty Niner Aug 22 '13 at 15:14
  • Yes, because the email is supposed to go to my inbox with info about the user. – fusi0n Aug 22 '13 at 15:22
  • @fusi0n Have you checked your Spam box maybe? Like I said, I fully tested my code and it went in my Inbox. – Funk Forty Niner Aug 22 '13 at 15:23
  • Yes, I checked my spam folder also :(. Is there anything server-side or anything else that I could check, that might be wrong? – fusi0n Aug 22 '13 at 15:26
  • @fusi0n I don't know. Are you running this from a hosted website, or from your own computer, local? – Funk Forty Niner Aug 22 '13 at 15:27
  • at the moment im running locally – fusi0n Aug 22 '13 at 15:35
  • @fusi0n Ah ok. That could be the problem and that is an area I have almost no knowledge about. Check to see if `mail()` is enabled or something like that, or SMTP settings. That's the best I can think of, sorry. – Funk Forty Niner Aug 22 '13 at 15:38
  • @fusi0n See this page might help http://marc.info/?l=php-general&m=129559166306831 --- you might have to set your email address to `@localhost` or something like that. See this also http://stackoverflow.com/a/17699981/1415724 – Funk Forty Niner Aug 22 '13 at 15:40
  • thank you for your effort, but neither of these links helped me :( – fusi0n Aug 22 '13 at 15:48
  • @fusi0n You're very much welcome. I suggest that you Google the problem that you have regarding receiving mail through a Webserver. It could probably be a simple setting in `php.ini` or path to the mail function. – Funk Forty Niner Aug 22 '13 at 17:58
  • Great answer @Fred-ii-! I added an alert box to the `echo` on my php file. Rather than going to the php file after submission, is there a way to stay on the same page? – esierr1 Feb 11 '16 at 18:21
  • @esierr1 Thanks. Well to stay on the same page, you would need to have both the form and the PHP together in the same file and changing `action="mail_handler.php"` to `action=""` which is the same as "self". However, if you're using the code from my answer with some JS/jQuery, that would be a different animal altogether ;-) *Cheers* – Funk Forty Niner Feb 11 '16 at 19:52
  • Yes, @Fred-ii-. I tried it myself and it didn't work. Is there a way to handle JS properly? Thanks! – esierr1 Feb 12 '16 at 16:06
  • @esierr1 Sorry to hear that. However, I'm not the person to speak with in regards to JS. TBH, I suck big time at client-side coding. – Funk Forty Niner Feb 12 '16 at 16:25
  • @Fred-ii- I know its quite old. I am trying to use your code but i am using button type="submit" instead of – Roxx Apr 01 '16 at 03:25
  • 1
    @CalculatingMachine My guess is that it's a JS problem and JS isn't something I'm very good at, especially when it comes to event firing stuff. Best I can suggest is to look at your console, and/or post a question. I'm sure you'll find someone who'll be able to help, *cheers* – Funk Forty Niner Apr 01 '16 at 11:49
  • the attribute 'action' shouldn't be blank. i.e. action="" is not valid. remove it all for html5. – Milche Patern Jun 10 '16 at 19:05
  • 1
    @MilchePatern Thanks for that. I'll modify my answer when I get back. I have to leave like *right now* - lol Cheers – Funk Forty Niner Jun 10 '16 at 19:34
  • 1
    @MilchePatern I have made an edit to the answer, which in order to conserve the originally given answer, has been included under **Footnotes:**. – Funk Forty Niner Jun 10 '16 at 23:10
  • This answer won't always work, as it spoofs someone's email address (whoever is filling the form), which may get rejected by some mail authentication mechanisms. My mail server, for example, rejects any attempt to send me emails on behalf of yahoo.com and aol.com users. (I've just found out that a 3rd party solution I've been using has missed years of support emails from users with those email addresses). Instead, put your own address in the From field and place the sender's address in the body of the message (the Reply-To field would be more convenient, but it might trigger the same issue). – Arda Jan 14 '19 at 02:23
  • I've just tested the Reply-To header with my server, and the previously blocked email addresses (when in the From header) make it through fine. Your mileage may vary depending on your server's implementation. Reply-To is convenient because you can then simply "reply" to emails you receive via your website. – Arda Jan 14 '19 at 03:13
  • Regarding HTML5, section 4.10.1.3 that's quoted in this answer is _"non-normative"_ (just an introductory example). According to section 4.10.18.6., which appears to be normative, _“when the [action] content attribute is missing or its value is the empty string, the document’s URL must be returned instead.”_ Hence, you don't have to specify the action in HTML5. But as per _"The action and formaction content attributes, if specified, must have a value that is a valid non-empty URL"_ that's in the same section, I wouldn't leave action blank, but omit it altogether instead. – Arda Jan 15 '19 at 18:47
  • How do I make it so the browser doesn't change to the PHP page? I want to have the user click "Submit" and the user will stay on the page. – Aaron Franke Jun 19 '20 at 23:07
  • @AaronFranke You'll most likely need to use Javascript / jQuery for that. This cannot be done in PHP. It can in a way but the page will reload in its own file. – Funk Forty Niner Jun 20 '20 at 00:13
5

PHP script to connect to a SMTP server and send email on Windows 7

Sending an email from PHP in Windows is a bit of a minefield with gotchas and head scratching. I'll try to walk you through one instance where I got it to work on Windows 7 and PHP 5.2.3 under (IIS) Internet Information Services webserver.

I'm assuming you don't want to use any pre-built framework like CodeIgniter or Symfony which contains email sending capability. We'll be sending an email from a standalone PHP file. I acquired this code from under the codeigniter hood (under system/libraries) and modified it so you can just drop in this Email.php file and it should just work.

This should work with newer versions of PHP. But you never know.

Step 1, You need a username/password with an SMTP server:

I'm using the smtp server from smtp.ihostexchange.net which is already created and setup for me. If you don't have this you can't proceed. You should be able to use an email client like thunderbird, evolution, Microsoft Outlook, to specify your smtp server and then be able to send emails through there.

Step 2, Create your Hello World Email file:

I'm assuming you are using IIS. So create a file called index.php under C:\inetpub\wwwroot and put this code in there:

<?php

  include("Email.php");

  $c = new CI_Email();

  $c->from("FromUserName@foobar.com");
  $c->to("user_to_receive_email@gmail.com");
  $c->subject("Celestial Temple");
  $c->message("Dominion reinforcements on the way.");
  $c->send();
  echo "done";
?>

You should be able to visit this index.php by navigating to localhost/index.php in a browser, it will spew errors because Email.php is missing. But make sure you can at least run it from the browser.

Step 3, Create a file called Email.php:

Create a new file called Email.php under C:\inetpub\wwwroot.

Copy/paste this PHP code into Email.php:

https://github.com/sentientmachine/standalone_php_script_send_email/blob/master/Email.php

Since there are many kinds of smtp servers, you will have to manually fiddle with the settings at the top of Email.php. I've set it up so it automatically works with smtp.ihostexchange.net, but your smtp server might be different.

For example:

  1. Set the smtp_port setting to the port of your smtp server.
  2. Set the smtp_crypto setting to what your smtp server needs.
  3. Set the $newline and $crlf so it's compatible with what your smtp server uses. If you pick wrong, the smtp server may ignore your request without error. I use \r\n, for you maybe \n is required.

The linked code is too long to paste as a stackoverflow answer, If you want to edit it, leave a comment in here or through github and I'll change it.

Step 4, make sure your php.ini has ssl extension enabled:

Find your PHP.ini file and uncomment the

;extension=php_openssl.dll

So it looks like:

extension=php_openssl.dll

Step 5, Run the index.php file you just made in a browser:

You should get the following output:

220 smtp.ihostexchange.net Microsoft ESMTP MAIL Service ready at 
Wed, 16 Apr 2014 15:43:58 -0400 250 2.6.0 
<534edd7c92761@summitbroadband.com> Queued mail for delivery 
lang:email_sent

done

Step 6, check your email, and spam folder:

Visit the email account for user_to_receive_email@gmail.com and you should have received an email. It should arrive within 5 or 10 seconds. If you does not, inspect the errors returned on the page. If that doesn't work, try mashing your face on the keyboard on google while chanting: "working at the grocery store isn't so bad."

Eric Leschinski
  • 146,994
  • 96
  • 417
  • 335
4

If you haven't already, look at your php.ini and make sure the parameters under the [mail function] setting are set correctly to activate the email service. After you can use PHPMailer library and follow the instructions.

Eric Leschinski
  • 146,994
  • 96
  • 417
  • 335
KB9
  • 599
  • 2
  • 7
  • 16
3

You can also use mandrill app to send the mail in php. You will get the API from https://mandrillapp.com/api/docs/index.php.html where you can find the complete details about emails sended and other details.

Hareesh
  • 1,507
  • 3
  • 21
  • 43
2

You need to add an action into your form like:

<form name='form1' method='post' action='<?php echo($_SERVER['PHP_SELF']);'>
    <!-- All your input for the form here -->
</form>

Then put your snippet at the top of the document en send the mail. What echo($_SERVER['PHP_SELF']); does is that it sends your information to the top of your script so you could use it.

Adil
  • 240
  • 1
  • 6
  • 19
Moduo
  • 623
  • 6
  • 17
1

You need a SMPT Server in order for

... mail($to,$subject,$message,$headers);

to work.

You could try light weight SMTP servers like xmailer

Andrei CACIO
  • 2,101
  • 15
  • 28
1

Here are the PHP mail settings I use:

//Mail sending function
$subject = $_POST['name'];
$to = $_POST['email'];
$from = "zenphoto@example.com";

//data
$msg = "Your MSG <br>\n";       

//Headers
$headers  = "MIME-Version: 1.0\r\n";
$headers .= "Content-type: text/html; charset=UTF-8\r\n";
$headers .= "From: <".$from. ">" ;

mail($to,$subject,$msg,$headers);
echo "Mail Sent.";
Eric Leschinski
  • 146,994
  • 96
  • 417
  • 335
-1

I think one error in the original code might have been that it had:

$message = echo getRequestURI();

instead of:

$message = getRequestURI();

(The code has since been edited though.)

Markus Amalthea Magnuson
  • 8,415
  • 4
  • 41
  • 49