Contact forms make it easy for the visitors of your site to contact you. Contact forms are available in various CM systems, but if you are creating your own site, you have to create the contact form yourself. The messages thus sent by the users have to be stored in databases and you have to constantly check the database for new messages. To overcome this problem, it’s better to directly send the messages to your inbox.

In my previous post, I gave the function send_mail which can be used to send free mails using the Mailgun API.

We can use that function in our contact form to send the messages given by the user directly to you. If you haven’t seen the send_mail() function yet, see this post. We will create a contact form which sends the messages directly to the site admin using Mailgun API and PHP. We should create our form first.

<form action="contact.php" method="POST">
<input type="text" name="name" placeholder="Your Name" size="40"/><br/>
<textarea name="message" cols="40" rows="10"></textarea><br/>
<input type="submit" value="Send Message" name="submit"/>


This is the page where the form data will be sent to. This file checks if all the fields are filled or not and if all are filled, it will send the email :

  $name = $_POST['name'];
  $msg = $_POST['message'];
  if($name != "" && $msg != ""){
    $ip_address = $_SERVER['REMOTE_ADDR'];
    send_mail("[email protected]","New Message","The IP ($ip_address) has sent you a message : <blockquote>$msg</blockquote>");
    echo "<h2 style='color:green;'>Your Message Has Been Sent</h2>";
    echo "<h2 style='color:red;'>Please Fill Up all the Fields</h2>";

The email sent will have the IP address of the user and the message of the user.