Preview Message API

Preview SMS Messages Before Sending

Introduction to Preview Message API

Welcome to SMSGatewayCenter's Preview Message API! This powerful API allows you to preview SMS messages before sending them. Get detailed information about message type (text/unicode), character count, number of parts, estimated cost, DLT template matching, and more. Perfect for building message preview features in mobile applications, calculating costs before sending, validating message length, and ensuring DLT compliance. Our RESTful endpoint supports both POST and GET methods with application/x-www-form-urlencoded content type for flexible integration.

About Message Preview

The Preview Message API enables you to:

  • Preview message details - Get character count, parts, and message type before sending
  • Calculate costs - Estimate SMS cost based on message length and type
  • Check DLT template match - Verify message matches registered DLT template (if applicable)
  • Validate message length - Ensure messages fit within SMS part limits
  • Detect message type - Identify text vs unicode messages automatically
  • Get template information - Retrieve matched DLT template ID and entity ID
  • Real-time preview - Instant feedback on message characteristics

This API is essential for building user-friendly SMS applications that show message previews, cost estimates, and validation feedback before sending.

What is Message Preview?

Message Preview allows you to analyze SMS messages before sending them. The API returns detailed information including message type (text or unicode), character count, number of SMS parts (single or multi-part), estimated cost, and DLT template matching information. This helps you build better user experiences by showing users exactly what their message will look like and how much it will cost before they send it.


Preview Message

Get a detailed preview of your SMS message including type, length, parts, cost, and DLT template information. Returns comprehensive message analysis without actually sending the SMS.

API Endpoint

https://unify.smsgateway.center/SMSApi/preview

HTTP Method

POST GET

Content Type

application/x-www-form-urlencoded

Important: This API requires application/x-www-form-urlencoded content type for POST requests. Use --data-urlencode in cURL or appropriate encoding in your HTTP client.

 

Required Parameters
KeyValueDescription
Login Credentials (Required)
Authenticate your API request using userid-password or apiKey—choose one method.
useridYour Registered UsernameYour registered username; use if apiKey isn't provided. Signup for User ID
passwordYour PasswordURL-encoded password (for special characters); use if apiKey isn't provided. Signup for API Key
Header (optional) Parameters
apiKeyYour unique apiKeyapiKey needs to be sent as HTTP header when you are not using userid-password method. You can avail this from your user control panel and use instead of userid-password HTTP Request parameter. Please do not disclose this to anyone.

 

