# Get Contacts by Emails

## Operation overview

```json
{"path":"https://api.sendgrid.com/v3/marketing/contacts/search/emails","method":"post","servers":[{"url":"https://api.sendgrid.com","description":"The Twilio SendGrid v3 API"}]}
```

**This endpoint allows you to retrieve up to 100 contacts matching the searched `email` address(es), including any `alternate_emails`.**

Email addresses are unique to a contact, meaning this endpoint can treat an email address as a primary key to search by. The contact object associated with the address, whether it is their `email` or one of their `alternate_emails` will be returned if matched.

Email addresses in the search request do not need to match the case in which they're stored, but the email addresses in the result will be all lower case. Empty strings are excluded from the search and will not be returned.

This endpoint should be used in place of the "Search Contacts" endpoint when you can provide exact email addresses and do not need to include other [Segmentation Query Language (SGQL)](/docs/sendgrid/for-developers/sending-email/segmentation-query-language/) filters when searching.

If you need to access a large percentage of your contacts, we recommend exporting your contacts with the "Export Contacts" endpoint and filtering the client side results.

This endpoint returns a `200` status code when any contacts match the address(es) you supplied. When searching multiple addresses in a single request, it is possible that some addresses will match a contact while others will not. When a partially successful search like this is made, the matching contacts are returned in an object and an error message is returned for the email address(es) that are not found.

This endpoint returns a `404` status code when no contacts are found for the provided email address(es).

A `400` status code is returned if any searched addresses are invalid.

Twilio SendGrid recommends exporting your contacts regularly as a backup to avoid issues or lost data.

## Operation details

### Authentication

API Key

### Headers

```json
[{"in":"header","name":"Authorization","required":true,"default":"Bearer <<YOUR_API_KEY_HERE>>","schema":{"type":"string"}}]
```

### Request body

```json
{"schema":{"type":"object","description":"","required":["emails"],"example":{"emails":["jane_doe@example.com","john_doe@example.com","joann_doe@example.com"]},"properties":{"emails":{"type":"array","description":"One or more primary and/or alternate email addresses to search for in your Marketing Campaigns contacts.","items":{"type":"string","maxLength":100}},"phone_number_id":{"type":"string","description":"The contact's Phone Number ID. This is required to be a valid phone number."},"external_id":{"type":"string","description":"The contact's External ID.","maxLength":254},"anonymous_id":{"type":"string","description":"The contact's Anonymous ID.","maxLength":254}}},"encodingType":"application/json"}
```

### Responses

