Frequently Asked Questions
Use the Plivo Node.js SDK and the client.messages.create()
method with type: 'mms'
and media_urls
set to an array of media URLs. This allows you to send multimedia messages like images and GIFs along with text from your Node application.
The Plivo Node.js SDK is a library that simplifies interaction with the Plivo communications platform, allowing developers to send SMS, MMS, and make voice calls programmatically within Node.js applications. The SDK handles authentication, API calls, and responses.
Plivo requires MMS-enabled numbers because standard SMS numbers often lack the capability to handle multimedia content. MMS-enabled numbers are specifically provisioned to support sending and receiving images, videos, and audio files.
Use media_ids
when you've pre-uploaded media to Plivo's servers, either through the console or API. This is suitable for frequently used media or if you don't have readily available public URLs. Use media_urls
if you have files hosted online and accessible via public links.
No, with a Plivo trial account, you can only send MMS to phone numbers verified as sandbox numbers in your Plivo console. This restriction is in place for testing and prevents misuse during the trial period.
Store your Plivo Auth ID, Auth Token, and sender number in a .env
file in your project's root directory. Then use the dotenv
library in your Node.js code to load these variables into process.env
.
A client application makes a request to your Node.js/Express server, which uses the Plivo SDK to interact with the Plivo API. Plivo then processes the request, validates it, and sends the MMS via carrier networks to the recipient's mobile device.
Define a POST route (e.g., /send-mms
) in your Express app. This endpoint receives the recipient number, message text, and media URL from the request body, validates them, uses the Plivo SDK to send the MMS, and returns a response to the client.
The .gitignore
file prevents sensitive data (like your .env
file containing Plivo credentials) and large directories (like node_modules
) from being committed to version control, enhancing security and repository efficiency.
Input validation prevents issues such as invalid phone numbers, incorrect URLs, or oversized messages from causing errors or security vulnerabilities in your MMS sending application. Basic validation is shown in the example, but production systems should use libraries for stricter validation.
Use try...catch
blocks to handle errors during the Plivo API call. Log detailed error information, including Plivo's error messages and status codes, for debugging. Return appropriate HTTP status codes and informative error messages to the client.
Retry mechanisms, using exponential backoff, handle transient network issues or temporary service disruptions by resending failed MMS requests after increasing delays. This improves the reliability of your application.
Use middleware like express-rate-limit
to restrict the number of MMS requests a client can make within a specific timeframe, based on IP or API key. This prevents abuse and manages costs.
Secure your API with authentication (API keys, JWT), input validation, and rate limiting. Always use HTTPS in production. Store sensitive data (like API keys) in environment variables and never hardcode them.
Learn how to send MMS messages with Plivo using Node.js and Express in this comprehensive guide. Multimedia Messaging Service (MMS) lets you enrich user communication by sending images, videos, and audio files alongside text messages.
This tutorial shows you how to build a production-ready MMS API using the Plivo Node.js SDK and Express framework. You'll start with a basic script and progressively build toward a robust API endpoint capable of handling MMS requests – covering setup, authentication, error handling, security, and deployment best practices.
Project Overview and Goals
What You're Building:
Create a Node.js application that programmatically sends MMS messages via Plivo's API. This involves:
POST /send-mms
) that accepts recipient details, text, and a media URL to send an MMSProblem Solved:
Integrate rich media messaging capabilities into your applications – move beyond simple text (SMS) to create engaging user experiences for notifications, alerts, marketing, or customer support.
Technologies Used:
dotenv
– Module to load environment variables from a.env
file, keeping sensitive credentials out of source codeSystem Architecture:
The basic flow for sending an MMS via your API endpoint looks like this:
Prerequisites:
node -v
andnpm -v
. Compatible with Node.js versions 5.5 and higher per the Plivo SDK documentation. Learn more about E.164 phone number formatting for international compliance.Expected Outcome:
You'll have a functional Node.js application capable of sending MMS messages programmatically – both via a direct script and through a secure, testable API endpoint. You'll understand the key configuration steps, error handling, and best practices for using Plivo's MMS API.
Setting Up Your Node.js MMS Project
Initialize your Node.js project and install the necessary dependencies.
Create Project Directory: Open your terminal and create a new directory for your project:
Initialize Node.js Project: Create a
package.json
file to manage your project's dependencies and scripts:Install Dependencies: Install the Plivo Node.js SDK, Express framework, and
dotenv
for managing environment variables:plivo
– Official Plivo library for interacting with their APIexpress
– Web server framework for building your API endpointdotenv
– Loads environment variables from a.env
fileCreate Project Structure: Set up the basic file structure:
Configure Environment Variables (
.env
): Create a file named.env
in your project root. This file holds your sensitive Plivo credentials and phone number. Never commit this file to version control.YOUR_PLIVO_AUTH_ID
andYOUR_PLIVO_AUTH_TOKEN
with credentials from your Plivo Console dashboardYOUR_MMS_ENABLED_PLIVO_NUMBER
with your E.164 formatted Plivo phone number (e.g.,+14155551212
)Configure
.gitignore
: Create a file named.gitignore
in your project root. Addnode_modules
and.env
to prevent committing them to your Git repository:Why
.gitignore
? Security and efficiency –node_modules
can be large and easily reinstalled usingnpm install
..env
contains sensitive API keys that should never be exposed in your codebase history.Your project environment is ready for implementation.
Implementing MMS Sending with Plivo SDK
Create a simple script to send one MMS message directly using the Plivo SDK. This helps verify your credentials and Plivo number setup.
Create the Sending Script (
send-mms.js
): Create the filesend-mms.js
and add the following code:Explanation:
require('dotenv').config();
loads the variables from your.env
file intoprocess.env
recipientNumber
to a valid target number before running. If using a trial account, ensure it's a verified sandbox number.new plivo.Client()
initializes the connection to the Plivo API using your Auth ID and Tokenclient.messages.create()
is the core function call:src
: Your MMS-enabled Plivo number (from.env
)dst
: The recipient's numbertext
: The message bodytype: 'mms'
: Crucial for sending MMS. Without this, it defaults to SMS.media_urls
: An array containing one or more publicly accessible URLs pointing to the media files (images, GIFs, videos, audio). Plivo fetches the media from these URLs. Ensure the URLs are valid and accessible..then()
handles the successful API response from Plivo, typically containing message UUIDs and status information.catch()
catches and logs any errors during the API call (e.g., invalid credentials, invalid number format, inaccessible media URL)Run the Script: Execute the script from your terminal:
Verification:
+1…
), or inaccessiblemedia_urls
.Building an Express API Endpoint for MMS
While the script is useful for testing, a more practical approach is to create an API endpoint that other services or frontends can call to send MMS messages.
Create the Express App (
app.js
): Create the fileapp.js
and add the following code:Explanation:
express
andplivo
, loads.env
express.json()
andexpress.urlencoded()
are essential for parsing incoming request bodies (JSON and form data)/send-mms
Endpoint (POST):POST
requests at the/send-mms
pathrecipientNumber
,messageText
, andmediaUrl
from the request body (req.body
)^\+[1-9]\d{1,14}$
) is a basic check; while helpful, it might allow technically invalid numbers (e.g., incorrect length for a country). For production, use a dedicated library likelibphonenumber-js
for robust phone number validation.mediaUrl
Handling: This implementation expects a singlemediaUrl
field in the request body. It then wraps this URL in an array ([mediaUrl]
) as required by the Plivo API'smedia_urls
parameter. Modify the API to accept an array of URLs directly if needed.async/await
for cleaner handling of the asynchronous Plivo API callplivoClient.messages.create
within atry…catch
block/health
Endpoint (GET): A simple endpoint used for monitoring to check if the service is runningapp.listen()
: Starts the Express server on the specified port and provides a samplecurl
command for local testingRun the API Server: Execute the app from your terminal:
You should see the message "MMS Sender API listening on port 3000" and the sample
curl
command.Test the API Endpoint: Use
curl
(or tools like Postman or Insomnia) to send a POST request to your running server. Open a new terminal window (leave the server running in the first one).IMPORTANT: Replace the placeholder values below (
+14155551234
and themediaUrl
) with a valid recipient number (remember the sandbox verification requirement if using a Plivo trial account) and a working, publicly accessible media URL.Verification:
node app.js
is running for log messagesPlivo API Authentication and Configuration
You've already used the Plivo credentials. Here's where to find them and how they work.
Auth ID and Auth Token:
.env
locally, secure configuration management in production) and never hardcode them directly into your source code. Usedotenv
locally and your deployment platform's environment variable system in production.MMS-Enabled Plivo Number (
src
):+14155551212
).env
file asPLIVO_SENDER_NUMBER
Media URLs (
media_urls
):content-type
andcontent-length
response headers, otherwise Plivo will reject the requestmedia_urls
andmedia_ids
)media_ids
): Upload media directly to Plivo via their console (Messaging > MMS Media Upload) or API. Uploaded media gets amedia_id
. You can then usemedia_ids: ['YOUR_MEDIA_ID']
instead ofmedia_urls
. This can be useful for frequently used media or if you don't have a public hosting location. The same size limits apply (2 MB per media, 5 MB total).Plivo Console Dashboard: Familiarize yourself with:
MMS Error Handling and Retry Logic
Robust applications need solid error handling and logging.
Error Handling Strategy:
try…catch
blocks around asynchronous operations like Plivo API callsapp.js
) and return clear4xx
error responses5xx
for server/Plivo issues,4xx
for client errors) and informative JSON error messages to the API caller.catch
blocks handle generic network errors too.Logging:
console.log
andconsole.error
are sufficient for simple cases and developmentwinston
orpino
. These offer:Example using
console
(adapt for libraries):Retry Mechanisms:
async-retry
orp-retry
can simplify this. Be cautious about retrying errors that are clearly not transient (e.g._ 401 Unauthorized_ 400 Bad Request due to invalid number format). Only retry on likely temporary issues (e.g._ 5xx errors_ network timeouts).Conceptual example (without a library):
Tracking MMS Status with a Database
While your simple API doesn't require a database, a production system often benefits from one for:
messageUuid
returned by Plivo and later update its status (sent, delivered, failed) using Plivo's message status callbacks (webhooks)If adding a database (e.g., PostgreSQL with Prisma):
Schema Design (Conceptual
schema.prisma
):Data Access: Use an ORM like Prisma or Sequelize to interact with the database, providing type safety and simplifying queries. Your API endpoint would first save a record with
status: 'initiated'
and then update it based on the Plivo API response or subsequent status callbacks.Migrations: Use the ORM's migration tools (e.g.,
prisma migrate dev
,sequelize db:migrate
) to manage schema changes safely.This section is conceptual. Implementing a full database layer is beyond the scope of this specific MMS sending guide but is a common next step for production systems.
Security Best Practices for MMS APIs
Secure your API endpoint.
Input Validation and Sanitization:
joi
,express-validator
,libphonenumber-js
) to enforce strict rules onrecipientNumber
(valid E.164 format),messageText
(length limits, character types), andmediaUrl
(valid URL format, perhaps restricting domains).messageText
that might be displayed elsewhere, use libraries likedompurify
(for HTML) or ensure proper escaping to prevent cross-site scripting (XSS). Plivo handles the SMS/MMS encoding.Authentication/Authorization:
Authorization: Bearer YOUR_API_KEY
orX-API-Key: YOUR_API_KEY
). Your Express app verifies the key against a stored list/database before processing the request.Rate Limiting:
express-rate-limit
. Configure it based on IP address or API key.Example using
express-rate-limit
:HTTPS: Always use HTTPS in production to encrypt data in transit. Deployment platforms like Heroku or using a reverse proxy like Nginx typically handle TLS/SSL termination.
Environment Variables: Keep sensitive data (API keys, Plivo Auth tokens) out of your code using environment variables. Ensure your
.env
file is in.gitignore
. For production, do not deploy the.env
file. Instead, use your hosting platform's built-in environment variable configuration (e.g., Heroku Config Vars, AWS Parameter Store, Azure App Configuration) or a dedicated secrets management service (e.g., AWS Secrets Manager, HashiCorp Vault). For related SMS implementations, check out our guides on basic SMS sending with Plivo and two-way messaging.Frequently Asked Questions
What is the maximum file size for MMS attachments with Plivo?
Plivo supports a maximum of 2 MB per attachment with up to 10 attachments per message. The total message size (text + all attachments) must be less than 5 MB. Messages exceeding 5 MB will fail with error code 120. For optimal carrier compatibility, keep attachments under 600 KB for US carriers and under 1 MB for Canadian carriers.
Can I send MMS messages internationally with Plivo?
No. Plivo MMS is only available for US and Canadian phone numbers. You need a US or Canadian Plivo number to send MMS, and recipients must also be in the US or Canada. For international messaging, consider using SMS or other messaging channels like WhatsApp.
How do I send MMS from a Plivo trial account?
Trial accounts can only send MMS to verified sandbox numbers. Add recipient numbers in the Plivo Console under Phone Numbers > Sandbox Numbers. Trial accounts cannot use alphanumeric sender IDs and require a minimum $25 recharge to upgrade and remove restrictions.
What media formats does Plivo MMS support?
Plivo fully supports and formats JPEG, PNG, and GIF images for device compatibility. Additional formats (various image, video, and audio types) are accepted but not automatically formatted for destination devices. See the complete list of supported MIME types. Always test with your target carriers to ensure compatibility.
How do I handle MMS delivery status in Node.js?
Implement webhook endpoints to receive Plivo delivery status callbacks. Configure the callback URL in your Plivo Console under message settings or use the
url
parameter when sending messages via the Send Message API. Your Express app should handle POST requests containing status updates (queued, sent, delivered, failed) and store them in your database using the message UUID.Can I send the same media file to multiple recipients?
Yes. Upload media to Plivo using Messaging > MMS Media Upload in the console or via the Upload Media API. You'll receive a
media_id
that you can reuse across multiple messages without re-uploading. This approach is more efficient than usingmedia_urls
for frequently sent media.What's the difference between media_urls and media_ids?
media_urls
are publicly accessible URLs that Plivo fetches when sending the MMS.media_ids
refer to media files you've pre-uploaded to Plivo's servers. Usemedia_ids
for frequently used media or when you don't have public hosting. Both methods support the same file size limits (2 MB per file, 5 MB total).How do I test MMS sending locally in development?
Run your Express server locally with
node app.js
, then use curl or Postman to send POST requests tohttp://localhost:3000/send-mms
. Ensure your Plivo credentials are in.env
and recipient numbers are verified in sandbox (for trial accounts). Check the Plivo Console logs for detailed delivery information.Why is my MMS failing with error code 120?
Error code 120 indicates your message exceeds the 5 MB total size limit. Check that each attachment is under 2 MB and the combined size of all attachments plus text is under 5 MB. Consider compressing images or videos before sending, or split content across multiple messages.
Can toll-free numbers send MMS with Plivo?
Yes. Plivo added MMS support for toll-free numbers in July 2020. However, as of January 31, 2024, unverified toll-free numbers may have messages blocked. Verify MMS capability and toll-free verification status in the Plivo Console under Phone Numbers > Your Numbers before sending.