Forward SMS to Email
This app will allow you to forward SMS text messages (sent to your Plivo number) as emails to your email address. The functionality can be broken down into these steps:
- Your friend sends you an SMS to your Plivo Number.
- The SMS gets forwarded to your email inboxNote: in this example, we are using Gmail as the email provider.
Prerequisites
- Sign up for a free Plivo trial account.
- Check out our server SDKs page and install the right helper based on the programming language you want to use.
- Buy a Plivo phone number (optional).Note: A phone number is required only for sending SMS to US and Canadian phone numbers. However, country-specific carrier conditions may still apply. You can buy a US or Canadian phone number through the Buy Numbers tab on your Plivo account UI.
- Use a web hosting service to host your web application. There are many inexpensive cloud hosting providers that you can use for just a few dollars a month. Follow the instructions of your hosting provider to host your web application.Note: If you are using a Plivo Trial account for this example, you can only send sms to phone numbers that have been verified with Plivo. Phone numbers can be verified at the Sandbox Numbers page.
Set up a Web Server
Let’s assume your web server is located at http://example.com
. Below is a snippet to set up a route on your webserver. Let’s call it, email_sms
. Now when we send an HTTP
request to http://example.com/email_sms/
this route will be invoked. This route will call the to_email()
function, which will send the email.
Note: For PHP, the route will be example.com/email_sms.php.
- Copy the relevant code below into a text file and save it. Let’s call it,
email_sms
. - Insert your email account detials in to
user_name
andpassword
parameters. - Fill in the following parameters
from
,to
andsubject
with the sender’s email address, receiver’s email address and the email subject line respectively. - The
body
of the email is the SMS that was received on your Plivo number. - Next, you will configure this web server URL in your Plivo application.Note: Depending on your email provider, you may need to configure your security settings. For example, if you are using Gmail, you may need to turn on access for "less secure apps" in your Google apps settings.
Code
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
import plivo, plivoxml
from flask import Flask, request
import smtplib
app = Flask(__name__)
@app.route("/email_sms/", methods =['GET','POST'])
def receive_sms():
# Sender's phone number
from_number = request.values.get('From')
# Receiver's phone number - Plivo number
to_number = request.values.get('To')
# The text which was received on your Plivo number
text = request.values.get('Text')
# Print the message
print 'Message received from %s: %s' % (from_number, text)
# Send the received SMS to your mail account
return to_email(text, from_number)
def to_email(text, from_number):
user_name = 'Your email address'
password = 'Your password'
from_ = 'From email address'
to = ['To email address'] # must be a list
subject = "SMS from %s" % (from_number)
body = text
# Prepare actual message
message = """\From: %s\nTo: %s\nSubject: %s\n\n%s
""" % (from_, ", ".join(from_), subject, body)
try:
server = smtplib.SMTP("smtp.gmail.com", 587)
server.ehlo()
server.starttls()
server.login(user_name, password)
server.sendmail(from_, to, message)
server.close()
print 'successfully sent the email'
except:
print "failed to send email"
return "SMS sent to email"
if __name__ == '__main__':
app.run(host='0.0.0.0', debug=True)
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
require 'mail'
require 'sinatra'
require 'plivo'
include Plivo
post '/email_sms/' do
# The phone number of the person who sent the SMS
from_number = params[:From]
# Your Plivo number that will receive the SMS
to_number = params[:To]
# The text which was received on your Plivo number
text = params[:Text]
# Print the message
puts "Message received from #{from_number}: #{text}"
to_email(text, from_number)
end
def to_email(text, from_number)
options = {
:address => "smtp.gmail.com",
:port => 587,
:user_name => 'Your email address',
:password => 'Your password',
:authentication => 'plain',
:enable_starttls_auto => true
}
Mail.defaults do
delivery_method :smtp, options
end
Mail.deliver do
to 'To email address'
from 'From email address'
subject 'SMS from #{from_number}'
body text
end
end
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
var plivo = require('plivo');
var express = require('express');
var nodemailer = require("nodemailer");
var bodyParser = require('body-parser');
var app = express();
app.use(bodyParser.urlencoded({extended: true}));
app.set('port', (process.env.PORT || 5000));
app.all('/email_sms/', function(request, response) {
// Sender's phone number
var from_number = request.body.From || request.query.From;
// Receiver's phone number - Plivo number
var to_number = request.body.To || request.query.To;
// The text which was received
var text = request.body.Text || request.query.Text;
// Print the message
console.log('Message received from: ' + from_number + ': ' + text);
var smtpTransport = nodemailer.createTransport("SMTP", {
service: "Gmail",
auth: {
user: "Your email address",
pass: "Your password"
}
});
smtpTransport.sendMail({
from: "From email address", // sender address
to: "To email address", // comma separated list of receivers
subject: "SMS from " + from_number, // Subject line
text: text // plaintext body
}, function(error, response){
if (error) {
console.log(error);
} else {
console.log("Message sent: " + response.message);
}
});
});
app.listen(app.get('port'), function() {
console.log('Node app is running on port', app.get('port'));
});
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
<?php
// Pear Mail Library
require_once "Mail.php";
// Sender's phone numer
$from_number = $_REQUEST["From"];
// Receiver's phone number - Plivo number
$to_number = $_REQUEST["To"];
// The text which was received on your Plivo number
$text = $_REQUEST["Text"];
// Print the message
echo("Message received from $from_number: $text");
to_email($text, $from_number);
function to_email($text, $from_number){
$from = 'From email address';
$to = 'To email address';
$subject = 'SMS from $from_number';
$body = $text;
$headers = array(
'From' => $from,
'To' => $to,
'Subject' => $subject
);
$smtp = Mail::factory('smtp', array(
'host' => 'ssl://smtp.gmail.com',
'port' => '465',
'auth' => true,
'username' => 'Your email address',
'password' => 'Your password'
));
// Send mail
$mail = $smtp->send($to, $headers, $body);
if (PEAR::isError($mail)) {
echo('<p>' . $mail->getMessage() . '</p>');
} else {
echo('<p>Message successfully sent!</p>');
}
}
?>
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
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
package com.plivo.test;
import java.io.IOException;
import java.util.Properties;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.eclipse.jetty.server.Server;
import org.eclipse.jetty.servlet.ServletContextHandler;
import org.eclipse.jetty.servlet.ServletHolder;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import com.plivo.helper.exception.PlivoException;
import com.plivo.helper.xml.elements.PlivoResponse;
public class smsToEmail extends HttpServlet{
private static final long serialVersionUID = 1L;
protected void doPost(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
String from_number = req.getParameter("From"); // Sender's phone number
String to_number = req.getParameter("To"); // Receiver's phone number - Plivo number
String text = req.getParameter("Text"); // The text which was received on your Plivo number
// Print the message
System.out.println("Message received from: " + from_number + ": " + text);
try {
String result = smsToEmail.sendEmail(text, from_number);
resp.getWriter().print(result);
} catch (Exception ex) {
ex.printStackTrace();
resp.getWriter().print("Error");
}
}
public static String sendEmail(String text, String from_number){]
// Recipient's email ID
String to = "To email address";
// Sender's email ID
String from = "From email address";
final String username = "Your email address";
final String password = "Your password";
String host = "smtp.gmail.com";
Properties props = new Properties();
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.starttls.enable", "true");
props.put("mail.smtp.host", host);
props.put("mail.smtp.port", "587");
// Get the Session object
Session session = Session.getInstance(props,
new javax.mail.Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(username, password);
}
});
try {
// Create a default MimeMessage object.
Message message = new MimeMessage(session);
// Set From: header field of the header.
message.setFrom(new InternetAddress(from));
// Set To: header field of the header.
message.setRecipients(Message.RecipientType.TO,InternetAddress.parse(to));
// Set Subject: header field
message.setSubject("SMS from " + from_number);
// Set the actual message
message.setText(text);
// Send message
Transport.send(message);
System.out.println("Sent message successfully!");
return "Sent message successfully!";
} catch (MessagingException e) {
throw new RuntimeException(e);
}
}
public static void main(String[] args) throws Exception {
String port = System.getenv("PORT");
if (port==null) port ="8080";
Server server = new Server(Integer.valueOf(port));
ServletContextHandler context = new ServletContextHandler(ServletContextHandler.SESSIONS);
context.setContextPath("/");
server.setHandler(context);
context.addServlet(new ServletHolder(new smsToEmail()),"/email_sms/");
server.start();
server.join();
}
}
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
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
using System;
using System.Collections.Generic;
using System.Reflection;
using System.Net;
using System.Net.Security;
using System.Security.Cryptography.X509Certificates;
using Nancy;
using RestSharp;
using Plivo.API;
using System.Net.Mail;
namespace Send_Email
{
public class Program : NancyModule
{
public Program()
{
Post["/email_sms/"] = x =>
{
String from_number = Request.Form["From"]; // Sender's phone number
String to_number = Request.Form["To"]; // Receiver's phone number - Plivo number
String text = Request.Form["Text"]; // The text which was received on your Plivo number
// Print the message
Console.WriteLine("Message received from {0}: {1}", from_number, text);
// Call the SendEmail function
string result = SendEmail(text, from_number);
return result;
};
}
// Send Email function
protected string SendEmail(string text, string from_number)
{
string result = "Message Sent Successfully!!";
string user_name = "Your email address";// Sender’s email ID
const string password = "Your password"; // password here…
string subject = "SMS from {0}", from_number; // Subject of the mail
string to = "To email 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) {
result = "Error sending email!!!";
}
return result;
}
}
}
Create an Application
- Create an Application by visiting the Application Page and click on
'New Application'
or by using Plivo’s Application API. - Give your application a name. Let’s call it
'Email SMS'
. Enter your server URL (e.g.http://example.com/email_sms/
) in the'Message URL'
field and set the method as'POST'
. See our Application API docs to learn how to modify your application through our APIs. - Click on
'Create'
to save your application.
Assign a Plivo number to your app
- Navigate to the Numbers page and select the phone number you want to use for this app.
- Select
'Email SMS'
(name of the app) from the Plivo App dropdown list. - Click on
'Update'
to save.
If you don’t have a number, go to the Buy Number page to purchase a Plivo phone number.
Test and validate
Send an SMS to your Plivo number using a regular mobile phone. Plivo will request the your Message URL
which will forward the sms to your gmail account.
Rate this page
🥳 Thank you! It means a lot to us!
×
Help Us Improve
Thank you so much for rating the page, we would like to get your input for further improvements!
Subscribe to Updates
Thank you for your feedback!