Setup Mailgun Over cURLMailgun as of late has made me decide to move on from using Contact Form 7 as my default for building contact forms. While CF7 is simple and easy to use it still uses SendMail or PostFix on the server to deliver email, and as a result most email ends up in the spam queue. This became a problem recently for Startup and Play, so I decided I would go ahead and swap out all my forms to use a proper email delivery company – bonus points for one who offers the first 10,000 emails free and is built for developers.

This is a quick tutorial on setting up a form, ajax, and a php curl request to Mailgun to deliver the email. I assuming that you have already setup a Mailgun accout and you have modified your DNS settings. Since I am also trying to keep this short in simple I am not providing any error handing/messaging, just the nuts and bolts to get this delivering emails over a cURL.

The basic form:

I would suggest adding in some spam mechanisms like a display:none hidden input that should have an empty value, also some protection for CSFR, and if using WordPress including utilizing the nonce functionality incorporated into core.

Next we will prepare a simple AJAX call to our PHP script that performs the curl. This script is expecting the php file to be in a folder called ‘ajax’ in the root. Once the submit button is hit, it fades out the form, announces the processing, completes the ajax request and outputs a result into the form.

Finally we need to build out PHP script to initiate the curl with MailGun. A brief walk through of this form is that it is 3 pieces, the first being the actual procedural PHP code. It checks to see if the POST is empty, if it is trigger the error function ‘ajaxResponse’, if not continue on. It implodes the POST array into a string for easier inclusion in the ajaxResponse (if needed). Then it calls the Mailgun function, placing the result once again into the ajaxResponse function.

That’s it. We’ve done it. A simple Mailgun form using a PHP cURL. Remember the three pieces in the PHP script that have to be set are the API key, domain and email address Mailgun is supposed to be sending to.