How to create a free PHP contact form with SendGrid?

I’m a huge fan of SendGrid. They are an email delivery service and provides an API to facilitate your sending of emails.

Building a contact form for your visitors is one of the crucial steps whenever you’re setting up a new website. I’m gonna show you how to do so for free with SendGrid.

  1. Sign up for a free SendGrid account
  2. Install the SendGrid PHP libraries with Composer in your working directory (If you don’t use already use Composer, I strongly recommend looking into it.)

    composer require sendgrid/sendgrid
    
  3. Create your form. Something like this should suffice.

    <form method='post' action='processmail.php'>
        <input type="text" name="name" placeholder="Your Name" required><br />
        <input type="text" name="email" placeholder="Your Email" required><br />
        <textarea class="input" name="message" placeholder="Message" required></textarea><br />
        <button type="submit">Submit</button>
    </form>
    
  4. Create processmail.php. You can copy and use the following code snippet directly, just replace with your own email address and your own SendGrid API key. It’s relatively rudimentary but should fulfil the most basic requirements.

    <?php
    require 'vendor/autoload.php';
    
    $yourEmail = 'REPLACE_WITH_YOUR_EMAIL_ADDRESS_HERE';
    $apiKey = 'REPLACE_WITH_YOUR_API_KEY_HERE';
    
    $fromName = $_POST['name'];
    $fromEmail = $_POST['email'];
    $fromMessage = $_POST['message'];
    
    $email = new \SendGrid\Mail\Mail();
    $email ->setFrom($fromEmail, $fromName);
    $email ->setSubject('Message from your website visitor');
    $email ->addto($yourEmail);
    $email ->addContent($fromMessage);
    
    $sendgrid = new \SendGrid($apiKey);
    $sendgrid->send($email);
    
    echo 'Thank you. Your message has been sent.';
    
    ?>
    
  5. That’s it. Visit your contact form page and send a test email.

So simple!

13 March 2019

index