> ## Documentation Index
> Fetch the complete documentation index at: https://www.ayrshare.com/docs/llms.txt
> Use this file to discover all available pages before exploring further.

# Send Message

> Send a direct message to a recipient

export const XByoNotice = () => <Info>
  <strong>Targeting X/Twitter?</strong> Starting March 31, 2026, all X operations require your own API credentials. After linking X via OAuth, include these 2 headers in your request:
  <br /><br />
  <code>X-Twitter-OAuth1-Api-Key</code> — Your API Key (Consumer Key)<br />
  <code>X-Twitter-OAuth1-Api-Secret</code> — Your API Key Secret (Consumer Secret)
  <br /><br />
  Not linked yet? See the <a href="/dashboard/connect-social-accounts/x-twitter-byo-keys">full setup guide</a> to connect your X account.
  <br /><br />
  Your keys are never logged or stored by Ayrshare.
</Info>;

export const PlansAvailable = ({plans = [], maxPackRequired}) => {
  let displayPlans = plans;
  if (plans && plans.length === 1) {
    const lowerCasePlan = plans[0].toLowerCase();
    if (lowerCasePlan === "basic") {
      displayPlans = ["Basic", "Premium", "Business", "Enterprise"];
    } else if (lowerCasePlan === "business") {
      displayPlans = ["Business", "Enterprise"];
    } else if (lowerCasePlan === "premium") {
      displayPlans = ["Premium", "Business", "Enterprise"];
    }
  }
  return <Note>
Available on {displayPlans.length === 1 ? "the " : ""}
{displayPlans.join(", ").replace(/\b\w/g, l => l.toUpperCase())}{" "}
{displayPlans.length > 1 ? "plans" : "plan"}.

{maxPackRequired && <span onClick={() => window.open('https://www.ayrshare.com/docs/additional/maxpack', '_self')} className="flex items-center mt-2 cursor-pointer">
 <span className="px-1.5 py-0.5 rounded text-sm" style={{
    backgroundColor: '#C264B6',
    color: 'white',
    fontSize: '12px'
  }}>
   Max Pack required
 </span>
</span>}
</Note>;
};

export const HeaderAPI = ({noProfileKey, profileKeyRequired}) => <>
    <ParamField header="Authorization" type="string" required>
      <a href="/apis/overview#authorization">API Key</a> of the Primary Profile.
      <br />
      <br />
      Format: <code>Authorization: Bearer API_KEY</code>
    </ParamField>
    {!noProfileKey && (profileKeyRequired ? <ParamField header="Profile-Key" type="string" required>
          <a href="/apis/overview#profile-key-format">Profile Key</a> of a User Profile.
          <br />
          <br />
          Format: <code>Profile-Key: PROFILE_KEY</code>
        </ParamField> : <ParamField header="Profile-Key" type="string">
          <a href="/apis/overview#profile-key-format">Profile Key</a> of a User Profile.
          <br />
          <br />
          Format: <code>Profile-Key: PROFILE_KEY</code>
        </ParamField>)}
  </>;

<PlansAvailable plans={["business"]} maxPackRequired={false} />

<XByoNotice />

Send a new direct message to a recipient.

<ul class="custom-bullets">
  <li>You can send an emoji as part of the `message` text.</li>

  <li>
    Facebook and Instagram `mediaUrls` must end in a known extension. Including query parameters
    will cause the media url to fail.
  </li>
</ul>

## Header Parameters

<HeaderAPI />

## Path Parameters

<ParamField path="platform" type="string" required>
  The platform to send the message: `facebook`, `instagram`, `twitter`
</ParamField>

## Body Parameters

<ParamField body="recipientId" type="string" required>
  The ID of the message recipient.
</ParamField>

<ParamField body="message" type="string" required>
  The message to send to the recipient.

  <ul class="custom-bullets">
    <li>
      Facebook and Instagram message may be an empty string or not included if a `mediaUrls` is provided.
    </li>

    <li>
      X requires a message of at least one character even if a `mediaUrls` is provided.
    </li>
  </ul>
</ParamField>

<ParamField body="mediaUrls" type="array">
  Array of media URLS for attaching images, a video, or a voice message.

  <ul class="custom-bullets">
    <li>
      URLs of media items should end in the file extension without additional parameters appended.
    </li>

    <li>Facebook and Instagram support multiple media URLs.</li>
    <li>X only accepts a single media URL.</li>
    <li>Voice messages are supported on Facebook and Instagram as an `aac` or `wav` file.</li>
  </ul>
</ParamField>

