Search code examples
coldfusioncfmllucee

How do you send a txt message to a cell phone from a Lucee web app?


I would like my application to send a text message to users on certain triggers, preferably using something like a cfmail tag. I've never had to send text message from a web app before, but given the huge number of mobile devices out there today I assumed this would be built into CF/Lucee if I ever needed it. However, now that I do I'm not seeing anything in the docs or first few pages of Google.

Is it possible to send text messages directly from Lucee? I know that I could use cfmail to send messages to the carrier's gateway (ie: [email protected]), but that requires me to know and maintain a list of every carrier's address scheme and know which carrier the recipient is with, which I can't. Is what I want to do only possible with a third party service?


Solution

  • Twilio (https://www.twilio.com/try-twilio) makes it easy to send text messages. All you need to do is to make an HTTP POST request.

    When you successfully send a message, Twilio responds with data about the process, including a message SID (System ID).

    Here is some code which you can put in a .cfm page and run it to send a message. Replace the three PLACEHOLDERS with your Twilio values.

    You'll find your Twilio credentials ACCOUNT_SID and AUTH_TOKEN, on your "Dashboard" after you signup/login at Twilio.

    YOUR_TWILIO_PHONE_NUMBER should start with +.


    
    <cffunction name="sendMessageWithTwilio" output="false" access="public" returnType="string">
        <cfargument name="aMessage" type="string" required="true" />
        <cfargument name="destinationNumber" type="string" required="true" />
    
        <cfset var twilioAccountSid = "YOUR_ACCOUNT_SID" />
        <cfset var twilioAuthToken = "YOUR_AUTH_TOKEN" />
        <cfset var twilioPhoneNumber = "YOUR_TWILIO_PHONE_NUMBER" />
    
        <cfhttp 
            result="result" 
            method="POST" 
            charset="utf-8" 
            url="https://api.twilio.com/2010-04-01/Accounts/#twilioAccountSid#/Messages.json"
            username="#twilioAccountSid#"
            password="#twilioAuthToken#" >
    
            <cfhttpparam name="From" type="formfield" value="#twilioPhoneNumber#" />
            <cfhttpparam name="Body" type="formfield" value="#arguments.aMessage#" />
            <cfhttpparam name="To" type="formfield" value="#arguments.destinationNumber#" />
    
        </cfhttp>
    
        <cfif result.Statuscode IS "201 CREATED">
            <cfreturn deserializeJSON(result.Filecontent.toString()).sid />
        <cfelse>
            <cfreturn result.Statuscode />
        </cfif>
    
    </cffunction>
    
    <cfdump var='#sendMessageWithTwilio(
        "This is a test message.",
        "+17775553333"
    )#' />