Request Parameters
ParameterTypeRequiredDescription
msgStringYesSMS message text to preview. Can include DLT template variables as {#var#}
senderidStringYesSender ID to use for the message (e.g., "SMSGAT")
dltEntityIdStringOptionalDLT Entity ID for India TRAI compliance. Required for DLT template matching
formatStringOptionalResponse format. Use json (recommended), xml, or plain. Default: json
outputStringOptionalAlias for format parameter. Use json for JSON response
Sample Request Code (cURL)

POST Request (JSON Format)

curl -X POST "https://unify.smsgateway.center/SMSApi/preview" \
  -H "Content-Type: application/x-www-form-urlencoded" \
  -d "userid=YOUR_USERNAME" \
  -d "password=YOUR_PASSWORD" \
  -d "msg=Hello, this is a test message" \
  -d "senderid=YOUR_SENDER_ID" \
  -d "dltEntityId=YOUR_ENTITY_ID" \
  -d "format=json"

POST Request (XML Format)

curl -X POST "https://unify.smsgateway.center/SMSApi/preview" \
  -H "Content-Type: application/x-www-form-urlencoded" \
  -d "userid=YOUR_USERNAME" \
  -d "password=YOUR_PASSWORD" \
  -d "msg=Hello, this is a test message" \
  -d "senderid=YOUR_SENDER_ID" \
  -d "dltEntityId=YOUR_ENTITY_ID" \
  -d "format=xml"

POST Request (Plain Text Format)

curl -X POST "https://unify.smsgateway.center/SMSApi/preview" \
  -H "Content-Type: application/x-www-form-urlencoded" \
  -d "userid=YOUR_USERNAME" \
  -d "password=YOUR_PASSWORD" \
  -d "msg=Hello, this is a test message" \
  -d "senderid=YOUR_SENDER_ID" \
  -d "format=plain"

GET Request (Query Parameters)

curl -X GET "https://unify.smsgateway.center/SMSApi/preview?userid=YOUR_USERNAME&password=YOUR_PASSWORD&msg=Hello%2C%20this%20is%20a%20test%20message&senderid=YOUR_SENDER_ID&dltEntityId=YOUR_ENTITY_ID&format=json"

Using API Key (Alternative Authentication)

curl -X POST "https://unify.smsgateway.center/SMSApi/preview" \
  -H "Content-Type: application/x-www-form-urlencoded" \
  -H "apiKey: YOUR_API_KEY" \
  -d "userid=YOUR_USERNAME" \
  -d "msg=Hello, this is a test message" \
  -d "senderid=YOUR_SENDER_ID" \
  -d "format=json"

Without DLT Entity ID (Optional Parameter)

curl -X POST "https://unify.smsgateway.center/SMSApi/preview" \
  -H "Content-Type: application/x-www-form-urlencoded" \
  -d "userid=YOUR_USERNAME" \
  -d "password=YOUR_PASSWORD" \
  -d "msg=Hello, this is a test message" \
  -d "senderid=YOUR_SENDER_ID" \
  -d "format=json"

Example with Unicode Message

curl -X POST "https://unify.smsgateway.center/SMSApi/preview" \
  -H "Content-Type: application/x-www-form-urlencoded" \
  -d "userid=YOUR_USERNAME" \
  -d "password=YOUR_PASSWORD" \
  -d "msg=नमस्ते, यह एक परीक्षण संदेश है" \
  -d "senderid=YOUR_SENDER_ID" \
  -d "format=json"
Sample Response (JSON Format)
{
  "status": "success",
  "statusCode": "200",
  "reason": "Preview generated successfully",
  "msgType": "text",
  "length": 28,
  "parts": 1,
  "dltTemplateId": "1234567890123456",
  "dltEntityId": "YOUR_ENTITY_ID",
  "amount": 0.05,
  "message": "Hello, this is a test message"
}

Response Fields

FieldTypeDescription
Success Response Fields
statusStringResponse status: "success" or "error"
statusCodeStringStatus code: "200" for success
reasonStringResult message: "Preview generated successfully" or error description
msgTypeStringMessage type: "text" for standard SMS or "unicode" for Unicode messages (Hindi, Arabic, etc.)
lengthIntegerCharacter count of the message
partsIntegerNumber of SMS parts required (1 for single SMS, 2+ for multi-part SMS)
dltTemplateIdStringDLT Template ID that matches the message (if DLT entity ID provided and template found)
dltEntityIdStringDLT Entity ID used for template matching
amountFloatEstimated cost per SMS in your account currency
messageStringOriginal message text as submitted
Error Response Fields
statusString"error"
statusCodeStringError code (e.g., "401" for authentication failure, "400" for invalid parameters)
reasonStringError description

Understanding Message Types and Parts

The Preview API automatically detects message type and calculates the number of SMS parts required based on message length and character set.

Message Type Detection
Message TypeCharactersDescriptionExample
textStandard ASCIIStandard English characters, numbers, and basic symbols"Hello, this is a test message"
unicodeExtended UnicodeNon-ASCII characters including Hindi, Arabic, Chinese, emojis, etc."नमस्ते, यह एक परीक्षण संदेश है"
SMS Parts Calculation
Message TypeSingle Part LimitMulti-Part Limit (per part)Maximum Parts
text160 characters153 characters per partUp to 255 parts
unicode70 characters67 characters per partUp to 255 parts

Note: Multi-part SMS messages are automatically concatenated by mobile operators and delivered as a single message to the recipient.


Integration Examples

Example 1: Message Preview in Mobile App

// React Native / JavaScript example
async function previewMessage(message, senderId, dltEntityId) {
  const params = new URLSearchParams({
    userid: 'YourUsername',
    password: 'YourPassword',
    output: 'json',
    msg: message,
    senderid: senderId,
    dltEntityId: dltEntityId || ''
  });

  try {
    const response = await fetch('https://unify.smsgateway.center/SMSApi/preview', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/x-www-form-urlencoded'
      },
      body: params.toString()
    });

    const data = await response.json();
    
    if (data.status === 'success' && data.statusCode === '200') {
      console.log('Message Preview:');
      console.log(`Type: ${data.msgType}`);
      console.log(`Length: ${data.length} characters`);
      console.log(`Parts: ${data.parts}`);
      console.log(`Cost: ${data.amount} per SMS`);
      
      if (data.dltTemplateId) {
        console.log(`DLT Template ID: ${data.dltTemplateId}`);
      }
      
      // Display preview in UI
      return {
        type: data.msgType,
        length: data.length,
        parts: data.parts,
        cost: data.amount,
        dltTemplateId: data.dltTemplateId
      };
    } else {
      console.error(`Preview failed: ${data.reason}`);
      return null;
    }
  } catch (error) {
    console.error('Preview error:', error);
    return null;
  }
}

