Published on

How to send email in PHP?

php-send-email-form-banner

Send Email In PHP Step By Step

To send mail from localhost XAMPP using Gmail, configure XAMPP after installing it. Follow all intruction step by step.

Step 1 : Configure xampp server

  • Go to your xampp installation directory e.g (C:\xampp).
  • Open C:\xampp\php\php.ini in your text editor.
php-ini-file
  • Find [mail function] by pressing ctrl + f and edit some values in your file.
php.ini
SMTP=smtp.gmail.com
smtp_port=587
sendmail_from = YourGmailId@gmail.com
sendmail_path = "\"C:\xampp\sendmail\sendmail.exe\" -t"
  • Now, Open C:\xampp\sendmail\sendmail.ini file and Find [sendmail] by pressing ctrl + f and edit some values in your file.
php-ini-file
sendmail.ini
smtp_server=smtp.gmail.com
smtp_port=587 or 25 //use any of them
error_logfile=error.log
debug_logfile=debug.log
auth_username=YourGmailId@gmail.com
auth_password=Your-Gmail-Password
force_sender=YourGmailId@gmail.com(optional)
  • After compeleting this configuration now your server ready to send email.

Step 2 : Code Contact Form

  • Create a new directory contact_form in C:\xampp\htdocs\ directory.
  • Create a new file index.html in contact_form directory. then copy the following code in index.html to create contact form.
index.html
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <!--===== CSS =====-->
    <link rel="stylesheet" href="assets/css/styles.css">
    <title>Login form style google</title>
</head>
<body>
    <div class="l-form">
        <form action="" class="form" method="post" id="form">
            <h1 class="form__title">Email</h1>
            <div class="form__div">
                <input type="email" class="form__input" placeholder=" " name="to">
                <label for="" class="form__label">To</label>
            </div>
            <div class="form__div">
                <input type="text" class="form__input" placeholder=" " name="subject">
                <label for="" class="form__label">Subject</label>
            </div>
            <div class="form__div form__textarea__div">
                <textarea class="form__input" rows="5" placeholder=" " name="msg"></textarea>
                <label for="" class="form__label">Message</label>
            </div>
            <input type="submit" class="form__button" id="submit" value="Send">
        </form>
    </div>
    <script type="text/javascript" src="assets/js/main.js"></script>
</body>
</html>

  • Create a new directory assets in C:\xampp\htdocs\contact_form directory.
  • Create two more directories js and css in C:\xampp\htdocs\contact_form\assets directory.
  • Create a new file main.js in C:\xampp\htdocs\contact_form\assets\js directory.
  • Create a new file styles.css in C:\xampp\htdocs\contact_form\assets\css directory.
  • Copy the following code in styles.css file to style your form.
styles.css
/*===== GOOGLE FONTS =====*/
@import url("https://fonts.googleapis.com/css2?family=Roboto:wght@400;500&display=swap");
/*===== VARIABLES CSS =====*/
:root{
  /*===== Colores =====*/
  --first-color: #1A73E8;
  --input-color: #80868B;
  --border-color: #DADCE0;

  /*===== Fuente y tipografia =====*/
  --body-font: 'Roboto', sans-serif;
  --normal-font-size: 1rem;
  --small-font-size: .75rem;
}
  
/*===== BASE =====*/
*,::before,::after{
  box-sizing: border-box;
}
body{
  margin: 0;
  padding: 0;
  font-family: var(--body-font);
  font-size: var(--normal-font-size);
  background-color: #f3f2ef;
}
h1{
  margin: 0;
}

/*===== FORM =====*/
.l-form{
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100vh;
}
.form{
  width: 360px;
  padding: 2rem 2rem;
  border-radius: 1rem;
  background-color: #FFFFFF;
}
.form__title{
  font-weight: 400;
  margin-bottom: 2rem;
  position: relative;
}

/* .form__title::before {
  content: '';
  position: absolute;
  background-color: #000;
  width: 50%;
  height: 2px;
  bottom: -.75rem;
  left: 0;
  transition: .5s;
} */

.form__div{
  position: relative;
  height: 48px;
  margin-bottom: 1.5rem;
}

.form__textarea__div{
  height: 100px;
}

.form__input{
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  font-size: var(--normal-font-size);
  border: 1px solid var(--border-color);
  border-radius: .5rem;
  outline: none;
  padding: 1rem;
  background: none;
  z-index: 1;
}
.form__label{
  position: absolute;
  left: 1rem;
  top: 1rem;
  padding: 0 .25rem;
  background-color: #fff;
  color: var(--input-color);
  font-size: var(--normal-font-size);
  transition: .3s;
}
.form__button{
  display: block;
  margin-left: auto;
  padding: .75rem 2rem;
  outline: none;
  border: none;
  background-color: var(--first-color);
  color: #fff;
  font-size: var(--normal-font-size);
  border-radius: .5rem;
  cursor: pointer;
  transition: .3s;
}
.form__button:hover{
  box-shadow: 0 10px 36px rgba(0,0,0,.15);
}

/*Input focus move up label*/
.form__input:focus + .form__label{
  top: -.5rem;
  left: .8rem;
  color: var(--first-color);
  font-size: var(--small-font-size);
  font-weight: 500;
  z-index: 10;
}

/*Input focus sticky top label*/
.form__input:not(:placeholder-shown).form__input:not(:focus)+ .form__label{
  top: -.5rem;
  left: .8rem;
  font-size: var(--small-font-size);
  font-weight: 500;
  z-index: 10;
}

/*Input focus*/
.form__input:focus{
  border: 1.5px solid var(--first-color);
}


@media screen and (min-width: 568px){
  .form{
    width: 70%;
    box-shadow: 0 10px 25px rgba(92,99,105,.2);
  }

}

@media screen and (min-width: 768px){
  .form{
    width: 50%;
  }
}
  • After styling your form Copy the following code in main.js file to send email data to backend server.
main.js
const formEl = document.getElementById('form');
const submitBtn = document.getElementById('submit');


formEl.addEventListener('submit', (e) => {
    e.preventDefault();
});



// Ajax
submitBtn.onclick = () => {
    let xhr = new XMLHttpRequest();
    xhr.open('POST', 'api/send_email.php', true);
    xhr.onload = () => {
        if (xhr.readyState == XMLHttpRequest.DONE && xhr.status == 200) {
            let data = xhr.response;

            if (data == 'success') {
                alert('Email sent successfully');
                submitBtn.value = 'Send';
                submitBtn.disabled = false;
                formEl.reset();
            }

            if (data == 'error') {
                alert('Something went wrong');
                submitBtn.value = 'Send';
                submitBtn.disabled = false;
            }

            if (data == 'missing_fields') {
                alert('All fields are required');
                submitBtn.value = 'Send';
                submitBtn.disabled = false;
            }

        }
    }

    xhr.send(new FormData(formEl));
    submitBtn.value = 'Loading ...';
    submitBtn.disabled = true;
}

  • Now your frontend part is completed.
  • let's now create new directory api in C:\xampp\htdocs\contact_form directory.
  • Create a new file send_mail.php in api directory.
  • Copy the following code in send_email.php for sending email.
send_email.php
<?php
    $to = $_POST['to'];
    $subject = $_POST['subject'];
    $msg = $_POST['msg'];
    $headers = 'From: iamtalib8010@gmail.com';

    if (!$to && !$subject && !$msg) {
        echo "missing_fields";
    } else {
        if (mail($to, $subject, $msg, $headers)) {
            echo "success";
        } else {
            echo "error";
        }
    }
?>
  • Now your goodlooking form is ready to sending mail.

Download Source Code