Forwarding SMS Messages to Email Using .Net

    Overview

    Businesses get communications through many channels. It can be handy to have a searchable archive of messages in one place. Forwarding SMS messages to email lets you keep both kinds of messages in one spot. Plivo makes it easy to forward SMS messages to email using the most popular web development languages. Here we walk through the process with .NET.

    Prerequisites

    • Plivo account: Sign up for a Plivo account if you don’t have one already.

    • Plivo phone number: To receive SMS, you must have a Plivo phone number that supports SMS. You can purchase numbers from the Numbers page of the Plivo console or by using the Numbers API.

      Buy a New Plivo Number

    The code example below presumes you have a Gmail account, but it’s easy to edit the code to support another SMTP client.

    Install .NET Core

    You can set up and install .NET Core 1.0 or higher to forward SMS messages to email without using any third-party libraries.

    Installation

    Operating SystemInstructions
    macOS and LinuxSee whether you already have .NET Core installed by running the command dotnet --version in the terminal. If you don’t, download it from Microsoft.
    WindowsTo install .NET Core on Windows, download it from Microsoft.

    Create a project

    • Create a project directory by running the command

      $ mkdir mydotnetcoreapp
      
    • Change to the project directory

      $ cd mydotnetcoreapp
      
    • Create a project template by running the command

      $ dotnet new console
      

    Forward SMS to Email

    Below is the code to Forward Incoming SMS to Email.

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    
    using System;
    using Microsoft.AspNetCore.Mvc;
    using System.Collections.Generic;
    using System.Reflection;
    using System.Net;
    using System.Net.Security;
    using System.Security.Cryptography.X509Certificates;
    using System.Net.Mail;
    namespace EmailSms.Controllers
    {
        public class EmailSmsController : Controller
        {
            // GET: /<controller>/
            public String Index()
            {
                String from_number = Request.Form["From"];
                String to_number = Request.Form["To"];
                String text = Request.Form["Text"];
                Console.WriteLine("Message received - From: {0}, To: {1}, Text: {2}", from_number, to_number, text);
                string user_name = "<email_address>";// Sender's email ID
                const string password = "<password>"; //  password here…
                string subject = "SMS from " + from_number; // Subject of the mail
                string to = "<recepient_address>";
                string body = text; // Body of the mail which the text that was received
                ServicePointManager.ServerCertificateValidationCallback =
                    delegate(object s, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors)
                {  return true; };
                try {
                    // Initialize the smtp client
                    SmtpClient smtp = new SmtpClient
                    {
                        Host = "smtp.gmail.com", // smtp server address here…
                        Port = 587,
                        EnableSsl = true,
                        DeliveryMethod = SmtpDeliveryMethod.Network,
                        Credentials = new System.Net.NetworkCredential(user_name, password),
                        Timeout = 30000,
                    };
                   MailMessage message = new MailMessage(user_name, to, subject, body);
                   // Send the mail
                   smtp.Send(message);
                } catch (Exception ex) {
                  Console.WriteLine("Error sending email!!!", ex);
                }
                return "Success";
            }
        }
    }
    
    Note: If you use Gmail to send email, you'll have to use an app password, which will be treated as your password to send email from the app.

    Expose your local server to the internet

    To receive Incoming Messages and to handle callbacks, your local server should be able to connect with Plivo API service, Ngrok is a tunneling software used to expose a web server running on your local machine to the internet. Using Ngrok you can set webhooks which can talk to Plivo server.

    ngrok block diagram

    Install ngrok and run it on the command line, specifying the port that hosts the application on which you want to receive messages (5000 in this case):

    $ ./ngrok http 5000
    

    Ngrok will display a forwarding link that you can use as a webhook to access your local server over the public network.

    Sample ngrok CLI

    Create an Application

    1. Create a Plivo application by visiting Messaging > Applications and clicking on Add New Application, or by using Plivo’s Application API.
    2. Give your application a name — we called our Email SMS. Enter your server URL (for example https://61d8fb8f250c.ngrok.io/email_sms/) in the Message URL field and set the method as POST.
    3. Click on 'Create Application' to save your application.

    Create Application

    Assign a Plivo number to your app

    1. Navigate to the Numbers page and select the phone number you want to use for the application.
    2. Select XML Application from the Application Type drop-down list, and Email SMS (the name of the application) from the Plivo Application drop-down list.
    3. Click on 'Update Number' to save.

    Assign Application

    Test and validate

    To test the application, enter the following command

    $ dotnet run
    

    Then send a text message to the Plivo number you associated with the application using a regular mobile phone.The incoming message should be reflected in your email.