// Usage in React Native component
const MessagePreview = ({ message, senderId }) => {
  const [preview, setPreview] = useState(null);
  
  useEffect(() => {
    if (message && message.length > 0) {
      previewMessage(message, senderId).then(setPreview);
    }
  }, [message, senderId]);
  
  if (!preview) return null;
  
  return (
    <View>
      <Text>Type: {preview.type}</Text>
      <Text>Length: {preview.length} characters</Text>
      <Text>Parts: {preview.parts}</Text>
      <Text>Cost: {preview.cost} per SMS</Text>
    </View>
  );
};

Example 2: Cost Calculator

import requests
from urllib.parse import urlencode

def calculate_sms_cost(userid, password, message, sender_id, dlt_entity_id=None):
    url = 'https://unify.smsgateway.center/SMSApi/preview'
    
    data = {
        'userid': userid,
        'password': password,
        'format': 'json',
        'msg': message,
        'senderid': sender_id
    }
    
    if dlt_entity_id:
        data['dltEntityId'] = dlt_entity_id
    
    headers = {
        'Content-Type': 'application/x-www-form-urlencoded'
    }
    
    response = requests.post(url, data=data, headers=headers)
    result = response.json()
    
    if result['status'] == 'success':
        parts = result.get('parts', 1)
        amount_per_sms = float(result.get('amount', 0))
        total_cost = parts * amount_per_sms
        
        return {
            'message_type': result.get('msgType', 'text'),
            'length': result.get('length', 0),
            'parts': parts,
            'cost_per_sms': amount_per_sms,
            'total_cost': total_cost,
            'dlt_template_id': result.get('dltTemplateId')
        }
    else:
        raise Exception(f"Preview failed: {result.get('reason', 'Unknown error')}")

# Calculate cost for bulk sending
message = "Hello, this is a test message"
sender_id = "YOUR_SENDER_ID"
recipient_count = 1000

preview = calculate_sms_cost('YourUsername', 'YourPassword', message, sender_id)
total_cost = preview['total_cost'] * recipient_count

print(f"Message Type: {preview['message_type']}")
print(f"Length: {preview['length']} characters")
print(f"Parts: {preview['parts']}")
print(f"Cost per SMS: {preview['cost_per_sms']}")
print(f"Total cost for {recipient_count} recipients: {total_cost}")

Example 3: PHP Integration

<?php
function previewSMSMessage($userid, $password, $message, $senderId, $dltEntityId = null) {
    $url = 'https://unify.smsgateway.center/SMSApi/preview';
    
    $postData = array(
        'userid' => $userid,
        'password' => $password,
        'output' => 'json',
        'msg' => $message,
        'senderid' => $senderId
    );
    
    if ($dltEntityId !== null) {
        $postData['dltEntityId'] = $dltEntityId;
    }
    
    $ch = curl_init($url);
    curl_setopt($ch, CURLOPT_POST, 1);
    curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($postData));
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/x-www-form-urlencoded'));
    
    $response = curl_exec($ch);
    $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    curl_close($ch);
    
    if ($httpCode === 200) {
        $result = json_decode($response, true);
        
        if ($result['status'] === 'success') {
            return array(
                'success' => true,
                'msgType' => $result['msgType'],
                'length' => $result['length'],
                'parts' => $result['parts'],
                'amount' => $result['amount'],
                'dltTemplateId' => $result['dltTemplateId'] ?? null,
                'message' => $result['message']
            );
        } else {
            return array(
                'success' => false,
                'error' => $result['reason'] ?? 'Unknown error'
            );
        }
    } else {
        return array(
            'success' => false,
            'error' => 'HTTP Error: ' . $httpCode
        );
    }
}

// Usage
$preview = previewSMSMessage(
    'YourUsername',
    'YourPassword',
    'Hello, this is a test message',
    'YOUR_SENDER_ID',
    'YOUR_ENTITY_ID' // Optional
);

