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.
- Sign up for a free SendGrid account
- 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
- 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 />
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.
$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');
$sendgrid = new \SendGrid($apiKey);
echo 'Thank you. Your message has been sent.';
- That’s it. Visit your contact form page and send a test email.