SMS Notifications with Perl and Twilio
Tags: perl, sms, twilio, beginners
Published: 2018-06-14 06:11:39

---
title: SMS Notifications with Perl and Twilio
published: true
description: Who needs E-Mail for password resets when you have SMS?
tags: #perl #sms #twilio #beginners
cover_image: https://thepracticaldev.s3.amazonaws.com/i/1r64c4pb0rxo2vuohef6.jpg
---
[Twilio](https://twilio.com) is beyond useful, and easy to integrate.  It's one of those tools that, once you get started, you just can't stop using it.  You can add SMS Notifications and password resets to your existing application in an afternoon.

I see several examples of Twilio usage on dev.to.  But of course, none for Perl, until now.

## First, the entire simple program:
``` perl
#!/usr/bin/env perl
use v5.10;
use strict;
use warnings;
use LWP::UserAgent;

my %text_message = (
    From => '12513001300', # Me
    To   => '16198675309', # Jenny
    Body => 'Thank you for being a friend! Travel down the road and back again!'
);

my %credentials = (
    account_id => '____YOUR_ACCOUNT_SID_GOES_HERE____',
    auth_token => '____YOUR_AUTH_TOKEN_GOES_HERE____',
);

my %twilio = (
    # HTTP Authentication
    api_domain => 'api.twilio.com:443',
    api_realm  => 'Twilio API',

    # Keep your line length within 80 characters please!
    api_url    => 'https://api.twilio.com/2010-04-01/Accounts/'
                  . $credentials{account_id}
                  . '/Messages'
);

my $ua = LWP::UserAgent->new;
$ua->credentials(
    $twilio{api_domain},
    $twilio{api_realm},
    $credentials{account_id},
    $credentials{auth_token}
);

my $response = $ua->post( $twilio{api_url}, \%text_message );

say $response->is_success
    ? "Message delivered"
    : "Error: ".$response->decoded_content;

```

## As this is a #beginner post, let's break this down statement by statement.

``` perl
#!/usr/bin/env perl
use v5.10;
use strict;
use warnings;
```
Begin with a [Shebang Line](https://en.wikipedia.org/wiki/Shebang_\(Unix\)).  If you execute this program from a shell, this is how the shell knows which interpreter to use for the program.  `#!/usr/bin/env perl` has replaced the long in the tooth standard `#!/usr/bin/perl` with good reason.

Invoking `use v5.10;` here allows us to use the [say](https://perldoc.perl.org/functions/say.html) function.

`use strict` and `use warnings` asks Perl to warn you if you're doing something stupid.  Like misspelling a variable name, or blogging at 2am.


``` perl
use LWP::UserAgent;
```
[LWP::UserAgent](https://metacpan.org/pod/LWP::UserAgent) can perform most actions your web browser does.  You can use it to browse pages, click links, and POST forms.  It can keep persistent cookies.  If you wanted to, say, write a robot to cheat an online poll, look no further.

``` perl
my %text_message = (
    From => '12513001300', # Me
    To   => '16198675309', # Jenny
    Body => 'Thank you for being a friend! Travel down the road and back again!'
);
```
Store information about your text message into a hash. You'll want to replace the example data with your own.  Jenny's had enough phone harassment.

``` perl
my %credentials = (
    account_id => '____YOUR_ACCOUNT_SID_GOES_HERE____',
    auth_token => '____YOUR_AUTH_TOKEN_GOES_HERE____',
);
```
You can find your Twilio account credentials in the Dashboard under Settings/General.  Twilio offers test API access.  You can use the test API to text yourself.

``` perl
my %twilio = (
    # HTTP Authentication
    api_domain => 'api.twilio.com:443',
    api_realm  => 'Twilio API',

    # Keep your line length within 80 characters please!
    api_url    => 'https://api.twilio.com/2010-04-01/Accounts/'
                  . $credentials{account_id}
                  . '/Messages'
);
```
Information you need to send a request to the Twilio API.  Twilio uses [Basic HTTP Authentication](https://en.wikipedia.org/wiki/Basic_access_authentication).   Here is the DOMAIN and REALM for this authentication scheme.  The Twilio API URL contains your account SID, so the full API URL is concatenated here.

``` perl
my $ua = LWP::UserAgent->new;
$ua->credentials(
    $twilio{api_domain},
    $twilio{api_realm},
    $credentials{account_id},
    $credentials{auth_token}
);
```
Instantiate a new instance of the LWP::UserAgent object, and set the credentials it will use for the HTTP Request to the Twilio API.

``` perl
my $response = $ua->post( $twilio{api_url}, \%text_message );
```
$ua makes a HTTP POST request to $twilio{api_url}.  The data from %text_message are sent as form values.  This operation returns a [HTTP::Response](https://metacpan.org/pod/HTTP\:\:Response) Object.

``` perl
say $response->is_success
    ? "Message delivered"
    : "Error: ".$response->decoded_content;

```
This statement includes the [ternary operator](https://perldoc.perl.org/perlop.html), a short-hand for an if-else block.  (Side note:  If you didn't know what a ternary operator was, or what it was called, and you saw this statement block in some code, how would you phrase your internet search to learn what this statement was doing?  Let me know in the comments...)

`$response->is_success` returns true or false based on the [HTTP Status Code](https://en.wikipedia.org/wiki/List_of_HTTP_status_codes) returned by the web server.

If Twilio reports the request was successful, you see **Message Delivered** displayed in your terminal.  If Twilio reports a problem, you will see the full response from the Twilio API displayed in your terminal.

## See how easy Twilio is?  Go build something...
Frankly, Twilio has made themselves so easy to use that most languages can break their use down to one-liners.  You can easily deliver an SMS via the shell using curl.

If you ever meet a Twilio engineer, be sure to buy them a beer.

Are you still reading?  Go build something!