if ($preview['success']) {
    echo "Message Type: " . $preview['msgType'] . "\n";
    echo "Length: " . $preview['length'] . " characters\n";
    echo "Parts: " . $preview['parts'] . "\n";
    echo "Cost: " . $preview['amount'] . " per SMS\n";
    
    if ($preview['dltTemplateId']) {
        echo "DLT Template ID: " . $preview['dltTemplateId'] . "\n";
    }
} else {
    echo "Error: " . $preview['error'] . "\n";
}

Error Codes

Status CodeStatusReasonDescription
200successPreview generated successfullyMessage preview generated successfully
400errorInvalid parametersMissing or invalid required parameters (msg, senderid, etc.)
401errorAuthentication failedInvalid username, password, or API key
500errorInternal server errorServer error occurred while processing the request

Best Practices

Recommendations

  • Preview Before Sending: Always preview messages before sending to show users cost and length information
  • Use x-www-form-urlencoded: Ensure proper content-type header is set for POST requests
  • URL Encoding: Use proper URL encoding for special characters in message text
  • Cost Calculation: Use preview API to calculate total costs before bulk sending
  • Length Validation: Check message length and parts to prevent unexpected costs
  • DLT Template Matching: Provide DLT entity ID to get template matching information
  • Unicode Detection: Use preview to detect unicode messages and adjust UI accordingly
  • Real-time Preview: Call preview API as user types to show live character count and cost
  • Error Handling: Handle preview errors gracefully and show user-friendly messages
  • Cache Results: Cache preview results for identical messages to reduce API calls

Common Use Cases

Message Preview UI

Show users a preview of their message with character count, parts, and estimated cost before sending.

Cost Calculator

Calculate total SMS costs for bulk campaigns before sending to help users budget their campaigns.

Length Validator

Validate message length and warn users if messages exceed recommended limits or become multi-part.

DLT Template Preview

Preview messages with DLT template matching to ensure compliance before sending.

Unicode Detection

Automatically detect unicode messages and adjust UI or pricing accordingly.

Real-time Feedback

Provide real-time character count, parts, and cost as users type their messages.

Testimonials

Why do Great Businesses Trust SMS Gateway Center?

K

Kurlon IT

2022-08-04

We have tied up with other SMS providers also, but SMS GatewayCenter is quite good. Good Service from the team. We are very happy with the service be it accounts related or technical issue. We always get good response.

I

INOX Air Products

2018-02-09

We have an excellent experience with SMS Gateway Center. The services and support has been of very high standard.

S

Shalabh Arora

2025-04-11

I’ve been using SMSGatewayCenter’s bulk SMS and WhatsApp services since early 2022 for my small business, and the experience has been fantastic. The platform is intuitive, and the message delivery is incredibly reliable, reaching my customers without fail. The 24/7 support team is quick to assist, and the cost-effectiveness is a big plus. It’s transformed how I connect with my audience, and I highly recommend it to other entrepreneurs! (Google Revirews)

R

Reflex

2025-04-11

We’ve been using your bulk SMS services for a few months, and the results have been phenomenal. The open rates and customer engagement have gone through the roof. Highly recommend for any business looking to scale fast! (Google Revirews)

V

Vedanth Gowda

2025-04-18

I’m Vedanth Gowda, leading a finance business, and I’ve been leveraging SMSGatewayCenter’s bulk SMS and WhatsApp tools —absolutely transformative! The platform’s speed and precision in delivering financial alerts to my clients are unmatched, giving me a competitive edge. Samrat’s expertise in tailoring notification workflows for market updates was a standout, and the robust security features instilled trust. The affordable pricing and proactive support team make it a no-brainer. Perfect for finance pros aiming to elevate client trust and efficiency! (Google Revirews)

N

Naval Bhatnagar

2025-04-12

From day one, the team at SMS GATEWAY CENTER guided us through setup, testing, and launching campaigns. Their support is A+. Whether you’re new to SMS marketing or experienced, they make it smooth. Thank you Aakash. (Google Revirews)


CTA for Unlock Real-Time Messaging – Integrate Today!

Unlock Real-Time Messaging – Integrate Today!

Try Our API in a Sandbox Environment Before Going Live!

Join Thousands of Developers – Try Our API Now!

Get in touchSign up