```json
[{"responseCode":"200","schema":{"description":"","content":{"application/json":{"schema":{"type":"object","description":"An object containing one or more of the email addresses matching the searched addresses in your contacts.","example":{"result":{"jane_doe@example.com":{"contact":{"address_line_1":"","address_line_2":"","alternate_emails":["janedoe@example1.com"],"city":"","country":"","email":"jane_doe@example.com","first_name":"Jane","id":"asdf-Jkl-zxCvBNm","last_name":"Doe","list_ids":[],"segment_ids":[],"postal_code":"","state_province_region":"","phone_number":"","whatsapp":"","line":"","facebook":"","unique_name":"","custom_fields":{},"created_at":"2021-03-02T15:25:47Z","updated_at":"2021-03-30T15:26:16Z","_metadata":{"self":"<metadata_url>"}}},"john_doe@example.com":{"contact":{"address_line_1":"","address_line_2":"","alternate_emails":[],"city":"","country":"","email":"john_doe@example.com","first_name":"Jane","id":"asdf-Jkl-qWeRTy","last_name":"Doe","list_ids":[],"segment_ids":[],"postal_code":"","state_province_region":"","phone_number":"","whatsapp":"","line":"","facebook":"","unique_name":"","custom_fields":{},"created_at":"2020-01-02T15:25:47Z","updated_at":"2020-12-20T15:26:16Z","_metadata":{"self":"<metadata_url>"}}},"joann_doe@example.com":{"error":"contact not found"}}},"properties":{"result":{"type":"object","patternProperties":{"^[A-Za-z0-9\\._%\\+-]+@[A-Za-z0-9\\.-]+\\.[A-Za-z]{2,6}$":{"type":"object","description":"An email address matching a searched address in your contacts that conforms to the above regex string.","properties":{"contact":{"title":"contact-details3","type":"object","required":["id","list_ids","segment_ids","created_at","updated_at"],"refName":"ContactDetails3","modelName":"ContactDetails3","properties":{"id":{"type":"string"},"first_name":{"type":"string"},"last_name":{"type":"string"},"unique_name":{"type":"string"},"email":{"type":"string"},"phone_number_id":{"type":"string"},"external_id":{"type":"string"},"anonymous_id":{"type":"string"},"alternate_emails":{"type":"array","items":{"type":"string"}},"address_line_1":{"type":"string"},"address_line_2":{"type":"string"},"city":{"type":"string"},"state_province_region":{"type":"string"},"country":{"type":"string"},"postal_code":{"type":"string"},"phone_number":{"type":"string"},"whatsapp":{"type":"string"},"line":{"type":"string"},"facebook":{"type":"string"},"list_ids":{"type":"array","items":{"type":"string"}},"segment_ids":{"type":"array","items":{"type":"string"}},"custom_fields":{"type":"object"},"created_at":{"type":"string"},"updated_at":{"type":"string"},"_metadata":{"title":"selfMetadata","type":"object","refName":"SelfMetadata","modelName":"SelfMetadata","properties":{"self":{"type":"string","description":"A link to this object."}}}}},"error":{"type":"string"}}}}}}},"examples":{"response":{"value":{"result":{"jane_doe@example.com":{"contact":{"address_line_1":"","address_line_2":"","alternate_emails":["janedoe@example1.com"],"city":"","country":"","email":"jane_doe@example.com","first_name":"Jane","id":"asdf-Jkl-zxCvBNm","last_name":"Doe","list_ids":[],"segment_ids":[],"postal_code":"","state_province_region":"","phone_number":"","whatsapp":"","line":"","facebook":"","unique_name":"","custom_fields":{},"created_at":"2021-03-02T15:25:47Z","updated_at":"2021-03-30T15:26:16Z","_metadata":{"self":"<metadata_url>"}}},"john_doe@example.com":{"contact":{"address_line_1":"","address_line_2":"","alternate_emails":[],"city":"","country":"","email":"john_doe@example.com","first_name":"Jane","id":"asdf-Jkl-qWeRTy","last_name":"Doe","list_ids":[],"segment_ids":[],"postal_code":"","state_province_region":"","phone_number":"","whatsapp":"","line":"","facebook":"","unique_name":"","custom_fields":{},"created_at":"2020-01-02T15:25:47Z","updated_at":"2020-12-20T15:26:16Z","_metadata":{"self":"<metadata_url>"}}},"joann_doe@example.com":{"error":"contact not found"}}}}}}}}},{"responseCode":"400","schema":{"description":"","content":{"application/json":{"schema":{"type":"object","example":{"errors":[{"field":"field_name","message":"error message"}]},"refName":"ErrorResponse","modelName":"ErrorResponse","properties":{"errors":{"type":"array","items":{"type":"object","properties":{"message":{"type":"string","description":"An error message."},"field":{"description":"When applicable, this property value will be the field that generated the error.","nullable":true,"type":"string"},"help":{"type":"object","description":"When applicable, this property value will be helper text or a link to documentation to help you troubleshoot the error."}}}},"id":{"type":"string","description":"When applicable, this property value will be an error ID."}}}}}}},{"responseCode":"401","schema":{"description":"","content":{"application/json":{"schema":{"type":"object","example":{"errors":[{"field":"field_name","message":"error message"}]},"refName":"ErrorResponse","modelName":"ErrorResponse","properties":{"errors":{"type":"array","items":{"type":"object","properties":{"message":{"type":"string","description":"An error message."},"field":{"description":"When applicable, this property value will be the field that generated the error.","nullable":true,"type":"string"},"help":{"type":"object","description":"When applicable, this property value will be helper text or a link to documentation to help you troubleshoot the error."}}}},"id":{"type":"string","description":"When applicable, this property value will be an error ID."}}}}},"refName":"#/components/responses/MarketingContacts401","modelName":"__components_responses_MarketingContacts401"}},{"responseCode":"403","schema":{"description":"","content":{"application/json":{"schema":{"type":"object","example":{"errors":[{"field":"field_name","message":"error message"}]},"refName":"ErrorResponse","modelName":"ErrorResponse","properties":{"errors":{"type":"array","items":{"type":"object","properties":{"message":{"type":"string","description":"An error message."},"field":{"description":"When applicable, this property value will be the field that generated the error.","nullable":true,"type":"string"},"help":{"type":"object","description":"When applicable, this property value will be helper text or a link to documentation to help you troubleshoot the error."}}}},"id":{"type":"string","description":"When applicable, this property value will be an error ID."}}}}},"refName":"#/components/responses/MarketingContacts403","modelName":"__components_responses_MarketingContacts403"}},{"responseCode":"404","schema":{"description":"","content":{"application/json":{"schema":{"type":"object","example":{"errors":[{"field":"field_name","message":"error message"}]},"refName":"ErrorResponse","modelName":"ErrorResponse","properties":{"errors":{"type":"array","items":{"type":"object","properties":{"message":{"type":"string","description":"An error message."},"field":{"description":"When applicable, this property value will be the field that generated the error.","nullable":true,"type":"string"},"help":{"type":"object","description":"When applicable, this property value will be helper text or a link to documentation to help you troubleshoot the error."}}}},"id":{"type":"string","description":"When applicable, this property value will be an error ID."}}}}}}},{"responseCode":"500","schema":{"description":"","content":{"application/json":{"schema":{"type":"object","properties":{"errors":{"type":"array","items":{"type":"object","properties":{"message":{"type":"string"}}}}}}}}}}]
```

Get Contacts by Emails

