# Send by Long Number

## URL

<mark style="color:green;">`POST`</mark> `https://api.smspartner.fr/v1/vn/send`

{% hint style="warning" %}
The platform does not send marketing SMS between **8 PM and 8 AM on weekdays, as well as on Sundays and public holidays** (legal restriction). If a message is sent during that time, it will be **on hold until the next working day at 8 AM**.\
Not sending marketing SMS? Contact us to disable this restriction: <help@smspartner.fr>
{% endhint %}

#### **Required Parameters**

| Name      | Value                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                |
| --------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `apiKey`  | [Your API key](https://my.smspartner.fr/dashboard/api)                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                               |
| `to`      | <p>Recipient's phone number.</p><ul><li>In national format (06xxxxxxxx) or international (+336xxxxxxxx) for French numbers</li><li>In international format (+496xxxxxxxx) for non-French numbers</li></ul>                                                                                                                                                                                                                                                                                                                                                                                                           |
| `from`    | Your virtual number in international format (e.g., 336xxxxxxxx)                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                      |
| `message` | <p>SMS content. <strong>160 characters</strong> max per SMS (beyond that, an additional SMS will be charged per 153-character segment).</p><p>Line break → :br: <strong>Note: line break counts as two characters.</strong></p><p>€ symbol → :euro:</p><div data-gb-custom-block data-tag="hint" data-style="danger" class="hint hint-danger"><p>The character ” must be escaped (\”) for the SMS to be valid. Otherwise, a 400 error will be returned.</p><p>Some <a data-mention href="/pages/mYV3b7pJz8NOy0a5FBaU">/pages/mYV3b7pJz8NOy0a5FBaU</a> will be replaced during sending. Please review them.</p></div> |

#### **Optional Parameters**

| Name          | Value                                                                                                                                                                                                                                                                    |
| ------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| `tag`         | String (max 20 characters, no spaces, lowercase only)                                                                                                                                                                                                                    |
| `urlResponse` | URL to receive SMS replies (e.g., <http://www.myresponseurl.com>)                                                                                                                                                                                                        |
| `urlDlr`      | URL to receive delivery reports (e.g., <http://www.mydlrurl.com>)                                                                                                                                                                                                        |
| `isStopSms`   | `1` to add the STOP mention at the end of the SMS (mandatory and automatic for marketing SMS)                                                                                                                                                                            |
| `sandbox`     | <p><code>1</code> to enable Sandbox Mode</p><div data-gb-custom-block data-tag="hint" data-style="info" class="hint hint-info"><p>No SMS will be sent and no credit will be charged. These SMS will be automatically removed from your sending logs every day.</p></div> |
| `_format`     | `json` or `xml`                                                                                                                                                                                                                                                          |

#### Requests

{% tabs %}
{% tab title="PHP" %}

```php
<?php
        // Prepare data for POST request
        $fields = array(
            'apiKey'=> 'YOUR API KEY',
            'to'=> '336xxxxxxxx',
            'from' => '336xxxxxxxx',
            'message'=> 'This is your message'
        );
 
 
        $curl = curl_init();
        curl_setopt($curl, CURLOPT_URL,'https://api.smspartner.fr/v1/vn/send');
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($curl, CURLOPT_TIMEOUT, 10);
        curl_setopt($curl, CURLOPT_POST, 1);
        curl_setopt($curl, CURLOPT_POSTFIELDS,json_encode($fields));
 
        $result = curl_exec($curl);
        curl_close($curl);
 
        // Process your response here
        echo $result;
?>
```

{% endtab %}

{% tab title="VB.net" %}

```vbnet
Imports System.IO
Imports System.Net
 
Module Module1
 
  Sub Main()
 
    Dim base_url As String = "http://api.smspartner.fr/v1/"
    Dim apiKey As String = "VOTRE_APIKEY"
 
    #send sms
    url = base_url & "vn/send"
    #note : utiliser une librairie JSON en production, par exemple :
    #https//www.nuget.org/packages/Newtonsoft.Json/
    Dim parameters As String = String.Format(
        "{{""apiKey"":""{0}"",""to"":""{1}"",""from"":""{2}"",""message"":""{3}""}}",
        apiKey,
        "336xxxxxxxx",
        "336xxxxxxxx",
        "message de test")
    Console.Write(parameters)
    apiRequest("POST", url, parameters)
 
  End Sub
 
  Function apiRequest(method As String, url As String, parameters As String) As String
 
    Dim request As HttpWebRequest
    request = WebRequest.Create(url)
    request.Method = method
    request.Timeout = 10000   # timeout in ms
    request.ContentType = "application/json; charset=utf-8"
    request.ContentLength = 0
 
    #set POST data
    If Not String.IsNullOrEmpty(parameters) Then
      request.ContentLength = parameters.Length
      Using reqStream As StreamWriter = New StreamWriter(request.GetRequestStream())
        reqStream.Write(parameters)
      End Using
    End If
 
    #get response
    Dim returnValue As String = Nothing
    Using response As HttpWebResponse = request.GetResponse()
      If response.StatusCode = HttpStatusCode.OK Then
        Using resStream = response.GetResponseStream()
          If resStream IsNot Nothing Then
            Using reader As New StreamReader(resStream)
              returnValue = reader.ReadToEnd()
            End Using
          End If
        End Using
      End If
    End Using
    apiRequest = returnValue
 
  End Function
 
End Module
```

{% endtab %}

{% tab title="Python" %}

```python
# std
import logging
import json
from collections import OrderedDict
 
# 3p
import requests
 
API_KEY = "MY API KEY"
URL = "https://api.smspartner.fr/v1"
 
class SMSPartner():
    def send_sms(self, to, from, msg):
		print(to)
 
		data = OrderedDict([
			("apiKey", API_KEY),
			("to", to),
			("from",from),
			("message", msg)
		])
 
		url = URL + "/vn/send"
		r = requests.post(url, data=json.dumps(data), verify=False)
 
		r_json = r.json()
		if r_json.get("success") == True:
			print(r_json)
			status = True
		else:
			print("SMS msg {} not delivered to {}".format(msg, to))
			status = False
		return status
```

{% endtab %}

{% tab title="cURL" %}

```
curl -H  "Content-Type: application/json" -X POST -d '{"apiKey":"xxxxx","to":"xxxx","from":"xxx","message":"test"}' https://api.smspartner.fr/v1/vn/send
```

{% endtab %}

{% tab title="Nodejs" %}

```javascript
const https = require("https");

// Remplacez par votre clé API
const apiKey = "VOTRE_CLÉ_API";

// Préparer les données pour la requête POST
const data = JSON.stringify({
  apiKey: apiKey,
  to: "336xxxxxxxx",
  from: "336xxxxxxxx",
  message: "Ceci est votre message",
});

// Définir les options pour la requête HTTP POST vers l'API SMS Partner
const options = {
  hostname: "api.smspartner.fr",
  port: 443,
  path: "/v1/vn/send",
  method: "POST",
  headers: {
    "Content-Type": "application/json",
    "Content-Length": data.length,
    "cache-control": "no-cache",
  },
};

// Effectuer la requête HTTP POST avec les options et données définies précédemment
const req = https.request(options, (res) => {
  console.log(`statusCode: ${res.statusCode}`);

  // Afficher les données de réponse de l'API sur la sortie standard
  res.on("data", (d) => {
    process.stdout.write(d);
  });
});

// Afficher en cas d'erreur lors de l'exécution de la requête HTTP POST
req.on("error", (error) => {
  console.error(error);
});

// Envoyer les données de l'objet 'data' à la demande
req.write(data);
// Terminer la demande HTTP POST
req.end();
```

{% endtab %}

{% tab title="JAVA" %}

```java
import java.net.HttpURLConnection;
import java.net.URL;
import java.io.OutputStream;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.stream.Collectors;
import org.json.JSONObject;

public class EnvoyerSMSLong {
    public static void main(String[] args) {
        try {
            // Remplacez par votre clé API
            String apiKey = "VOTRE_CLÉ_API";

            // Création de l'objet URL avec l'adresse de l'API SMS
            URL url = new URL("https://api.smspartner.fr/v1/vn/send");

            // Ouverture de la connexion HTTP avec l'API
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setRequestMethod("POST");
            conn.setRequestProperty("Content-Type", "application/json");
            conn.setRequestProperty("cache-control", "no-cache");
            conn.setDoOutput(true);

            // Création de l'objet JSON contenant les paramètres du SMS à envoyer
            JSONObject json = new JSONObject();
            json.put("apiKey", apiKey);
            json.put("to", "336xxxxxxxx");
            json.put("from", "336xxxxxxxx");
            json.put("message", "Ceci est votre message");

            // Écriture des données JSON dans le corps de la requête HTTP
            OutputStream os = conn.getOutputStream();
            os.write(json.toString().getBytes());
            os.flush();

            // Lecture de la réponse de l'API
            BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream()));
            String response = br.lines().collect(Collectors.joining());
            System.out.println(response);

            // Fermeture de la connexion HTTP
            conn.disconnect();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
```

{% endtab %}

{% tab title="Swift" %}

```swift
import SwiftUI
import Foundation

// Struct pour la vue "EnvoieSMSParNumeroLong"
struct EnvoieSMSParNumeroLong: View {
    var body: some View {
        NavigationView {
            VStack {
                // Un bouton qui appelle la fonction EnvoieSMSParNumeroLong() lorsqu'il est pressé
                Button(action: {
                    EnvoieSMSParNumeroLong()
                }) {
                    Text("Envoyer SMS")
                        .font(.system(size: 20))
                        .foregroundColor(.white)
                        .frame(minWidth: 0, maxWidth: .infinity)
                        .padding()
                        .background(LinearGradient(gradient: Gradient(colors: [Color.blue, Color.blue.opacity(0.8)]), startPoint: .top, endPoint: .bottom))
                        .cornerRadius(10)
                        .padding(.horizontal)
                }
            }
        }
    }
    
    // Fonction pour envoyer un SMS par numéro long
    func EnvoieSMSParNumeroLong() {
        let apiKey = "XXXXXXXXXXXX YOUR API KEY XXXXXXXXXXXXX" // Votre clé API
        let destinataire = "33XXXXXXXXX" // Le numéro du destinataire
        let expediteur = "33XXXXXXXXX" // Votre numéro
        let message = "status" // Le message à envoyer

        let url = URL(string: "https://api.smspartner.fr/v1/vn/send")! // URL pour envoyer le SMS
        var requete = URLRequest(url: url)
        requete.httpMethod = "POST"
        requete.addValue("application/json", forHTTPHeaderField: "Content-Type") // Ajout du type de contenu dans l'en-tête de la requête

        // Paramètres pour l'envoi du SMS
        let params: [String: Any] = [
            "apiKey": apiKey,
            "to": destinataire,
            "from": expediteur,
            "message": message
        ]
        
        // Ajout des paramètres dans le corps de la requête
        requete.httpBody = try? JSONSerialization.data(withJSONObject: params)
        
        let session = URLSession.shared
        // Tâche pour envoyer la requête
        let task = session.dataTask(with: requete) { (data, response, error) in
            // Si une erreur survient, on l'affiche
            if let erreur = error {
                print("Erreur : \(erreur.localizedDescription)")
                return
            }
            
            // Sinon, on affiche les données reçues
            if let donnees = data {
                if let resultat = String(data: donnees, encoding: .utf8) {
                    print(resultat) // Impression du résultat
                }
            }
        }
        
        task.resume() // On lance la tâche
    }
}
```

{% endtab %}

{% tab title="Go" %}

```go
package main

import (
	"bytes"
	"fmt"
	"net/http"
)

func main() {
	apiKey := "YOUR API KEY"
	to := "336xxxxxxxx"
	from := "336xxxxxxxx"
	message := "This is your message"

	// Construire les données JSON pour la requête POST
	data := map[string]interface{}{
		"apiKey":  apiKey,
		"to":      to,
		"from":    from,
		"message": message,
	}

	// Convertir les données en JSON
	jsonData, err := json.Marshal(data)
	if err != nil {
		fmt.Println("Erreur lors de la conversion en JSON:", err)
		return
	}

	// Effectuer la requête POST
	url := "https://api.smspartner.fr/v1/vn/send"
	resp, err := http.Post(url, "application/json", bytes.NewBuffer(jsonData))
	if err != nil {
		fmt.Println("Erreur lors de l'envoi de la requête:", err)
		return
	}
	defer resp.Body.Close()

	// Traiter la réponse
	if resp.StatusCode == http.StatusOK {
		body := new(bytes.Buffer)
		_, err := body.ReadFrom(resp.Body)
		if err != nil {
			fmt.Println("Erreur lors de la lecture de la réponse:", err)
			return
		}
		fmt.Println(body.String())
	} else {
		fmt.Println("La requête POST a échoué. Code de réponse:", resp.StatusCode)
	}
}
```

{% endtab %}

{% tab title="C#" %}

```csharp
using System;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
using Newtonsoft.Json;

class Program
{
    private static readonly HttpClient client = new HttpClient();

    static async Task Main(string[] args)
    {
        var request = new
        {
            apiKey = "YOUR_API_KEY",
            to = "336xxxxxxxx",
            from = "336xxxxxxxx",
            message = "This is your message"
        };

        var content = new StringContent(
            JsonConvert.SerializeObject(request),
            Encoding.UTF8,
            "application/json");

        HttpResponseMessage response = await client.PostAsync("https://api.smspartner.fr/v1/vn/send", content);

        if (response.IsSuccessStatusCode)
        {
            var result = await response.Content.ReadAsStringAsync();
            Console.WriteLine(result);
        }
        else
        {
            Console.WriteLine("POST request failed with status code: " + response.StatusCode);
        }
    }
}
```

{% endtab %}
{% endtabs %}

#### Response

{% tabs %}
{% tab title="json" %}

```json
{
   "success":true,
   "code":200,
   "message_id":xxx,
   "nb_sms": 1,
   "cost": xxx,
   "currency": "EUR"
}
```

{% endtab %}

{% tab title="xml" %}

```xml
<?xml version='1.0' encoding='UTF-8'?>
<result>
  <entry>true</entry>
  <entry>200</entry>
  <entry>xxx</entry>
  <entry>1</entry>
  <entry>xxx</entry>
  <entry>
        <![CDATA[EUR]]>
  </entry>
</result>
```

{% endtab %}
{% endtabs %}


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://www.docpartner.dev/en/api/sms-partner/send-sms/send-by-long-number.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
