You can use the PHP mail() function to send an email with PHP. The simplest way to do this is to send a text email. This is one way to handle sending you the results when a visitor to your website fills out a form.

Basic PHP email() fuction code

Below is the code for the baic email function. We can take the script and actually use a form on our website to set the variables in the script above to send an email.

<?php
//if "email" variable is filled out, send email
  if (isset($_REQUEST['email']))  {
  
  //Email information
  $admin_email = "someone@example.com";
  $email = $_REQUEST['email'];
  $subject = $_REQUEST['subject'];
  $comment = $_REQUEST['comment'];
  
  //send email
  mail($admin_email, "$subject", $comment, "From:" . $email);
  
  //Email response
  echo "Thank you for contacting us!";
  }
  
  //if "email" variable is not filled out, display the form
  else  {
?>

 <form method="post">
  Email: <input name="email" type="text" /><br />
  Subject: <input name="subject" type="text" /><br />
  Message:<br />
  <textarea name="comment" rows="15" cols="40"></textarea><br />
  <input type="submit" value="Submit" />
  </form>
  
<?php
  }
?>

So let’s now review what the form is actually doing.

1. The first part checks to make sure the email input field is filled out. If it is not, then it will display the HTML form on the page. If the email is in fact, set (after the visitor fills out the form), it is ready to send.

2. When the submit button is pressed, after the form is filled out, the page reloads and reads that the email input is set, so it sends the email.

Keep in mind, this is a basic tutorial to explain how to use the mail() function in PHP. Using the method, exactly the way it is, can be insecure and should not be used on your website. This tutorial is aiming to provide you the basic of how to use phpmail() and for further use, you may want to look into securing your code to possible hacks.

To learn more about the PHP email function, please see the article on How to create a custom PHP contact form with more information on validation and error checking. If you need further assistance please feel free to ask a question on our support center.

Did you find this article helpful?

We value your feedback!

Why was this article not helpful? (Check all that apply)
The article is too difficult or too technical to follow.
There is a step or detail missing from the instructions.
The information is incorrect or out-of-date.
It does not resolve the question/problem I have.
How did you find this article?
Please tell us how we can improve this article:
Email Address
Name

new! - Enter your name and email address above and we will post your feedback in the comments on this page!

Related Questions

Here are a few questions related to this article that our customers have asked:
Emails sent from my website have the server name in them
Would you like to ask a question about this page? If so, click the button below!
Ask a Question
n/a Points
2014-04-10 3:26 am

Hi , 

This code is working properly and display ed the msg as Thank you for contacting us but mail is not send to the correspomding mail address.. pls give any suggestions...

Staff
9,968 Points
2014-04-10 4:56 am
Hello Sankar,

It's possible that the message is ending up in a spam folder in the recipient's email address due to the mail coming directly from a PHP script.

If that is the case, you could use something like phpMailer in order to send an SMTP authenticated email.

Either that or there is some incorrect information typed in to your script. The Thank you for contacting us! message is displayed if the email form is submitted, but it doesn't actually check to ensure that the mail was delivered. If you have access to the server's mail logs, you should be able to see if the PHP mail attempt is making it to the local server to even attempt a delivery out.

It looks like we might need to update the example script used in this guide to at least wrap the code with if (!mail( ...)){ echo "Failure" } code to see if the server accepts the PHP mail attempt. However this is more just a proof of concept then something you'd probably want to use on a live contact form for your website.

- Jacob
n/a Points
2014-04-11 12:07 am

Hi Jacob, 

 i was alredy used the phpmailer code it was shown the error of Message was not sent.Mailer error: SMTP connect() failed.. 

Staff
9,968 Points
2014-04-11 12:20 am
Hello Sankar,

If you're getting a SMTP connect() failed error, then this means your PHP script can't establish a SMTP connection with the server you've entered into your script.

Are you possibly trying to connect to a secure mail server by chance? You might need some additional settings in your phpMailer script such as:

$mail->SMTPSecure = 'tls';
$mail->Host = "secure.example.com";


If you're still having issues let us know.

- Jacob
n/a Points
2014-04-25 2:13 am

mail is not send to the correspomding mail address.. pls give any suggestions...and i m a new devoloper to php socan u sugest me how to use

 phpMailer script...

 

Staff
9,479 Points
2014-04-25 7:52 am
for information on using phpMailer, I recommend that you review our article on using phpMailer to send mail using PHP.
n/a Points
2014-07-02 3:30 am

how to work SMTP i Dont no can anyone explais pls.... advance thank

Staff
20,312 Points
2014-07-02 7:38 am
Hello Darshan,

SMTP settings are explained here. If you need to send an SMTP authenticated message you may want to check out the phpmailer article.

Kindest Regards,
Scott M
n/a Points
2014-05-13 9:23 pm

Just wanted to mention an issue I just ran across in the hopes that it might help someone else.  In our situation we use inmotion for web hosting, but host email for the same domain locally in our network. When the domain was set up on inmotion, thedefault setting was to use InMotion's MX server, so all email sent to address on our domain were attempted delivery to inmotion rather than our mail server.  I think I've fixed this by setting the mx servers to be remote instead of local.

Staff
9,968 Points
2014-05-14 5:44 pm
Hello Nathan, and thanks for the comment!

Yes you are correct that if your domain's email is not hosted with us, when you try to deliver from a PHP script it will try to deliver it locally unless you change DNS records to have email hosted by a 3rd party.

You also need to set the Email Routing option to Remote Mail Exchanger instead of the local one like you mentioned.

Thanks again for your comment!

- Jacob
n/a Points
2014-06-27 5:28 am

Please, i am sending email via phpmail() with a link, the link work perfectly but did not display any information posted to the link from sql. And even the email is not  entering into inbox of my client.

can you help me? 

Staff
20,312 Points
2014-06-27 9:09 am
Hello Olorunnisola,

If you are not getting any errors or messages saying the email was not sent, but the recipient is not able to see the email, you will want to contact our Live Support team to see if they can confirm the email actually left the server. If it did, then the script worked properly and the issue maybe on the receiving end. If not, they may be able to see something specific to advise you on a next step.

Kindest Regards,
Scott M
n/a Points
2014-06-27 5:33 am

Please someone teach me how to create ds text formats and attached files form computer to a textarea on a webpage.

Staff
20,312 Points
2014-06-27 9:12 am
Hello Olorunnisola,

We are unfamiliar with what you mean by ds text format. Could you be more specific in what you are trying to accomplish?

Kindest Regards,
Scott M
n/a Points
2014-06-27 10:27 am

Thank you scott, 

here are my codes:

    //var_dump($link);

//$msg = wordwrap($msg,70);

   $subject = "Call For Meeting";

   $message = "Dear"." "."Sir\Madam,".

"You had been invited to attend a meeting by the name organization"." ".$org_ind." "."that is to hold on"." ".$date." "."by"." ".$start_time." "."via online, Based on"." ".$meeting_title."."."Your feedback about this proposed meeting will be of better help for the preparation.

Please click to give your view."." "."<a href='http://exolvetechnologies.com/meeting/Notification.php?call_for_meeting.php = $meetingId'>Notification</a>"." "."Thank you.<br>";

// Always set content-type when sending HTML email

$headers = 'MIME-Version: 1.0'. "\r\n";

$headers .= 'Content-type:text/html;charset=UTF-8'. "\r\n";

$headers .= 'From: Gentlesoul <emmanuelabiodun2011@live.com>'. "\r\n";

   foreach($_POST['division_name'] as $key =>$email)

  {

      $mail = mail($email,$subject,$message,$headers);

      //var_dump($email);

        if ($mail) {

      echo "<p>Message sent!</p>";

     } else {

       echo "<p>Message delivery failed...</p>";

     }

  }

