How to Send SMS to San Marino: Complete Guide (+378 Compliance & API)
Learn how to send SMS messages to San Marino mobile numbers (+378). Complete guide covering GDPR Law 171 compliance, alphanumeric sender IDs, message format limits, and API integration with Twilio, Sinch, Plivo, and MessageBird.
Sending SMS messages to San Marino (+378) requires understanding specific compliance requirements, phone number formats, and technical limitations. This comprehensive guide covers everything you need to know about SMS delivery to San Marino, including GDPR-aligned Law 171 compliance, alphanumeric sender IDs, message character limits, and API integration examples for Twilio, Sinch, Plivo, and MessageBird.
Delivery Performance: Expect delivery rates above 95% to mobile numbers when you use properly formatted sender IDs and compliant content. Messages typically deliver in 3–10 seconds during normal network conditions.
Key SMS Features and Capabilities in San Marino
San Marino supports basic SMS functionality with limitations on advanced features. All services route through Italian carriers because San Marino lacks domestic telecommunication infrastructure.
Two-Way SMS Support
San Marino does not support two-way SMS according to current provider specifications. You cannot receive replies through standard A2P channels.
Workarounds for two-way communication:
Include a web link in your SMS directing recipients to a response form
Provide a dedicated phone number for voice callback
Direct users to email or mobile app for responses
Use WhatsApp Business API as an alternative for interactive messaging
Concatenated Messages (Segmented SMS)
Support: San Marino does not support concatenated messages.
Message length rules: Standard SMS character limits apply – 160 characters for GSM-7 encoding and 70 characters for Unicode (UCS-2).
Encoding considerations: Both GSM-7 and UCS-2 encodings are supported, though messages cannot be concatenated.
Character counting and truncation:
GSM-7 encoding: Messages exceeding 160 characters will be truncated at the 160-character mark
UCS-2 encoding (Unicode): Messages exceeding 70 characters will be truncated at 70 characters
Extended GSM characters (e.g., |, ^, €, {, }, [, ], ~, \\) count as 2 characters each
Calculate message length accounting for encoding before sending to detect potential truncation
Test with your SMS provider's character counter or implement length validation in your application
MMS messages are automatically converted to SMS with an embedded URL link. Host multimedia content separately and link it within the message body.
Best practices for multimedia content hosting:
Use HTTPS URLs for security and deliverability
Keep URLs short (use URL shorteners like bit.ly, tinyurl.com)
Host images at recommended sizes: max 1 MB, 640×480 px for compatibility
Set appropriate cache headers for faster loading
Ensure landing pages are mobile-optimized
Monitor link click-through rates to measure engagement
San Marino Phone Number Format (+378)
Number Portability
San Marino does not offer number portability. Mobile numbers remain tied to their original carriers.
Carrier identification: According to Wikipedia, San Marino phone numbers follow these patterns:
Mobile numbers start with 6 (format: +378 6XXX XXXX)
Landlines start with 0, 8, or 9
IP telephony services use 5
Premium numbers use 7
Sending SMS to Landlines
You cannot send SMS to landline numbers in San Marino. Attempts to send to landlines fail with a 400 response error (error code 21614) from messaging APIs. These messages won't appear in logs, and you won't be charged.
Landline detection validation:
JavaScript
functionisSanMarinoMobile(phoneNumber) {
// Remove country code and formattingconst cleaned = phoneNumber.replace(/[\s\-\(\)]/g, '');
// Check if it starts with +378 6 (mobile) or 378 6if (cleaned.match(/^\+?3786/)) {
returntrue;
}
// Landlines start with 0, 8, or 9if (cleaned.match(/^\+?378[089]/)) {
returnfalse; // Landline
}
returnnull; // Unknown/invalid
}
San Marino SMS Compliance and GDPR Regulations
San Marino follows Data Protection Law (Law No. 171 of 21 December 2018), which aligns closely with GDPR principles. The Authority for Personal Data Protection (Autorità Garante per la Protezione dei Dati Personali) oversees compliance. All SMS communications must adhere to these standards, particularly regarding personal data processing and storage.
Infringements of basic processing principles (Articles 5, 6, 9)
Violations of data subjects' rights (Articles 12-22)
Failure to obtain proper consent (Article 7)
Unauthorized international data transfers
Data retention requirements:
Retain consent records for the duration of the relationship plus 3 years
Delete personal data when no longer necessary for original purpose
Document data retention periods in your privacy policy
Implement automated deletion processes for expired data
Maintain audit logs of data processing activities for at least 1 year
Consent and Opt-In Requirements
Explicit Consent Requirements:
Obtain written or electronic consent before sending marketing messages
Ensure consent is freely given, specific, and informed
Keep detailed records of when and how you obtained consent
Provide clear information about how you'll use the phone number
Include your business name and purpose in consent requests
Consent refresh: Re-confirm consent every 24 months for marketing communications, or when you significantly change how you process data. Transactional messages do not require consent renewal if within the original scope.
HELP/STOP and Other Commands
Include clear opt-out instructions in all marketing messages
Honor STOP commands immediately (within 1 hour)
Provide HELP responses in Italian (primary language) and English
Support common keywords: STOP, ANNULLA, AIUTO, INFO, HELP
Maintain logs of all opt-out requests and their processing dates
Example message templates:
Italian HELP response:
Code
Hai richiesto AIUTO. Questo servizio invia aggiornamenti da [Nome Azienda]. Per fermare i messaggi, rispondi STOP. Contatto: [email/telefono]. Costi standard applicabili.
English HELP response:
Code
You requested HELP. This service sends updates from [Company Name]. To stop messages, reply STOP. Contact: [email/phone]. Standard rates apply.
Italian STOP confirmation:
Code
Sei stato rimosso dalla lista. Non riceverai più messaggi da [Nome Azienda]. Per riattivare, contatta [email/telefono].
English STOP confirmation:
Code
You've been unsubscribed. You'll no longer receive messages from [Company Name]. To resubscribe, contact [email/phone].
Restrictions: Cannot be all numeric; no special characters except space
Best practices for effective sender IDs:
Use your company or brand name (e.g., "AcmeCorp", "BankAlert")
Keep it short and recognizable (6–8 characters ideal)
Be consistent across all campaigns
Avoid generic terms like "INFO" or "ALERT"
Test sender ID preservation with your provider before large campaigns
Long Codes
Domestic vs. International:
Domestic long codes are supported but not available through major providers
International long codes are commonly used as an alternative
Sender ID preservation: Original sender IDs are typically preserved
Provisioning time: 1–3 business days for international long codes
Use cases: Ideal for transactional messages and two-factor authentication
Cost considerations: International long codes typically cost $1–5/month per number plus per-message fees ($0.01–0.05 per SMS). Domestic options, when available, may have lower per-message costs but similar monthly fees.
Short Codes
Support: San Marino does not currently support short codes
Provisioning time: Not applicable
Use cases: Not available for marketing or authentication purposes
Short codes are unavailable in San Marino due to small market size and lack of local infrastructure. Italian carrier infrastructure does not extend short code support to San Marino numbers.
Restricted SMS Content, Industries, and Use Cases
Restricted Industries and Content:
Gambling and betting services
Adult content or services
Cryptocurrency promotions
Political messaging without proper authorization
Religious content without proper consent
Examples of violations:
Gambling: "Win big at [Casino]! Deposit now and get 100% bonus!"
Adult content: Any sexually explicit material or links to adult websites
Crypto: "Invest in [Coin] now! 500% guaranteed returns!"
Political: Unsolicited campaign messages or political fundraising
Religious: Proselytizing or religious conversion messaging without opt-in
Enforcement and penalties: Violations result in:
Immediate message blocking by carriers
Sender ID blacklisting
Account suspension by SMS providers
GDPR fines up to €20 million or 4% of global revenue for data protection violations
Legal action from recipients or regulatory authorities
Content Filtering
Known Carrier Filters:
URLs from unknown domains may be blocked
Messages containing certain keywords related to restricted industries
Multiple exclamation marks or all-caps messages
Best Practices to Avoid Filtering:
Use registered URL shorteners (bit.ly, t.co, etc.)
Limit punctuation to 1–2 exclamation marks per message
Maintain consistent sender IDs
Include clear business identification
Keep message content professional and straightforward
Excessive punctuation definition:
More than 2 consecutive exclamation marks (!!!)
More than 3 total exclamation marks in a message
ALL CAPS for more than 3 consecutive words
Excessive use of special characters (*****, !?!?!?)
Message formatting comparison:
Well-formatted (not filtered):
Code
Your order #12345 has shipped! Track here: bit.ly/track12345
- AcmeStore
Likely to be filtered:
Code
URGENT!!! ORDER NOW!!! HUGE SAVINGS!!! CLICK HERE: suspiciousdomain.xyz/offer
Best Practices for Sending SMS in San Marino
Messaging Strategy
Keep messages under 160 characters when possible
Include clear calls to action
Use personalization tokens thoughtfully
Maintain consistent branding across messages
Effective CTAs in SMS:
Use action verbs: "Reply", "Visit", "Call", "Click"
Bounce rate: Failed messages / total sent (target: <2%)
Response rate: Replies / messages delivered (varies by use case)
SMS API Integration Examples for San Marino
Twilio SMS API Integration
Twilio provides a REST API for sending SMS messages to San Marino. Store your account SID and auth token securely in environment variables for authentication.
TypeScript
import * asTwiliofrom'twilio';
// Initialize Twilio client with your credentialsconst client = newTwilio(
process.env.TWILIO_ACCOUNT_SID, // Your Account SID
process.env.TWILIO_AUTH_TOKEN// Your Auth Token
);
// Function to send SMS to San Marino with error handling and retry logicasyncfunctionsendSMSToSanMarino(to: string,
message: string,
senderId: string,
maxRetries: number = 3) {
// Validate message lengthif (message.length > 160) {
thrownewError('Message exceeds 160 characters and will be truncated in San Marino');
}
// Validate phone number formatif (!to.match(/^\+3786\d{7,8}$/)) {
thrownewError('Invalid San Marino mobile number format. Expected: +378 6XXX XXXX');
}
let attempt = 0;
while (attempt < maxRetries) {
try {
const formattedNumber = to.startsWith('+378') ? to : `+378${to}`;
const response = await client.messages.create({
body: message,
from: senderId,
to: formattedNumber,
statusCallback: 'https://your-webhook.com/status'
});
console.log(`Message sent successfully! SID: ${response.sid}`);
return response;
} catch (error: any) {
attempt++;
// Handle specific error codesif (error.code === 21614) {
thrownewError('Invalid phone number format – likely landline');
} elseif (error.code === 21408) {
// Rate limit exceeded - exponential backoffconst waitTime = Math.pow(2, attempt) * 1000;
console.log(`Rate limited. Waiting ${waitTime}ms before retry ${attempt}/${maxRetries}`);
awaitnewPromise(resolve =>setTimeout(resolve, waitTime));
} elseif (error.code === 21611) {
thrownewError('Message content rejected by carrier – check for restricted content');
} elseif (attempt >= maxRetries) {
console.error('Max retries reached:', error);
throw error;
} else {
// Generic retry with exponential backoffconst waitTime = Math.pow(2, attempt) * 1000;
awaitnewPromise(resolve =>setTimeout(resolve, waitTime));
}
}
}
}
Sinch SMS API Integration
Sinch offers an API for SMS delivery to San Marino with delivery reports and batch sending.
Provider-specific support channels through account dashboards
Frequently asked questions
Format the recipient's phone number with the +378 country code and use an SMS API like Twilio, Sinch, MessageBird, or Plivo. These APIs provide easy integration and reliable delivery to San Marino numbers. Ensure your messages adhere to local regulations and best practices for optimal delivery rates.
San Marino adheres to standard SMS character limits: 160 characters for GSM-7 encoding and 70 characters for UCS-2. Concatenated messages are not supported, so keep individual messages within these limits.
MMS is automatically converted to SMS with a URL link because San Marino has limitations on direct MMS support. This method allows for rich media content delivery by hosting content externally and linking to it within the SMS message.
Adhere to the 8:00 AM to 8:00 PM Central European Time (CET/CEST) window. Avoid sending messages during public holidays and consider Italian holidays due to close ties between the regions. Emergency messages are an exception.
Yes, alphanumeric sender IDs are supported in San Marino and do not require pre-registration. Sender IDs are usually preserved, though variations may occur based on carrier networks.
San Marino's data protection law (Law No. 171 of 2018), aligned with GDPR, mandates explicit consent for marketing messages. You must offer clear opt-out instructions (STOP, ANNULLA, AIUTO, INFO), maintain meticulous consent records, and respect user privacy.
Process opt-out requests (STOP, ANNULLA) within 24 hours. Maintain comprehensive records of opt-outs, including dates and methods. Ensure all marketing messages contain clear opt-out instructions and regularly audit your compliance.
Gambling, adult content, cryptocurrency promotions, unauthorized political messaging, and religious content without consent are restricted. Avoid content that may trigger carrier filters, like suspicious URLs and excessive punctuation.
Prioritize concise messages under 160 characters, clear calls to action, and personalized content. Limit sending frequency to 2-3 messages per week, respect local time zones, and always offer an opt-out option.
Use the Twilio REST API with your account SID and auth token. Format San Marino numbers with +378, specify your alphanumeric sender ID or long code, and implement status callbacks for delivery tracking.
Twilio, Sinch, MessageBird, and Plivo all provide APIs with robust features for sending and managing SMS messages to San Marino, including delivery reports and support for various sender ID types.
Adhere to provider rate limits (usually 1-10 messages per second) and use exponential backoff for retries. Consider queue systems like Redis or RabbitMQ for high-volume sending to ensure smooth delivery without exceeding limits.
Common errors include 21614 (invalid number format), 21408 (rate limit exceeded), and 21611 (message content rejected). Monitor these codes through webhooks and maintain detailed error logs for troubleshooting.
Consult the San Marino Data Protection Authority website, Telecommunications Regulatory Authority, and available SMS compliance guidelines for detailed information on local regulations and best practices.
Sending SMS messages to San Marino (+378) requires understanding specific compliance requirements, phone number formats, and technical limitations. This comprehensive guide covers everything you need to know about SMS delivery to San Marino, including GDPR-aligned Law 171 compliance, alphanumeric sender IDs, message character limits, and API integration examples for Twilio, Sinch, Plivo, and MessageBird.
San Marino SMS Market Overview
Market Conditions: San Marino maintains modern telecommunications infrastructure despite its small population of approximately 33,600 (DataReportal, 2024). Mobile teledensity reached 121.8% in December 2022 (approximately 40,000 subscriptions), indicating most people use multiple devices. TIM (Telecom Italia Mobile) is the dominant carrier, providing 5G coverage to 99% of the territory as of December 2018.
Delivery Performance: Expect delivery rates above 95% to mobile numbers when you use properly formatted sender IDs and compliant content. Messages typically deliver in 3–10 seconds during normal network conditions.
Key SMS Features and Capabilities in San Marino
San Marino supports basic SMS functionality with limitations on advanced features. All services route through Italian carriers because San Marino lacks domestic telecommunication infrastructure.
Two-Way SMS Support
San Marino does not support two-way SMS according to current provider specifications. You cannot receive replies through standard A2P channels.
Workarounds for two-way communication:
Concatenated Messages (Segmented SMS)
Support: San Marino does not support concatenated messages.
Message length rules: Standard SMS character limits apply – 160 characters for GSM-7 encoding and 70 characters for Unicode (UCS-2).
Encoding considerations: Both GSM-7 and UCS-2 encodings are supported, though messages cannot be concatenated.
Character counting and truncation:
|,^,€,{,},[,],~,\\) count as 2 characters eachExample truncation detection:
function checkMessageTruncation(message) { const extendedChars = /[\|\^\€\{\}\[\]\~\\]/g; let length = message.length; const extendedCount = (message.match(extendedChars) || []).length; length += extendedCount; // Extended chars count as 2 const isUnicode = /[^\x00-\x7F]/.test(message); const limit = isUnicode ? 70 : 160; return { length, limit, willTruncate: length > limit, charactersOver: Math.max(0, length - limit) }; }MMS Support
MMS messages are automatically converted to SMS with an embedded URL link. Host multimedia content separately and link it within the message body.
Best practices for multimedia content hosting:
San Marino Phone Number Format (+378)
Number Portability
San Marino does not offer number portability. Mobile numbers remain tied to their original carriers.
Carrier identification: According to Wikipedia, San Marino phone numbers follow these patterns:
Sending SMS to Landlines
You cannot send SMS to landline numbers in San Marino. Attempts to send to landlines fail with a 400 response error (error code 21614) from messaging APIs. These messages won't appear in logs, and you won't be charged.
Landline detection validation:
function isSanMarinoMobile(phoneNumber) { // Remove country code and formatting const cleaned = phoneNumber.replace(/[\s\-\(\)]/g, ''); // Check if it starts with +378 6 (mobile) or 378 6 if (cleaned.match(/^\+?3786/)) { return true; } // Landlines start with 0, 8, or 9 if (cleaned.match(/^\+?378[089]/)) { return false; // Landline } return null; // Unknown/invalid }San Marino SMS Compliance and GDPR Regulations
San Marino follows Data Protection Law (Law No. 171 of 21 December 2018), which aligns closely with GDPR principles. The Authority for Personal Data Protection (Autorità Garante per la Protezione dei Dati Personali) oversees compliance. All SMS communications must adhere to these standards, particularly regarding personal data processing and storage.
Penalties for non-compliance: Following GDPR-aligned principles, penalties can reach up to €20 million or 4% of global annual turnover (whichever is higher) for serious violations including:
Data retention requirements:
Consent and Opt-In Requirements
Explicit Consent Requirements:
Consent refresh: Re-confirm consent every 24 months for marketing communications, or when you significantly change how you process data. Transactional messages do not require consent renewal if within the original scope.
HELP/STOP and Other Commands
Example message templates:
Italian HELP response:
English HELP response:
Italian STOP confirmation:
English STOP confirmation:
Implementation for keyword detection:
function processInboundSMS(messageBody, phoneNumber) { const normalized = messageBody.trim().toUpperCase(); const stopKeywords = ['STOP', 'ANNULLA', 'CANCEL', 'UNSUBSCRIBE']; const helpKeywords = ['HELP', 'AIUTO', 'INFO', 'INFORMATION']; if (stopKeywords.includes(normalized)) { return handleOptOut(phoneNumber); } else if (helpKeywords.includes(normalized)) { return sendHelpMessage(phoneNumber); } return null; // No keyword match }Do Not Call / Do Not Disturb Registries
San Marino doesn't maintain a centralized Do Not Call registry. However, you should:
Time Zone Sensitivity
San Marino follows Central European Time (CET/CEST):
San Marino Public Holidays (2025) (source):
Alphanumeric Sender ID and Phone Number Options
Alphanumeric Sender ID
Operator network capability: Supported with dynamic usage allowed
Registration requirements: No pre-registration required
Sender ID preservation: Sender IDs are generally preserved as sent
Character limits and requirements (industry standard):
Best practices for effective sender IDs:
Long Codes
Domestic vs. International:
Sender ID preservation: Original sender IDs are typically preserved
Provisioning time: 1–3 business days for international long codes
Use cases: Ideal for transactional messages and two-factor authentication
Cost considerations: International long codes typically cost $1–5/month per number plus per-message fees ($0.01–0.05 per SMS). Domestic options, when available, may have lower per-message costs but similar monthly fees.
Short Codes
Support: San Marino does not currently support short codes
Provisioning time: Not applicable
Use cases: Not available for marketing or authentication purposes
Short codes are unavailable in San Marino due to small market size and lack of local infrastructure. Italian carrier infrastructure does not extend short code support to San Marino numbers.
Restricted SMS Content, Industries, and Use Cases
Restricted Industries and Content:
Examples of violations:
Enforcement and penalties: Violations result in:
Content Filtering
Known Carrier Filters:
Best Practices to Avoid Filtering:
Excessive punctuation definition:
Message formatting comparison:
Well-formatted (not filtered):
Likely to be filtered:
Best Practices for Sending SMS in San Marino
Messaging Strategy
Effective CTAs in SMS:
Sending Frequency and Timing
Optimal bulk send spacing: For campaigns over 1,000 messages:
Localization
Common Italian SMS phrases:
Character encoding troubleshooting:
Opt-Out Management
Testing and Monitoring
Delivery rate benchmarks:
Key Performance Indicators (KPIs):
SMS API Integration Examples for San Marino
Twilio SMS API Integration
Twilio provides a REST API for sending SMS messages to San Marino. Store your account SID and auth token securely in environment variables for authentication.
import * as Twilio from 'twilio'; // Initialize Twilio client with your credentials const client = new Twilio( process.env.TWILIO_ACCOUNT_SID, // Your Account SID process.env.TWILIO_AUTH_TOKEN // Your Auth Token ); // Function to send SMS to San Marino with error handling and retry logic async function sendSMSToSanMarino( to: string, message: string, senderId: string, maxRetries: number = 3 ) { // Validate message length if (message.length > 160) { throw new Error('Message exceeds 160 characters and will be truncated in San Marino'); } // Validate phone number format if (!to.match(/^\+3786\d{7,8}$/)) { throw new Error('Invalid San Marino mobile number format. Expected: +378 6XXX XXXX'); } let attempt = 0; while (attempt < maxRetries) { try { const formattedNumber = to.startsWith('+378') ? to : `+378${to}`; const response = await client.messages.create({ body: message, from: senderId, to: formattedNumber, statusCallback: 'https://your-webhook.com/status' }); console.log(`Message sent successfully! SID: ${response.sid}`); return response; } catch (error: any) { attempt++; // Handle specific error codes if (error.code === 21614) { throw new Error('Invalid phone number format – likely landline'); } else if (error.code === 21408) { // Rate limit exceeded - exponential backoff const waitTime = Math.pow(2, attempt) * 1000; console.log(`Rate limited. Waiting ${waitTime}ms before retry ${attempt}/${maxRetries}`); await new Promise(resolve => setTimeout(resolve, waitTime)); } else if (error.code === 21611) { throw new Error('Message content rejected by carrier – check for restricted content'); } else if (attempt >= maxRetries) { console.error('Max retries reached:', error); throw error; } else { // Generic retry with exponential backoff const waitTime = Math.pow(2, attempt) * 1000; await new Promise(resolve => setTimeout(resolve, waitTime)); } } } }Sinch SMS API Integration
Sinch offers an API for SMS delivery to San Marino with delivery reports and batch sending.
import axios from 'axios'; class SinchSMSClient { private readonly apiToken: string; private readonly serviceId: string; private readonly baseUrl = 'https://sms.api.sinch.com/xms/v1'; constructor(apiToken: string, serviceId: string) { this.apiToken = apiToken; this.serviceId = serviceId; } async sendSMS(to: string, message: string, senderId: string) { try { const response = await axios.post( `${this.baseUrl}/${this.serviceId}/batches`, { from: senderId, to: [to], body: message }, { headers: { 'Authorization': `Bearer ${this.apiToken}`, 'Content-Type': 'application/json' } } ); return response.data; } catch (error: any) { if (error.response) { const status = error.response.status; const data = error.response.data; if (status === 400) { throw new Error(`Bad request: ${data.message || 'Invalid parameters'}`); } else if (status === 401) { throw new Error('Authentication failed – check API token'); } else if (status === 429) { throw new Error('Rate limit exceeded – implement retry with backoff'); } } console.error('Sinch SMS Error:', error); throw error; } } // Batch sending optimization async sendBatch(recipients: string[], message: string, senderId: string) { // Sinch allows up to 1000 recipients per batch const batchSize = 1000; const results = []; for (let i = 0; i < recipients.length; i += batchSize) { const batch = recipients.slice(i, i + batchSize); const result = await this.sendSMS(batch.join(','), message, senderId); results.push(result); // Rate limiting: wait 100ms between batches if (i + batchSize < recipients.length) { await new Promise(resolve => setTimeout(resolve, 100)); } } return results; } }MessageBird SMS API Integration
MessageBird provides an API for sending SMS to San Marino with delivery tracking.
import { MessageBird } from 'messagebird'; class MessageBirdClient { private client: MessageBird; constructor(apiKey: string) { this.client = new MessageBird(apiKey); } sendSMS(to: string, message: string, senderId: string): Promise<any> { // Validate inputs before sending if (!this.validatePhoneNumber(to)) { return Promise.reject(new Error('Invalid San Marino mobile number')); } if (message.length > 160) { return Promise.reject(new Error('Message too long – will be truncated')); } if (!this.validateSenderId(senderId)) { return Promise.reject(new Error('Invalid sender ID format')); } return new Promise((resolve, reject) => { this.client.messages.create({ originator: senderId, recipients: [to], body: message, reportUrl: 'https://your-webhook.com/delivery-reports' }, (err, response) => { if (err) { reject(err); } else { resolve(response); } }); }); } private validatePhoneNumber(phone: string): boolean { return /^\+3786\d{7,8}$/.test(phone); } private validateSenderId(senderId: string): boolean { // 3-11 characters, alphanumeric + space, must contain at least one letter return /^(?=.*[A-Za-z])[A-Za-z0-9 ]{3,11}$/.test(senderId); } }Plivo SMS API Integration
Plivo offers SMS delivery to San Marino with detailed delivery insights.
import * as plivo from 'plivo'; class PlivoSMSClient { private client: plivo.Client; constructor(authId: string, authToken: string) { this.client = new plivo.Client(authId, authToken); } async sendSMS(to: string, message: string, senderId: string) { // Parameter validation and sanitization const sanitizedMessage = this.sanitizeMessage(message); const validatedNumber = this.validateAndFormatNumber(to); if (!validatedNumber) { throw new Error('Invalid phone number format for San Marino'); } try { const response = await this.client.messages.create({ src: senderId, dst: validatedNumber, text: sanitizedMessage, url: 'https://your-webhook.com/status', method: 'POST' }); return response; } catch (error) { console.error('Plivo SMS Error:', error); throw error; } } private sanitizeMessage(message: string): string { // Remove null bytes and trim return message.replace(/\0/g, '').trim(); } private validateAndFormatNumber(phone: string): string | null { const cleaned = phone.replace(/[\s\-\(\)]/g, ''); // Check if valid San Marino mobile if (cleaned.match(/^\+3786\d{7,8}$/)) { return cleaned; } // Try to add country code if missing if (cleaned.match(/^6\d{7,8}$/)) { return '+378' + cleaned; } return null; } }API Rate Limits and Throughput
Provider-specific rate limits:
Rate limiting implementation example:
class RateLimiter { private queue: Array<() => Promise<any>> = []; private processing = false; private readonly messagesPerSecond: number; private readonly intervalMs: number; constructor(messagesPerSecond: number = 10) { this.messagesPerSecond = messagesPerSecond; this.intervalMs = 1000 / messagesPerSecond; } async add<T>(fn: () => Promise<T>): Promise<T> { return new Promise((resolve, reject) => { this.queue.push(async () => { try { const result = await fn(); resolve(result); } catch (error) { reject(error); } }); if (!this.processing) { this.process(); } }); } private async process() { this.processing = true; while (this.queue.length > 0) { const fn = this.queue.shift(); if (fn) { await fn(); await new Promise(resolve => setTimeout(resolve, this.intervalMs)); } } this.processing = false; } } // Usage const limiter = new RateLimiter(10); // 10 messages per second async function sendWithRateLimit(to: string, message: string) { return limiter.add(() => sendSMSToSanMarino(to, message, 'YourBrand')); }Error Handling and Reporting
Common error codes across providers:
Retry strategies by error type:
Troubleshooting Common SMS Issues in San Marino
Common Issues and Solutions
Issue: Messages not delivering
Issue: High bounce rate
Issue: Messages being filtered
Issue: Rate limiting errors
Key Takeaways
Essential SMS Best Practices for San Marino:
Next Steps
Implementation Checklist:
Additional Resources
Official Documentation:
Community and Support: