Sending Images over SMS

Last updated: 2022-08-22Contributors
Edit this page

One can send images and other files via SMS as well. Doing so requires developers to POST to the sms endpoint using multipart form-data, or attachments. In the following example we will transmit an image called test.jpg along with the text message, "hello world."

Creating Attachments

When assembling a multipart message, it is important to remember that the root part, or first part of the request is always the request body or payload. Subsequently you attach images and files to the request. You can see how this is done via the code samples below.

Attachment Limitations

  • There is a combined limit of 1.5M bytes for all attachments.
  • There is a limit of 10 attachments for any request.
/* You get the environment parameters from your 
   application dashbord in your developer account 
   https://developers.ringcentral.com */

const RC = require('@ringcentral/sdk').SDK
require('dotenv').config();

const RECIPIENT    = process.env.SMS_RECIPIENT

var rcsdk = new RC({
    'server':       process.env.RC_SERVER_URL,
    'clientId':     process.env.RC_CLIENT_ID,
    'clientSecret': process.env.RC_CLIENT_SECRET
});

var platform = rcsdk.platform();
 platform.login({
    'username':  process.env.RC_USERNAME,
    'password':  process.env.RC_PASSWORD,
    'extension': process.env.RC_EXTENSION
})

platform.on(platform.events.loginSuccess, function(e){
    read_extension_phone_number()
});

async function read_extension_phone_number(){
  try {
      var resp = await platform.get("/restapi/v1.0/account/~/extension/~/phone-number")
      var jsonObj = await resp.json()
      for (var record of jsonObj.records){
          for (feature of record.features){
              if (feature == "MmsSender"){
                  return send_mms(record.phoneNumber)
              }
          }
      }
  } catch(e) {
      console.log(e.message)
      process.exit(1)
  }
}

async function send_mms(fromNumber){
    var FormData = require('form-data');
    fd = new FormData();
    var body = {
        from: {'phoneNumber': fromNumber},
        to: [{'phoneNumber': RECIPIENT}],
        text: 'Hello World!'
    }
    fd.append('json', new Buffer.from(JSON.stringify(body)), {
        contentType: 'application/json'
    });
    fd.append('attachment', require('fs').createReadStream('TestImage.jpg'));
    try {
    var resp = await platform.post('/restapi/v1.0/account/~/extension/~/mms', fd)
    var jsonObj = await resp.json()
        console.log("MMS sent. Message status: " + jsonObj.messageStatus)
        console.log('Message Id: ' + jsonObj.id)
    }
    catch (e){
        console.log(e.message)
    }
} 
#!/usr/bin/env python

# You get the environment parameters from your 
# application dashbord in your developer account 
# https://developers.ringcentral.com

from ringcentral import SDK
import os,sys

from dotenv import load_dotenv
load_dotenv()

RECIPIENT    = os.environ.get('SMS_RECIPIENT')

rcsdk = SDK( os.environ.get('RC_CLIENT_ID'),
             os.environ.get('RC_CLIENT_SECRET'),
             os.environ.get('RC_SERVER_URL') )
platform = rcsdk.platform()

try:
  platform.login(os.environ.get('RC_USERNAME'),
                 os.environ.get('RC_EXTENSION'),
                 os.environ.get('RC_PASSWORD') )
except:
  sys.exit("Unable to authenticate to platform. Check credentials.")

def read_extension_phone_number():
  try:
    resp = platform.get("/restapi/v1.0/account/~/extension/~/phone-number")
    jsonObj = resp.json()
  except e:
    sys.exit("Unable to fetch SMS-enabled phone numbers")
  for record in jsonObj.records:
    for feature in record.features:
      if feature == "MmsSender":
        return send_mms(record.phoneNumber)
  sys.exit("No MMS-enabled phone number found")

def send_mms(fromNumber):
    builder = rcsdk.create_multipart_builder()
    builder.set_body({
      'from' : { 'phoneNumber': fromNumber },
      'to'   : [ {'phoneNumber': RECIPIENT} ],
      'text' : 'Hello World!'
    })
    image = open ('TestImage.jpg', 'rb')
    attachment = ('TestImage.jpg', image, 'image/jpeg')
    builder.add(attachment)
    try:
        request = builder.request('/account/~/extension/~/sms')
        response = platform.send_request(request)
    except Exception as e:
        print(e)


read_extension_phone_number()
<?php
/* You get the environment parameters from your 
   application dashbord in your developer account 
   https://developers.ringcentral.com */

require('vendor/autoload.php');
$dotenv = Dotenv\Dotenv::createImmutable(__DIR__ . '/../');
$dotenv->load();

const RECIPIENT = $_ENV['SMS_RECIPIENT'] 

$rcsdk = new RingCentral\SDK\SDK( $_ENV['RC_CLIENT_ID'],
$_ENV['RC_CLIENT_SECRET'],
$_ENV['RC_SERVER_URL'] );

$platform = $rcsdk->platform();

$platform->login( $_ENV['RC_USERNAME'],
$_ENV['RC_EXTENSION'],
$_ENV['RC_PASSWORD'] );

$body = array(
    'from' => array( 'phoneNumber' => "username" ),
    'to'   => array( array('phoneNumber' => RECIPIENT ) ),
    'text' => 'Hello World!'
);

$request = $rcsdk->createMultipartBuilder()
    ->setBody( $body )
    ->add(fopen(__DIR__.'/TestImage.jpg', 'r'))
    ->request('/account/~/extension/~/mms');
$r = $platform->sendRequest($request);
?>

Rate this page: