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 inbox
Note: in this example, we are using Gmail as the email provider.
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 and password parameters.
Fill in the following parameters from, to and subject 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.
importplivo,plivoxmlfromflaskimportFlask,requestimportsmtplibapp=Flask(__name__)@app.route("/email_sms/",methods=['GET','POST'])defreceive_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
returnto_email(text,from_number)defto_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)
require'mail'require'sinatra'require'plivo'includePlivopost'/email_sms/'do# The phone number of the person who sent the SMSfrom_number=params[:From]# Your Plivo number that will receive the SMSto_number=params[:To]# The text which was received on your Plivo numbertext=params[:Text]# Print the messageputs"Message received from #{from_number}: #{text}"to_email(text,from_number)enddefto_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.defaultsdodelivery_method:smtp,optionsendMail.deliverdoto'To email address'from'From email address'subject'SMS from #{from_number}'bodytextendend
varplivo=require('plivo');varexpress=require('express');varnodemailer=require("nodemailer");varbodyParser=require('body-parser');varapp=express();app.use(bodyParser.urlencoded({extended:true}));app.set('port',(process.env.PORT||5000));app.all('/email_sms/',function(request,response){// Sender's phone numbervarfrom_number=request.body.From||request.query.From;// Receiver's phone number - Plivo numbervarto_number=request.body.To||request.query.To;// The text which was receivedvartext=request.body.Text||request.query.Text;// Print the messageconsole.log('Message received from: '+from_number+': '+text);varsmtpTransport=nodemailer.createTransport("SMTP",{service:"Gmail",auth:{user:"Your email address",pass:"Your password"}});smtpTransport.sendMail({from:"From email address",// sender addressto:"To email address",// comma separated list of receiverssubject:"SMS from "+from_number,// Subject linetext: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'));});
<?php// Pear Mail Libraryrequire_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 messageecho("Message received from $from_number: $text");to_email($text,$from_number);functionto_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>');}}?>
packagecom.plivo.test;importjava.io.IOException;importjava.util.Properties;importjavax.servlet.ServletException;importjavax.servlet.http.HttpServlet;importjavax.servlet.http.HttpServletRequest;importjavax.servlet.http.HttpServletResponse;importorg.eclipse.jetty.server.Server;importorg.eclipse.jetty.servlet.ServletContextHandler;importorg.eclipse.jetty.servlet.ServletHolder;importjavax.mail.Message;importjavax.mail.MessagingException;importjavax.mail.PasswordAuthentication;importjavax.mail.Session;importjavax.mail.Transport;importjavax.mail.internet.InternetAddress;importjavax.mail.internet.MimeMessage;importcom.plivo.helper.exception.PlivoException;importcom.plivo.helper.xml.elements.PlivoResponse;publicclasssmsToEmailextendsHttpServlet{privatestaticfinallongserialVersionUID=1L;protectedvoiddoPost(HttpServletRequestreq,HttpServletResponseresp)throwsServletException,IOException{Stringfrom_number=req.getParameter("From");// Sender's phone numberStringto_number=req.getParameter("To");// Receiver's phone number - Plivo numberStringtext=req.getParameter("Text");// The text which was received on your Plivo number// Print the messageSystem.out.println("Message received from: "+from_number+": "+text);try{Stringresult=smsToEmail.sendEmail(text,from_number);resp.getWriter().print(result);}catch(Exceptionex){ex.printStackTrace();resp.getWriter().print("Error");}}publicstaticStringsendEmail(Stringtext,Stringfrom_number){]// Recipient's email IDStringto="To email address";// Sender's email IDStringfrom="From email address";finalStringusername="Your email address";finalStringpassword="Your password";Stringhost="smtp.gmail.com";Propertiesprops=newProperties();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 objectSessionsession=Session.getInstance(props,newjavax.mail.Authenticator(){protectedPasswordAuthenticationgetPasswordAuthentication(){returnnewPasswordAuthentication(username,password);}});try{// Create a default MimeMessage object.Messagemessage=newMimeMessage(session);// Set From: header field of the header.message.setFrom(newInternetAddress(from));// Set To: header field of the header.message.setRecipients(Message.RecipientType.TO,InternetAddress.parse(to));// Set Subject: header fieldmessage.setSubject("SMS from "+from_number);// Set the actual messagemessage.setText(text);// Send messageTransport.send(message);System.out.println("Sent message successfully!");return"Sent message successfully!";}catch(MessagingExceptione){thrownewRuntimeException(e);}}publicstaticvoidmain(String[]args)throwsException{Stringport=System.getenv("PORT");if(port==null)port="8080";Serverserver=newServer(Integer.valueOf(port));ServletContextHandlercontext=newServletContextHandler(ServletContextHandler.SESSIONS);context.setContextPath("/");server.setHandler(context);context.addServlet(newServletHolder(newsmsToEmail()),"/email_sms/");server.start();server.join();}}
usingSystem;usingSystem.Collections.Generic;usingSystem.Reflection;usingSystem.Net;usingSystem.Net.Security;usingSystem.Security.Cryptography.X509Certificates;usingNancy;usingRestSharp;usingPlivo.API;usingSystem.Net.Mail;namespaceSend_Email{publicclassProgram:NancyModule{publicProgram(){Post["/email_sms/"]=x=>{Stringfrom_number=Request.Form["From"];// Sender's phone numberStringto_number=Request.Form["To"];// Receiver's phone number - Plivo numberStringtext=Request.Form["Text"];// The text which was received on your Plivo number// Print the messageConsole.WriteLine("Message received from {0}: {1}",from_number,text);// Call the SendEmail functionstringresult=SendEmail(text,from_number);returnresult;};}// Send Email functionprotectedstringSendEmail(stringtext,stringfrom_number){stringresult="Message Sent Successfully!!";stringuser_name="Your email address";// Sender’s email IDconststringpassword="Your password";// password here…stringsubject="SMS from {0}",from_number;// Subject of the mailstringto="To email address";stringbody=text;// Body of the mail which the text that was receivedServicePointManager.ServerCertificateValidationCallback=delegate(objects,X509Certificatecertificate,X509Chainchain,SslPolicyErrorssslPolicyErrors){returntrue;};try{// Initialize the smtp clientSmtpClientsmtp=newSmtpClient{Host="smtp.gmail.com",// smtp server address here…Port=587,EnableSsl=true,DeliveryMethod=SmtpDeliveryMethod.Network,Credentials=newSystem.Net.NetworkCredential(user_name,password),Timeout=30000,};MailMessagemessage=newMailMessage(user_name,to,subject,body);// Send the mailsmtp.Send(message);}catch(Exceptionex){result="Error sending email!!!";}returnresult;}}}
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!