Using a Remote JSONP ColdFusion Service to Send Mail

A user had an interesting question regarding jQuery and JSONP. He wanted to know if a file on one server (a server without ColdFusion) could use jQuery and JSONP to run CFML code on another server and send email. The problem with using JSONP in this scenario is that JSONP is a GET request. Emails are - typically - a bit long and could fail to execute if the message was too large. He still wanted to see an example anyway so I whipped up the following demo. The code is based on the blog entry I wrote two months ago on JSONP services in ColdFusion.

The front end is incredibly simple. One text area and a button:

<form id="theform"> <textarea name="msg" id="msg"></textarea> <input type="submit"> </form>

I then whipped up some quick jQuery code to process the form:

<script> $(document).ready(function() {

$("#theform").submit(function() {
	var message = $("#msg").val()
	$.getJSON('', {message:message}, function(d,t) {
		$("#result").html('Mail Sent')
	return false
}) }) &lt;/script&gt; </code>

I begin by grabbing the textarea value. Then I run the JSONP request. A JSONP request is no different than a normal JSON request, but you have to include the ? parameter at the end of the URL. This tips off jQuery that we are doing a JSONP request instead of a simple HTTP request to an item on the same server.

The CFC is a bit simpler than the one I wrote for my previous blog entry. Instead of writing two methods to nicely abstract the service, I just wrote a method to send the mail and return the properly formatted result:

<cffunction name="sendmail" access="remote" returntype="any" output="false" returnformat="plain"> <cfargument name="message" type="string" required="true"> <cfargument name="callback" type="string" required="true"> <cfset var data = "">

&lt;cflog file="application" text="Going to send this in email: #arguments.message#"&gt;

&lt;cfset data = serializeJSON(true)&gt;
&lt;!--- wrap ---&gt;
&lt;cfset data = arguments.callback & "(" & data & ")"&gt;
&lt;cfreturn data&gt; &lt;/cffunction&gt; </code>

The cflog line is standing in for my cfmail command. I don’t really care about the result so I just return true. Note the use of the callback wrapper which fits into the JSONP requirements.

Once setup, you could put the HTML on any server and then use the form to send your text to the remote CFC.

Is this a good idea? Probably not. Again, you have to worry about the GET size limits, but you could probably add a size limit to the textarea easily enough.

Raymond Camden's Picture

About Raymond Camden

Raymond is a developer advocate for Extend by Auth0. He focuses on serverless and enterprise cat demos. If you like this article, please consider visiting my Amazon Wishlist or donating via PayPal to show your support.

Lafayette, LA