The project is my own personal project that i want to host by tuesday, please help me.

have not being here before, this will be my first time.

About the text format! I mean to give client opportunity to bold,italic or number list to typing text has he or she type.

 

 

   echo "<h4>Meeting set successful!</h4>";

}

n/a Points
2014-06-27 10:33 am

on my own system here, if i view my mail send has a text, i saw everything.

But on other peoples laptop, they saw the message and the link but inside the link all the field i call from mysql server to that notification page was not showing.

Staff
10,345 Points
2014-06-27 12:00 pm
Hello Olorunnisola,

Thank you for contacting us today. Since you are having trouble coding a PHP contact form, I recommend following our updated guide on How to create a custom PHP contact form with validation.

That tutorial provides a successful example that should help you code your form.

If you have any further questions, feel free to post them below.
Thank you,

-John-Paul
n/a Points
2014-06-30 4:35 pm

I am using Wordpress WooCommerce and my order confirmation emails are not being sent. I am using an email forward to send mail (example@mydomain.com forwards to an AOL email account). Would this prevent emails from being sent if I am using the default DNS records? I also have not changed the Email Routing option to Remote Mail Exchanger.

Staff
9,968 Points
2014-06-30 5:36 pm
Hello Fawn,

I would recommend sending your order confirmations directly to an email account hosted on the same domain as your WordPress site to rule out any 3rd party delivery errors.

If you are missing any order confirmations at your AOL.com address I would suggest that you login to webmail and check for them locally on the server.

I do see some delivery errors from your account to AOL.com and this will happen from time to time, as AOL offers free email accounts and sometimes will reject automated messages from servers, especially on their first delivery attempts. This is also referred to as temporary defferment and is mentioned on this AOL page about 421 errors which is what some of your mails are getting rejected by.

Please let us know if you had any further questions.

- Jacob
n/a Points
2014-07-06 2:37 pm

i'm new in programming, i created a form to send email from my website to yahoomail but i got this error

Failed to connect to mailserver at "localhost" port 25, verify your "SMTP" and "smtp_port" setting in php.ini or use ini_set()

what can i do

Staff
9,968 Points
2014-07-06 6:42 pm
Hello Morphy,

As your PHP error states, it can't connect to the server localhost on port 25.

You'll need to check with your web host to find out what mail server you should be using. You might need to send mail with phpMailer instead of the default PHP mail() function depending on your server configuration.

You more than likely need to define some SMTP settings, and use the same server and account information you would use when setting up a normal email account on your desktop. Or your web host might let you know you need to define another SMTP port rather than 25 in your php.ini file.

- Jacob
n/a Points
2014-07-06 11:41 pm

hi, i want to create auto responder and get the data into database and its like send a data differently to sender. help me

how could i create it. im very new in php

Staff
20,312 Points
2014-07-07 7:12 am
Hello Eihton,

While not a difficult task, it would require a few more pieces to be added. To auto respond to the customer, you would need to add another piece of code that emails out that the information was received. Then, to add the data to the database you would need to have the proper tables set up in an existing database, code for php to connect to the database, then build your SQL query using the information input by the user as the data to insert. Finally you would insert that data into the database.

Unfortunately we currently do not have that type of tutorial information available, however there are many articles and tutorials around the web for each part that is required. I have given you the layout, so go from there and see if you can find code samples to assist. Be sure to also read up on error checking and avoiding SQL injection from malicious users to protect your database. We do have an article that may help you get started.

Kindest Regards,
Scott M
n/a Points
2014-07-09 11:17 am

Warning: mail(): Failed to connect to mailserver at &quot;localhost&quot; port 25, verify your &quot;SMTP&quot; and &quot;smtp_port&quot; setting in php.ini or use ini_set() in C:\wamp\www\design\mail.php on line 13

what will i do now

Staff
20,312 Points
2014-07-09 11:36 am
Hello Antara,

When you use 'localhost' in your settings, that means it will look on the current computer. If you are using this on your local computer, yuo likely do not have it set up as a mail server, which is why you are getting the message. You will need to have it point to a server with mail serving functionality, such as your webhosting server.

Kindest Regards,
Scott M
n/a Points
2014-08-21 1:02 am

Q .As u ve mentioned here

$admin_email = "someone@example.com";to send mail to that particular mail address.. I m using phpmailer n its working fine for me to send mail to any gmail or yahoo mail but not to any custom mail address. 

I want to send mail to any custom domain address by phpmailer. Any help here  ??

Staff
20,312 Points
2014-08-21 7:39 am
Hello Pooja,

If the you are successfully sending emails to some addresses but not others, then the issue would not likely be with the function. You will want to test by sending an email from your server via webmail to the address that is not receiving it. Look for a return message in that email account for the reason why it is not getting through.

Kindest Regards,
Scott M
n/a Points
2014-08-26 5:50 am
should give the explanatory example like on w3 schools (try yourself).
Staff
10,345 Points
2014-10-06 10:28 am
Hello priya,

Thank you for your suggestion. For anyone else who may find this post, here is a helpful link to the w3Schools page on PHP 5 mail() Function.

Thank you,
John-Paul
n/a Points
2014-09-05 6:34 pm

Hi there, i have made use of the basic PHP mail code thanks to you but the issue im having is that the email comes through to me from my hosting server and no comments added to the email... subject is the visitors email address as i set it... see below and please advise if i am doing it wrong:

<?php//if "email" variable is filled out, send email  if (isset($_REQUEST['email']))  {    //Email information  $to = "admin@mydomain.co.za";  $name = $_REQUEST['name'];  $email = $_REQUEST['email'];  $telephone = $_REQUEST['telephone'];  $comments = $_REQUEST['comments'];    //send email  mail($to,$name,$comments);    //Email response  echo "Thank you for contacting us!";  }    ?>

Staff
17,855 Points
2014-09-05 6:50 pm
Hello Mo,

Make sure that you when you use the code above, that it's spaced out with the comments on their own line - like the following:

//if "email" variable is filled out, send email

if (isset($_REQUEST['email'])) {

//Email information

$to = "admin@mydomain.co.za";
$name = $_REQUEST['name'];
$email = $_REQUEST['email'];
$telephone = $_REQUEST['telephone'];
$comments = $_REQUEST['comments'];

//send email

mail($to,$name,$comments);

//Email response

echo "Thank you for contacting us!";
}
?>


Your email form requires should be asking for the comment as well. As per the code above, the form section has "comment" set in the text area. I hope that helps to clarify the issue! Please let us know if you have any further questions.

Regards,
Arnel C.

n/a Points
2014-09-05 8:36 pm

Hi,

Thank you for the speedy reply.

I have made changes to the PHP code and now have the message come through in the body of the mail but still cannot get the visitors email to come up as FROM:.... just comes from my webhost name. see code below:

<?php

//if "email" variable is filled out, send email  if (isset($_POST ['submit'] ))  {    //Email information  $to = "admin@squareonline.co.za";  $from = 'email';  $name = $_POST['name'];  $email = $_POST['email'];  $message = $_POST['message'];    //send email  mail($to,$email, $name, $message,$from);    //Email response  echo "Thank you for contacting us! We will contact you shortly ";  }  ?>

Staff
17,855 Points
2014-09-05 8:54 pm
Hello Mo,

If you look closely at your code, take a close at your $from. I think that's the problem. Make sure you're using the right variable there and then everything should be okay.

I hope that helps!

Regards,
Arnel C.
n/a Points
2014-10-02 5:57 am

pls i am new in web designing and development. how can i design a php webpage that i can use to send and recieve mail like that of yahoo and gmail. it will have all the features like the trash box, draft box, inbox, sent and delet links. if you can send m the codes and syntax it will be welcome. pls forward to my email

Staff
20,312 Points
2014-10-02 1:27 pm
Hello Chike,

While your question is about email, it does not relate to this article directly. I have moved your question to be a brand new question. You can find it here.

Kindest Regards,
Scott M
n/a Points
2014-10-13 5:00 am

following code is not working

-----------------------------------------------------

 

<?php    $to = 'satbir4@gmail.com';        $subject = 'Website Change Reqest';        $message="Message Goes Here";    $headers = "MIME-Version: 1.0\r\n";    $headers .= "Content-Type: text/html; charset=ISO-8859-1\r\n";    if (mail($to, $subject, $message, $headers))    {      echo 'Your message has been sent.';    }        else    {      echo 'There was a problem sending the email.';    }?>

Staff
20,312 Points
2014-10-13 10:43 am
Hello Satbir,

Are you getting an error message? If so, what is it? Where are you trying to use this code? Is it a webserver or a WAMP, XAMP, LAMP setup?

Kindest Regards,
Scott M
n/a Points
2014-10-24 1:37 pm

I use LAMP postfix centos and this script :)) i recive Thank you for contacting us! but i dont recive the mail please help me

Staff
20,312 Points
2014-10-24 2:56 pm
Hello,

You will need to check in your email logs to see if the email went out or if there is an error message.

Kindest Regards,
Scott M
n/a Points
2014-10-28 9:48 pm

this code is selecting an email address from my database and is going to send a message to the selected email. the code works fine but not the mail function for $to = $address

$to = $address;

(mail($to,$subject,$txt,$headers);

 

 

// select statement        $SQLString = "SELECT email\n"        . "FROM tutor\n"        . "WHERE MATCH(text_data) AGAINST ('{$messageText}' IN BOOLEAN MODE)\n"        . "GROUP BY id\n"        . "ORDER BY sum(5) DESC";    echo $SQLString;          $result = mysql_query($SQLString);        // Verify it worked        if (!$result) echo mysql_error();        // execute select statement        $row = mysql_fetch_row($result);        // Should show you an integer result.        $address = print_r($row, true);        echo $address;                $to = $address;        $subject = "testing...";        $txt = $messageText;        $headers = $senderPhone;                if (mail($to,$subject,$txt,$headers))        {        echo "successful";        }        else        {        echo "error";        }

 

thanks for any help in advance :)

Staff
20,312 Points
2014-10-29 9:07 am
Hello Kaleb,

From the way you phrased your question, it seems that you are having issues with $to taking the value of $address. The code snippet you provided does not show where the $address variable is filled. What do you get when you echo $address? The $to = $address is not a function, but an assignment, making $to the value of whatever is in $address at the time. Do the other variables ($subject, $txt, etc) receive their values?

The mail($to,$subject,$txt,$headers) function is called but you do not have any code to catch and display the return code to know why it is failing. You will need to do that in order to understand what is going on.

Kindest Regards,
Scott M
n/a Points
2014-11-11 5:36 am

Hello Iam Alaa i have error and i can not find it can help me when i sent to email see this massage what can i do

Deprecated: Function eregi() is deprecated in C:\wamp\www\Light\js\sendmail.php on line 49

 

 

Staff
9,479 Points
2014-11-11 10:40 am
This means that you are using a function that has been removed from newer versions of PHP within that code located at C:\wamp\www\Light\js\sendmail.php. You will need to further investigate the code of that file and re-write the PHP to allow it to work on newer versions of PHP.

Post a Comment

Name:
Email Address:
Phone Number:
Comment:
Submit

Please note: Your name and comment will be displayed, but we will not show your email address.

43 Questions & Comments

Post a comment

Back to first comment | top

Need more Help?

Search

Ask the Community!

Get help with your questions from our community of like-minded hosting users and InMotion Hosting Staff.

Current Customers

Chat: Click to Chat Now E-mail: support@InMotionHosting.com
Call: 888-321-HOST (4678) Ticket: Submit a Support Ticket

Not a Customer?

Get web hosting from a company that is here to help. Sign up today!