```js
const client = require("@sendgrid/client");
client.setApiKey(process.env.SENDGRID_API_KEY);

const data = {
  emails: [
    "jane_doe@example.com",
    "john_doe@example.com",
    "joann_doe@example.com",
  ],
};

const request = {
  url: `/v3/marketing/contacts/search/emails`,
  method: "POST",
  body: data,
};

client
  .request(request)
  .then(([response, body]) => {
    console.log(response.statusCode);
    console.log(response.body);
  })
  .catch((error) => {
    console.error(error);
  });
```

```python
import os
from sendgrid import SendGridAPIClient


sg = SendGridAPIClient(os.environ.get("SENDGRID_API_KEY"))

data = {
    "emails": [
        "jane_doe@example.com",
        "john_doe@example.com",
        "joann_doe@example.com",
    ]
}

response = sg.client.marketing.contacts.search.emails.post(request_body=data)

print(response.status_code)
print(response.body)
print(response.headers)
```

```csharp
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using SendGrid;

public class Program {
    public static async Task Main() {
        string apiKey = Environment.GetEnvironmentVariable("SENDGRID_API_KEY");
        var client = new SendGridClient(apiKey);

        var data =
            @"{
            ""emails"": [
                ""jane_doe@example.com"",
                ""john_doe@example.com"",
                ""joann_doe@example.com""
            ]
        }";

        var response = await client.RequestAsync(
            method: SendGridClient.Method.POST,
            urlPath: "marketing/contacts/search/emails",
            requestBody: data);

        Console.WriteLine(response.StatusCode);
        Console.WriteLine(response.Body.ReadAsStringAsync().Result);
        Console.WriteLine(response.Headers.ToString());
    }
}
```

```java
import com.sendgrid.*;
import java.io.IOException;
import org.json.JSONObject;
import java.util.HashMap;
import java.util.Arrays;

public class Example {
    public static void main(String[] args) throws IOException {
        try {
            SendGrid sg = new SendGrid(System.getenv("SENDGRID_API_KEY"));
            Request request = new Request();
            request.setMethod(Method.POST);
            request.setEndpoint("/marketing/contacts/search/emails");
            request.setBody(new JSONObject(new HashMap<String, Object>() {
                {
                    put("emails",
                        Arrays.asList("jane_doe@example.com", "john_doe@example.com", "joann_doe@example.com"));
                }
            }).toString());
            Response response = sg.api(request);
            System.out.println(response.getStatusCode());
            System.out.println(response.getBody());
            System.out.println(response.getHeaders());
        } catch (IOException ex) {
            throw ex;
        }
    }
}
```

```go
package main

import (
	"fmt"
	"github.com/sendgrid/sendgrid-go"
	"os"
)

func main() {
	apiKey := os.Getenv("SENDGRID_API_KEY")
	host := "https://api.sendgrid.com"
	request := sendgrid.GetRequest(apiKey, "/v3/marketing/contacts/search/emails", host)
	request.Method = "POST"
	request.Body = []byte(`{
  "emails": [
    "jane_doe@example.com",
    "john_doe@example.com",
    "joann_doe@example.com"
  ]
}`)
	response, err := sendgrid.API(request)
	if err != nil {
		fmt.Println(err.Error())
		os.Exit(1)
	} else {
		fmt.Println(response.StatusCode)
		fmt.Println(response.Body)
		fmt.Println(response.Headers)
	}
}
```

```php
<?php
// Uncomment the next line if you're using a dependency loader (such as Composer) (recommended)
// require 'vendor/autoload.php';

// Uncomment next line if you're not using a dependency loader (such as Composer)
// require_once '<PATH TO>/sendgrid-php.php';

$apiKey = getenv("SENDGRID_API_KEY");
$sg = new \SendGrid($apiKey);
$request_body = json_decode('{
    "emails": [
        "jane_doe@example.com",
        "john_doe@example.com",
        "joann_doe@example.com"
    ]
}');

try {
    $response = $sg->client
        ->marketing()
        ->contacts()
        ->search()
        ->emails()
        ->post($request_body);
    print $response->statusCode() . "\n";
    print_r($response->headers());
    print $response->body() . "\n";
} catch (Exception $ex) {
    echo "Caught exception: " . $ex->getMessage();
}
```

```ruby
require 'sendgrid-ruby'
include SendGrid

sg = SendGrid::API.new(api_key: ENV['SENDGRID_API_KEY'])
data = JSON.parse('{
  "emails": [
    "jane_doe@example.com",
    "john_doe@example.com",
    "joann_doe@example.com"
  ]
}')

response = sg.client.marketing.contacts.search.emails.post(request_body: data)
puts response.status_code
puts response.headers
puts response.body
```

```bash
curl -X POST "https://api.sendgrid.com/v3/marketing/contacts/search/emails" \
--header "Authorization: Bearer $SENDGRID_API_KEY" \
--header "Content-Type: application/json" \
--data '{"emails": ["jane_doe@example.com", "john_doe@example.com", "joann_doe@example.com"]}'
```
