Skip to content

Instantly share code, notes, and snippets.

@emersonbroga
Last active August 29, 2017 16:28
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save emersonbroga/62eac05b2cf67e1752ebbe331b7b194d to your computer and use it in GitHub Desktop.
Save emersonbroga/62eac05b2cf67e1752ebbe331b7b194d to your computer and use it in GitHub Desktop.
Wordpress + Mailgun

Wordpress + Mailgun

This is a simple snippet to create a wordpress contact form that sends email using mailgun api.

Installation

. Install the mailgun plugin for wordrpess https://wordpress.org/plugins/mailgun/

. Add the config constants to your wp-config.php

. In the worpess admin, create a page and a template for that page, see page-contact.php (https://codex.wordpress.org/Template_Hierarchy)

. Add the functions to send the email csrf, json_result, contact_email.

That's pretty much it.

Improvements to be made:

  • return actual http status: The way it is right now, all messages will return http status 200, although the json status field will be 500 when errors occur.

  • return correct http status: The way it is right now, the error messages are all 500 instad of the correct ones.

  • handle the ajax error the way it is right now, it is not handling the ajax errors.

<?php
// ...
function csrf()
{
if (!isset($_SESSION['token'])) {
$token = md5(uniqid(rand(), TRUE));
$_SESSION['token'] = $token;
} else {
$token = $_SESSION['token'];
}
return $token;
}
function json_result($message, $status = 200)
{
$result = array('status' => $status, 'message' => $message);
return json_encode($result);
}
function contact_email()
{
if(!class_exists('Mailgun')) {
echo json_result('Install mailgun plugin.', 500);
die;
}
$token = (isset($_POST['_token'])) ? $_POST['_token'] : null;
$name = (isset($_POST['name'])) ? $_POST['name'] : null;
$email = (isset($_POST['email'])) ? $_POST['email'] : null;
$message = (isset($_POST['message'])) ? $_POST['message'] : null;
$validToken = ($token !== null && isset($_SESSION['token']) && $_SESSION['token'] === $token);
if (!$validToken) {
echo json_result('Reload the page, invalid token.', 500);
die;
}
if (empty($name) || empty($email) || empty($message)) {
echo json_result('Please fill all the fields.', 500);
die;
}
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
echo json_result('Invalid email address.', 500);
die;
}
$mailgun = new Mailgun();
$uri = MAILGUN_DOMAIN . '/messages';
// email html
$text = sprintf('<p><strong>Name</strong>:%s (%s)</p><p>%s</p>', $name, $email, $message);
$params = array(
'from' => sprintf('%s <%s>', $name, $email),
'to' => CONTACT_MAIL,
'subject' => 'Contact',
'html' => $text,
);
unset($_SESSION['token']);
$result = $mailgun->api_call($uri, $params);
echo json_result('Email sent successfully.', 200);
die;
}
add_action('wp_ajax_contactEmail', 'contact_email');
add_action('wp_ajax_nopriv_contactEmail', 'contact_email');
// ...
<?php
/**
* The template for displaying the contact page.
*
* @link https://codex.wordpress.org/Template_Hierarchy
*
*/
while ( have_posts() ) : the_post(); ?>
<div>
<article id="post-<?php the_ID(); ?>" <?php post_class(); ?>>
<h1><?php the_title( '<h1 class="entry-title">', '</h1>' ); ?></h1>
<div class="entry-content">
<?php the_content(); ?>
</div>
<div class="entry-content">
<div id="alert" role="alert"></div>
<form class="contact-form" action="/wp-admin/admin-ajax.php" method="post">
<input type="hidden" name="action" value="contactEmail" />
<input type="hidden" name="_token" value="<?php echo csrf() ?>" />
<div class="form-group">
<label for="name">Name</label>
<input type="text" class="form-control" id="name" name="name" placeholder="Name">
</div>
<div class="form-group">
<label for="email">Email</label>
<input type="text" class="form-control" id="email" name="email" placeholder="Email">
</div>
<div class="form-group">
<label for="message">Message</label>
<textarea class="form-control" name="message" placeholder="Message"> </textarea>
</div>
<div class="form-group">
<div class="g-recaptcha" data-sitekey="xyz"></div>
</div>
<div class="form-group">
<button type="submit" class="btn btn-default">Send</button>
</div>
</form>
</div><!-- .entry-content -->
</article><!-- #post-## -->
</div>
<?php endwhile; // End of the loop. ?>
<script src='https://www.google.com/recaptcha/api.js'></script>
<script type="text/javascript">
$(document).ready(function() {
$('.contact-form').submit(function(e) {
e.preventDefault();
var data = $('.contact-form').serialize();
var $alert = $('#alert');
var captchResponse = $('#g-recaptcha-response').val();
if (captchResponse.length == 0 ){
$alert.text('Please fill all the fields').removeClass().addClass('alert alert-danger');
return;
}
$.ajax({
type: 'POST',
url: '/wp-admin/admin-ajax.php',
data: data,
success: function( data ) {
var response = jQuery.parseJSON(data);
if (response.status != 200) {
$alert.text(response.message).removeClass().addClass('alert alert-danger');
return;
}
$alert.text(response.message).removeClass().addClass('alert alert-success');
}
});
return false;
});
});
</script>
<?php
// ...
// mailgun plugin configuration.
define( 'MAILGUN_USEAPI', true);
define( 'MAILGUN_APIKEY', 'xyz');
define( 'MAILGUN_DOMAIN', 'your-domain.com');
define( 'MAILGUN_USERNAME', 'postmaster@your-domain.com');
define( 'MAILGUN_PASSWORD', '123456');
define( 'MAILGUN_SECURE', true);
define( 'MAILGUN_FROM_NAME', 'YOUR SITE NAME');
define( 'MAILGUN_FROM_ADDRESS', 'postmaster@your-domain.com');
define( 'CONTACT_MAIL', 'destination@email.com');
//...
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment