Sending email with Mandrill API
Mandrill provides a reliable, secure delivery API for
transactional emails from websites and applications. It's easy for developers to
integrate sending emails with its API
which are available in various programming languages.
The following piece of code uses an Ajax request to
send the needed information to Mandrill API :
< form id = "contactForm" method = "post" class = "form-horizontal" >
<!-- This container will be shown after sending new message -->
< div id = "alertContainer" class = "alert" style = "display: none;" ></ div >
<!-- Form fields -->
...
</ form >
$ ( '#contactForm' )
. formValidation ({
...
})
. on ( 'success.form.fv' , function ( e ) {
// Prevent default form submission
e . preventDefault ();
// Change these values to match with your application
var MANDRILL_API_KEY = 'YOUR-MANDRILL-API-KEY' ,
EMAIL_SUBJECT = 'Contact form' ,
RECEIVER_EMAIL = 'hello@formvalidation.io' ;
var $form = $ ( e . target ),
// Generate a message based on submitted form data
body = [
'<strong>Name:</strong> ' + $form . find ( '[name="firstName"]' ). val () + ' ' + $form . find ( '[name="lastName"]' ). val (),
'<strong>Phone number:</strong> ' + ( $form . find ( '[name="phoneNumber"]' ). val () || 'n/a' ),
'' ,
'<strong>Message:</strong> ' ,
$form . find ( '[name="message"]' ). val ()
]. join ( '<br/>' );
// Send the message
$ . ajax ({
type : 'POST' ,
url : 'http://mandrillapp.com/api/1.0/messages/send.json' ,
contentType : 'text/plain' ,
dataType : 'json' ,
data : {
key : MANDRILL_API_KEY ,
message : {
from_name : $form . find ( '[name="fullName"]' ). val (),
from_email : $form . find ( '[name="email"]' ). val (),
to : [
{
email : RECEIVER_EMAIL ,
'type' : 'to'
}
],
auto_text : true ,
subject : EMAIL_SUBJECT ,
html : body
}
}
}). done ( function ( response ) {
// Clear the form
$form . formValidation ( 'resetForm' , true );
// Regenerate the captcha
generateCaptcha ();
// Show the message
response . status === 'error'
? $ ( '#alertContainer' )
. removeClass ( 'alert-success' )
. addClass ( 'alert-warning' )
. html ( 'Sorry, cannot send the message' )
. show ()
: $ ( '#alertContainer' )
. removeClass ( 'alert-warning' )
. addClass ( 'alert-success' )
. html ( 'Your message has been successfully sent' )
. show ();
}). fail ( function ( jqXHR , textStatus , errorThrown ) {
$ ( '#alertContainer' )
. removeClass ( 'alert-success' )
. addClass ( 'alert-warning' )
. html ( 'Sorry, cannot send the message' )
. show ();
});
Due to the cross domain issue, the Ajax request
above doesn't work on the Internet Explorer (IE) browser version 8, 9. In order to
support these IE versions, you should take a look at the
jQuery-ajaxTransport-XDomainRequest
script.
Although the code above doesn't require to touch your server side, the visitors can view
the source and use your API key. To avoid that, you can send the form data to your
back-end first:
$ ( '#contactForm' )
. formValidation ({
...
})
. on ( 'success.form.fv' , function ( e ) {
// Prevent default form submission
e . preventDefault ();
var $form = $ ( e . target );
// Send all form data to back-end
$ . ajax ({
url : '/path/to/your/send-mail.php' ,
type : 'POST' ,
data : $form . serialize (),
dataType : 'json' ,
success : function ( response ) {
// Clear the form
$form . formValidation ( 'resetForm' , true );
// Regenerate the captcha
generateCaptcha ();
// Show the message
response . result === 'error'
? $ ( '#alertContainer' )
. removeClass ( 'alert-success' )
. addClass ( 'alert-warning' )
. html ( 'Sorry, cannot send the message' )
. show ()
: $ ( '#alertContainer' )
. removeClass ( 'alert-warning' )
. addClass ( 'alert-success' )
. html ( 'Your message has been successfully sent' )
. show ();
}
});
});
And then the back-end sends the email using Mandrill API . The following code shows
how to do it with PHP:
<?php
// send-mail.php
// Download Mandrill PHP library from
// https://bitbucket.org/mailchimp/mandrill-api-php/get/master.zip
require_once '/path/to/Mandrill.php' ;
try {
// See https://mandrillapp.com/api/docs/index.php.html
$mandrill = new Mandrill ( 'YOUR-MANDRILL-API-KEY' );
// Build the message body
$body = array (
'<strong>Name:</strong> ' + $_POST [ 'firstName' ] + ' ' + $_POST [ 'lastName' ],
'<strong>Phone number:</strong> ' + isset ( $_POST [ 'phoneNumber' ]) ? $_POST [ 'phoneNumber' ] : 'n/a' ,
'<strong>Message:</strong> ' ,
$_POST [ 'message' ],
);
$body = implode ( '<br/>' , $body );
$message = array (
'html' => $body ,
'subject' => 'Contact form' ,
'from_email' => $_POST [ 'email' ],
'from_name' => $_POST [ 'firstName' ] + ' ' + $_POST [ 'lastName' ],
'to' => array (
array (
'email' => 'change-to-your-email-address@domain.com' ,
'name' => 'Change to your name' ,
'type' => 'to'
)
),
'headers' => array (
'Reply-To' => 'message.reply@example.com'
),
);
$async = false ;
$result = $mandrill -> messages -> send ( $message , $async );
echo json_encode ( array (
'result' => 'ok' ,
));
} catch ( Mandrill_Error $e ) {
echo json_encode ( array (
'result' => 'error' ,
));
}