<RequestExample>
  ```bash cURL theme={"system"}
  curl \
  -H "Authorization: Bearer API_KEY" \
  -H 'Content-Type: application/json' \
  -d '{"message": "What's up!", "recipientId": "283j839222"} \
  -X POST https://api.ayrshare.com/api/messages/instagram
  ```

  ```javascript JavaScript theme={"system"}
  const apiKey = 'API_KEY';
  const url = 'https://api.ayrshare.com/api/messages/instagram';

  const data = {
    message: "What's up!",
    recipientId: '283j839222',
  };

  const headers = {
    'Authorization': `Bearer ${apiKey}`,
    'Content-Type': 'application/json',
  };

  fetch(url, {
    method: 'POST',
    headers: headers,
    body: JSON.stringify(data),
  })
    .then(response => response.json())
    .then(data => {
      console.log('Response:', data);
    })
    .catch(error => {
      console.error('Error:', error);
    });
  ```

  ```python Python theme={"system"}
  import requests

  api_key = 'API_KEY'
  url = 'https://api.ayrshare.com/api/messages/instagram'

  data = {
      'message': "What's up!",
      'recipientId': '283j839222',
  }

  headers = {
      'Authorization': f'Bearer {api_key}',
      'Content-Type': 'application/json',
  }

  response = requests.post(url, json=data, headers=headers)
  print('Response:', response.json())
  ```

  ```php PHP theme={"system"}
  <?php

  $apiKey = 'API_KEY';
  $url = 'https://api.ayrshare.com/api/messages/instagram';

  $data = [
      'message' => "What's up!",
      'recipientId' => '283j839222',
  ];

  $headers = [
      'Authorization: Bearer ' . $apiKey,
      'Content-Type: application/json',
  ];

  $ch = curl_init($url);
  curl_setopt($ch, CURLOPT_POST, true);
  curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));
  curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
  curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

  $response = curl_exec($ch);

  if ($response === false) {
      $error = curl_error($ch);
      echo 'Error: ' . $error;
  } else {
      $responseData = json_decode($response, true);
      print_r($responseData);
  }

  curl_close($ch);

  ?>
  ```

  ```csharp C# theme={"system"}
  using System;
  using System.Net.Http;
  using System.Net.Http.Headers;
  using System.Text;
  using System.Text.Json;
  using System.Threading.Tasks;

  class Program
  {
      static async Task Main()
      {
          string apiKey = "API_KEY";
          string url = "https://api.ayrshare.com/api/messages/instagram";

          var data = new
          {
              message = "What's up!",
              recipientId = "283j839222"
          };

          var jsonData = JsonSerializer.Serialize(data);

          using var client = new HttpClient();
          client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", apiKey);
          client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

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

          try
          {
              var response = await client.PostAsync(url, content);
              response.EnsureSuccessStatusCode();

              var responseBody = await response.Content.ReadAsStringAsync();
              var responseData = JsonSerializer.Deserialize<dynamic>(responseBody);

              Console.WriteLine("Response:");
              Console.WriteLine(responseData);
          }
          catch (HttpRequestException ex)
          {
              Console.WriteLine($"Error: {ex.Message}");
          }
      }
  }
  ```

  ```java Java theme={"system"}
  import java.io.IOException;
  import java.net.URI;
  import java.net.http.HttpClient;
  import java.net.http.HttpRequest;
  import java.net.http.HttpResponse;

  public class Main {
      public static void main(String[] args) {
          String apiKey = "API_KEY";
          String url = "https://api.ayrshare.com/api/messages/instagram";

          String data = "{\"message\": \"What's up!\", \"recipientId\": \"283j839222\"}";

          HttpClient client = HttpClient.newHttpClient();
          HttpRequest request = HttpRequest.newBuilder()
                  .uri(URI.create(url))
                  .header("Authorization", "Bearer " + apiKey)
                  .header("Content-Type", "application/json")
                  .POST(HttpRequest.BodyPublishers.ofString(data))
                  .build();

          try {
              HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString());

              if (response.statusCode() == 200) {
                  String responseBody = response.body();
                  System.out.println("Response:");
                  System.out.println(responseBody);
              } else {
                  System.out.println("Request failed. Status code: " + response.statusCode());
              }
          } catch (IOException | InterruptedException e) {
              System.out.println("Error: " + e.getMessage());
          }
      }
  }
  ```
</RequestExample>

<ResponseExample>
  ```json 200: Success theme={"system"}
  { // single text message
      "status": "success",
      "recipientId": "72706337063589124",
      "messageId": "aWdfZAG1faXRlbToxOkl",
      "message": "What is up?"
  }
  ```

  ```json 400: Error theme={"system"}
  {
    // single text message
    "action": "messages",
    "status": "error",
    "code": 363,
    "message": "The recipient ID was not found. Please confirm the recipient ID is correct."
  }
  ```

  ```json 200: Media Urls theme={"system"}
  {
    // single image
    "status": "success",
    "recipientId": "761943",
    "messageId": "m_EgvfBrgjaM",
    "type": "image",
    "mediaUrl": "https://img.ayrshare.com/012/gb.jpg"
  }
  ```

  ```json 400: Media Urls theme={"system"}
  {
    // text and image message
    "action": "send",
    "status": "error",
    "code": 337,
    "message": "Error sending message.",
    "messages": [
      {
        "recipientId": "727063370635",
        "messageId": "aWdfZAG1faXRlbT",
        "message": "What a great day"
      },
      {
        "action": "messages",
        "status": "error",
        "code": 365,
        "message": "An error occurred sending the message attachment. Please verify the attachment is still available and try again."
      }
    ]
  }
  ```
</ResponseExample>
