# Manage your exclusion list

## Exclusion list overview

Whenever you have contacts subscribed to multiple lists, it’s tedious to unsubscribe them from every single one, in case they don’t want to receive any marketing emails. You would also want an easy way to prevent a sending in case you accidentally subscribed a contact to a new list.

This is why Campaign Exclusion List was created - it helps you prevent an accidental sending of a marketing campaign to users. You can add users to this exclusion list and they will be automatically blocked from receiving marketing emails.

Info
Contacts in the exclusion list will still be able to receive messages sent via the Send API.

## Single contact exclusion

To add a single contact to the exclusion list, you simply need to modify its IsExcludedFromCampaigns property to true with a `PUT /contact/{contact_id_or_email}`.

### Example

cURL
```shell
# Call to add contact to exclusion list
curl -s \
	-X PUT \
	--user "$MJ_APIKEY_PUBLIC:$MJ_APIKEY_PRIVATE" \
	https://api.mailjet.com/v3/REST/contact/$ID_OR_EMAIL \
	-H 'Content-Type: application/json' \
	-d '{
		"IsExcludedFromCampaigns":"true"
	}'
```

PHP
```php
<?php
/*
Call to add contact to exclusion list
*/
require 'vendor/autoload.php';
use \Mailjet\Resources;
$mj = new \Mailjet\Client(getenv('MJ_APIKEY_PUBLIC'), getenv('MJ_APIKEY_PRIVATE'));
$body = [
    'IsExcludedFromCampaigns' => "true"
];
$response = $mj->put(Resources::$Contact, ['id' => $id, 'body' => $body]);
$response->success() && var_dump($response->getData());
?>
```

Node.js
```javascript
/**
 *
 * Call to add contact to exclusion list
 *
 */
const mailjet = require ('node-mailjet')
	.connect(process.env.MJ_APIKEY_PUBLIC, process.env.MJ_APIKEY_PRIVATE)
const request = mailjet
	.put("contact")
	.id($ID_OR_EMAIL)
	.request({
		"IsExcludedFromCampaigns":"true"
	})
request
	.then((result) => {
		console.log(result.body)
	})
	.catch((err) => {
		console.log(err.statusCode)
	})
```

Ruby
```ruby
# Call to add contact to exclusion list
require 'mailjet'
Mailjet.configure do |config|
  config.api_key = ENV['MJ_APIKEY_PUBLIC']
  config.secret_key = ENV['MJ_APIKEY_PRIVATE']  
end
target = Mailjet::Contact.find($ID_OR_EMAIL)
target.update_attributes(is_excluded_from_campaigns: "true"
)
p variable.attributes['Data']
```

Python
```python
"""
Call to add contact to exclusion list
"""
from mailjet_rest import Client
import os
api_key = os.environ['MJ_APIKEY_PUBLIC']
api_secret = os.environ['MJ_APIKEY_PRIVATE']
mailjet = Client(auth=(api_key, api_secret))
id = '$ID_OR_EMAIL'
data = {
  'IsExcludedFromCampaigns': 'true'
}
result = mailjet.contact.update(id=id, data=data)
print result.status_code
print result.json()
```

Java
```java
package com.my.project;
import com.mailjet.client.errors.MailjetException;
import com.mailjet.client.errors.MailjetSocketTimeoutException;
import com.mailjet.client.MailjetClient;
import com.mailjet.client.MailjetRequest;
import com.mailjet.client.MailjetResponse;
import com.mailjet.client.resource.Contact;
import org.json.JSONArray;
import org.json.JSONObject;
public class MyClass {
    /**
     * Call to add contact to exclusion list
     */
    public static void main(String[] args) throws MailjetException, MailjetSocketTimeoutException {
      MailjetClient client;
      MailjetRequest request;
      MailjetResponse response;
      client = new MailjetClient(System.getenv("MJ_APIKEY_PUBLIC"), System.getenv("MJ_APIKEY_PRIVATE"));
      request = new MailjetRequest(Contact.resource, ID)
			.property(Contact.ISEXCLUDEDFROMCAMPAIGNS, "true");
      response = client.put(request);
      System.out.println(response.getStatus());
      System.out.println(response.getData());
    }
}
```

Go
```go
/*
Call to add contact to exclusion list
*/
package main
import (
	"fmt"
	"log"
	"os"
	mailjet "github.com/mailjet/mailjet-apiv3-go"
	"github.com/mailjet/mailjet-apiv3-go/resources"
)
func main () {
	mailjetClient := NewMailjetClient(os.Getenv("MJ_APIKEY_PUBLIC"), os.Getenv("MJ_APIKEY_PRIVATE"))
	mr := &Request{
	  Resource: "contact",
	  ID: RESOURCE_ID,
	}
	fmr := &FullRequest{
	  Info: mr,
	  Payload: &resources.Contact {
      IsExcludedFromCampaigns: "true",
    },
	}
	err := mailjetClient.Put(fmr)
	if err != nil {
	  fmt.Println(err)
	}
}
```

C#
```csharp
using Mailjet.Client;
using Mailjet.Client.Resources;
using System;
using Newtonsoft.Json.Linq;
namespace Mailjet.ConsoleApplication
{
   class Program
   {
      /// <summary>
      /// Call to add contact to exclusion list
      /// </summary>
      static void Main(string[] args)
      {
         RunAsync().Wait();
      }
      static async Task RunAsync()
      {
         MailjetClient client = new MailjetClient(Environment.GetEnvironmentVariable("MJ_APIKEY_PUBLIC"), Environment.GetEnvironmentVariable("MJ_APIKEY_PRIVATE"));
         MailjetRequest request = new MailjetRequest
         {
            Resource = Contact.Resource,
            ResourceId = ResourceId.Numeric(ID)
         }
            .Property(Contact.IsExcludedFromCampaigns, "true");
         MailjetResponse response = await client.PutAsync(request);
         if (response.IsSuccessStatusCode)
         {
            Console.WriteLine(string.Format("Total: {0}, Count: {1}\n", response.GetTotal(), response.GetCount()));
            Console.WriteLine(response.GetData());
         }
         else
         {
            Console.WriteLine(string.Format("StatusCode: {0}\n", response.StatusCode));
            Console.WriteLine(string.Format("ErrorInfo: {0}\n", response.GetErrorInfo()));
            Console.WriteLine(response.GetData());
            Console.WriteLine(string.Format("ErrorMessage: {0}\n", response.GetErrorMessage()));
         }
      }
   }
}
```

### API Response

```
{
	"Count": 1,
	"Data": [
		{
			"CreatedAt": "2014-06-10T08:30:32Z",
			"DeliveredCount": "",
			"Email": "Mister@mailjet.com",
			"ExclusionFromCampaignsUpdatedAt": "2014-06-10T08:47:28Z",
			"ID": "1",
			"IsExcludedFromCampaigns": "true",
			"IsOptInPending": "false",
			"IsSpamComplaining": "false",
			"LastActivityAt": "2014-06-10T08:47:28Z",
			"LastUpdateAt": "2014-12-31T11:00:46Z",
			"Name": "John",
			"UnsubscribedAt": "",
			"UnsubscribedBy": ""
		}
	],
	"Total": 1
}
```

## Bulk exclusion

In case you want to exclude multiple contacts, you have a couple of options to do that:

- Using `/contact/managemanycontacts`
- Using `/csvimport`


### Using /contact/managemanycontacts

When doing the `POST` call, simply set the `IsExcludedFromCampaigns` to `true` for the contacts you want to exclude.

### Example

cURL
```shell
# Create : Manage the details of a Contact.
curl -s \
	-X POST \
	--user "$MJ_APIKEY_PUBLIC:$MJ_APIKEY_PRIVATE" \
	https://api.mailjet.com/v3/REST/contact/managemanycontacts \
	-H 'Content-Type: application/json' \
	-d '{
		"Contacts":[
				{
						"Email": "jimsmith@example.com",
						"Name": "Jim",
						"IsExcludedFromCampaigns": true,
						"Properties": {
								"Property1": "value",
								"Property2": "value2"
						}
				},
				{
						"Email": "janetdoe@example.com",
						"Name": "Janet",
						"IsExcludedFromCampaigns": true,
						"Properties": {
								"Property1": "value",
								"Property2": "value2"
						}
				}
		]
	}'
```

PHP
```php
<?php
require 'vendor/autoload.php';
use \Mailjet\Resources;
$mj = new \Mailjet\Client(getenv('MJ_APIKEY_PUBLIC'), getenv('MJ_APIKEY_PRIVATE'));
$body = [
    'Contacts' => [
        [
            'Email' => "jimsmith@example.com",
            'Name' => "Jim",
            'IsExcludedFromCampaigns' => true,
            'Properties' => [
                'Property1' => "value",
                'Property2' => "value2"
            ]
        ],
        [
            'Email' => "janetdoe@example.com",
            'Name' => "Janet",
            'IsExcludedFromCampaigns' => true,
            'Properties' => [
                'Property1' => "value",
                'Property2' => "value2"
            ]
        ]
    ]
];
$response = $mj->post(Resources::$ContactManagemanycontacts, ['body' => $body]);
$response->success() && var_dump($response->getData());
?>
```

Node.js
```javascript
/**
 *
 * Create : Manage the details of a Contact.
 *
 */
const mailjet = require ('node-mailjet')
	.connect(process.env.MJ_APIKEY_PUBLIC, process.env.MJ_APIKEY_PRIVATE)
const request = mailjet
	.post("contact")
	.action("managemanycontacts")
	.request({
		"Contacts":[
				{
						"Email": "jimsmith@example.com",
						"Name": "Jim",
						"IsExcludedFromCampaigns": true,
						"Properties": {
								"Property1": "value",
								"Property2": "value2"
						}
				},
				{
						"Email": "janetdoe@example.com",
						"Name": "Janet",
						"IsExcludedFromCampaigns": true,
						"Properties": {
								"Property1": "value",
								"Property2": "value2"
						}
				}
		]
	})
request
	.then((result) => {
		console.log(result.body)
	})
	.catch((err) => {
		console.log(err.statusCode)
	})
```

Ruby
```ruby
# Create : Manage the details of a Contact.
Mailjet.configure do |config|
  config.api_key = ENV['MJ_APIKEY_PUBLIC']
  config.secret_key = ENV['MJ_APIKEY_PRIVATE']
  config.default_from = 'your default sending address'
end
variable = Mailjet::Contact_managemanycontacts.create(contacts: [{ 'Email'=> 'jimsmith@example.com', 'Name'=> 'Jim', 'IsExcludedFromCampaigns'=> true, 'Properties'=> { 'Property1'=> 'value', 'Property2'=> 'value2' }}, { 'Email'=> 'janetdoe@example.com', 'Name'=> 'Janet', 'IsExcludedFromCampaigns'=> true, 'Properties'=> { 'Property1'=> 'value', 'Property2'=> 'value2' }}])
```

Python
```python
"""
Create : Manage the details of a Contact.
"""
from mailjet_rest import Client
import os
api_key = os.environ['MJ_APIKEY_PUBLIC']
api_secret = os.environ['MJ_APIKEY_PRIVATE']
mailjet = Client(auth=(api_key, api_secret))
data = {
  'Contacts': [
				{
						"Email": "jimsmith@example.com",
						"Name": "Jim",
						"IsExcludedFromCampaigns": "true",
						"Properties": {
								"Property1": "value",
								"Property2": "value2"
						}
				},
				{
						"Email": "janetdoe@example.com",
						"Name": "Janet",
						"IsExcludedFromCampaigns": "true",
						"Properties": {
								"Property1": "value",
								"Property2": "value2"
						}
				}
		]
}
result = mailjet.contact_managemanycontacts.create(data=data)
print result.status_code
print result.json()
```

Java
```java
package com.my.project;
import com.mailjet.client.errors.MailjetException;
import com.mailjet.client.errors.MailjetSocketTimeoutException;
import com.mailjet.client.MailjetClient;
import com.mailjet.client.MailjetRequest;
import com.mailjet.client.MailjetResponse;
import com.mailjet.client.resource.ContactManagemanycontacts;
import org.json.JSONArray;
import org.json.JSONObject;
public class MyClass {
    /**
     * Create : Manage the details of a Contact.
     */
    public static void main(String[] args) throws MailjetException, MailjetSocketTimeoutException {
      MailjetClient client;
      MailjetRequest request;
      MailjetResponse response;
      client = new MailjetClient(System.getenv("MJ_APIKEY_PUBLIC"), System.getenv("MJ_APIKEY_PRIVATE"));
      request = new MailjetRequest(ContactManagemanycontacts.resource)
						.property(ContactManagemanycontacts.CONTACTS, new JSONArray()
                                                                .put(new JSONObject()
                                                                    .put("Email", "jimsmith@example.com")
                                                                    .put("Name", "Jim")
                                                                    .put("IsExcludedFromCampaigns", "true")
                                                                    .put("Properties", new JSONObject()
                                                                        .put("Property1", "value")
                                                                        .put("Property2", "value2")))
                                                                .put(new JSONObject()
                                                                    .put("Email", "janetdoe@example.com")
                                                                    .put("Name", "Janet")
                                                                    .put("IsExcludedFromCampaigns", "true")
                                                                    .put("Properties", new JSONObject()
                                                                        .put("Property1", "value")
                                                                        .put("Property2", "value2"))));
      response = client.post(request);
      System.out.println(response.getStatus());
      System.out.println(response.getData());
    }
}
```

Go
```go
/*
Create : Manage the details of a Contact.
*/
package main
import (
	"fmt"
	. "github.com/mailjet/mailjet-apiv3-go"
	"github.com/mailjet/mailjet-apiv3-go/resources"
	"os"
)
func main () {
	mailjetClient := NewMailjetClient(os.Getenv("MJ_APIKEY_PUBLIC"), os.Getenv("MJ_APIKEY_PRIVATE"))
	var data []resources.ContactManagemanycontacts
	mr := &Request{
	  Resource: "contact",
	  Action: "managemanycontacts",
	}
	fmr := &FullRequest{
	  Info: mr,
	  Payload: &resources.ContactManagemanycontacts {
      Contacts: []MailjetContact {
        MailjetContact {
          Email: "jimsmith@example.com",
          Name: "Jim",
          IsExcludedFromCampaigns: true,
          Properties: MyPropertiesStruct {
            Property1: "value",
            Property2: "value2",
          },
        },
        MailjetContact {
          Email: "janetdoe@example.com",
          Name: "Janet",
          IsExcludedFromCampaigns: true,
          Properties: MyPropertiesStruct {
            Property1: "value",
            Property2: "value2",
          },
        },
      },
    },
	}
	err := mailjetClient.Post(fmr, &data)
	if err != nil {
	  fmt.Println(err)
	}
	fmt.Printf("Data array: %+v\n", data)
}
```

C#
```csharp
using Mailjet.Client;
using Mailjet.Client.Resources;
using System;
using Newtonsoft.Json.Linq;
namespace Mailjet.ConsoleApplication
{
    class Program
    {
	/// <summary>
	/// Create : Manage the details of a Contact.
	/// </summary>
	static void Main(string[] args)
        {
            RunAsync().Wait();
        }
        static async Task RunAsync()
        {
            MailjetClient client = new MailjetClient(Environment.GetEnvironmentVariable("MJ_APIKEY_PUBLIC"), Environment.GetEnvironmentVariable("MJ_APIKEY_PRIVATE"));
            MailjetRequest request = new MailjetRequest
            {
                Resource = ContactManagemanycontacts.Resource,
            }
		.Property(ContactManagemanycontacts.Contacts, new JArray {
                new JObject {
                 {"Email", "jimsmith@example.com"},
                 {"Name", "Jim"},
                 {"IsExcludedFromCampaigns", "true"},
                 {"Properties", new JObject {
                  {"Property1", "value"},
                  {"Property2", "value2"}
                  }}
                 },
                new JObject {
                 {"Email", "janetdoe@example.com"},
                 {"Name", "Janet"},
                 {"IsExcludedFromCampaigns", "true"},
                 {"Properties", new JObject {
                  {"Property1", "value"},
                  {"Property2", "value2"}
                  }}
                 }
                });
            MailjetResponse response = await client.PostAsync(request);
            if (response.IsSuccessStatusCode)
            {
                Console.WriteLine(string.Format("Total: {0}, Count: {1}\n", response.GetTotal(), response.GetCount()));
                Console.WriteLine(response.GetData());
            }
            else
            {
                Console.WriteLine(string.Format("StatusCode: {0}\n", response.StatusCode));
                Console.WriteLine(string.Format("ErrorInfo: {0}\n", response.GetErrorInfo()));
                Console.WriteLine(string.Format("ErrorMessage: {0}\n", response.GetErrorMessage()));
            }
	}
    }
}
```

### Using /csvimport

Using the CSV Upload methodology, you can upload a list of contacts to add them to or remove them from the exclusion list. To do that, you need to set the Method property to `excludemarketing` or `includemarketing`, respectively.

Info
The JSON payload sent to /csvimport should NOT contain the `ContactsListID` property. If it does, the following error will appear:` MJ08 Property ContactsList is invalid: Exclusion of contacts from marketing campaign is a global status and can not be applied to a list`

### Example

cURL
```shell
# Create: A wrapper for the CSV importer
curl -s \
	-X POST \
	--user "$MJ_APIKEY_PUBLIC:$MJ_APIKEY_PRIVATE" \
	https://api.mailjet.com/v3/REST/csvimport \
	-H 'Content-Type: application/json' \
	-d '{
		"DataID":"$ID_DATA",
		"Method":"excludemarketing"
	}'
```

PHP
```php
<?php
/*
Create: A wrapper for the CSV importer
*/
require 'vendor/autoload.php';
use \Mailjet\Resources;
$mj = new \Mailjet\Client(getenv('MJ_APIKEY_PUBLIC'), getenv('MJ_APIKEY_PRIVATE'));
$body = [
    'DataID' => "$ID_DATA",
    'Method' => "excludemarketing"
];
$response = $mj->post(Resources::$Csvimport, ['body' => $body]);
$response->success() && var_dump($response->getData());
?>
```

Node.js
```javascript
/**
 *
 * Create: A wrapper for the CSV importer
 *
 */
const mailjet = require ('node-mailjet')
	.connect(process.env.MJ_APIKEY_PUBLIC, process.env.MJ_APIKEY_PRIVATE)
const request = mailjet
	.post("csvimport")
	.request({
		"DataID":"$ID_DATA",
		"Method":"excludemarketing"
	})
request
	.then((result) => {
		console.log(result.body)
	})
	.catch((err) => {
		console.log(err.statusCode)
	})
```

Ruby
```ruby
# Create: A wrapper for the CSV importer
require 'mailjet'
Mailjet.configure do |config|
  config.api_key = ENV['MJ_APIKEY_PUBLIC']
  config.secret_key = ENV['MJ_APIKEY_PRIVATE']  
end
variable = Mailjet::Csvimport.create(data_id: "$ID_DATA",
method: "excludemarketing"
)
p variable.attributes['Data']
```

Python
```python
"""
Create: A wrapper for the CSV importer
"""
from mailjet_rest import Client
import os
api_key = os.environ['MJ_APIKEY_PUBLIC']
api_secret = os.environ['MJ_APIKEY_PRIVATE']
mailjet = Client(auth=(api_key, api_secret))
data = {
  'DataID': '$ID_DATA',
  'Method': 'excludemarketing'
}
result = mailjet.csvimport.create(data=data)
print result.status_code
print result.json()
```

Java
```java
package com.my.project;
import com.mailjet.client.errors.MailjetException;
import com.mailjet.client.errors.MailjetSocketTimeoutException;
import com.mailjet.client.MailjetClient;
import com.mailjet.client.MailjetRequest;
import com.mailjet.client.MailjetResponse;
import com.mailjet.client.resource.Csvimport;
import org.json.JSONArray;
import org.json.JSONObject;
public class MyClass {
    /**
     * Create: A wrapper for the CSV importer
     */
    public static void main(String[] args) throws MailjetException, MailjetSocketTimeoutException {
      MailjetClient client;
      MailjetRequest request;
      MailjetResponse response;
      client = new MailjetClient(System.getenv("MJ_APIKEY_PUBLIC"), System.getenv("MJ_APIKEY_PRIVATE"));
      request = new MailjetRequest(Csvimport.resource)
			.property(Csvimport.DATAID, "$ID_DATA")
			.property(Csvimport.METHOD, "excludemarketing");
      response = client.post(request);
      System.out.println(response.getStatus());
      System.out.println(response.getData());
    }
}
```

Go
```go
/*
Create: A wrapper for the CSV importer
*/
package main
import (
	"fmt"
	"log"
	"os"
	mailjet "github.com/mailjet/mailjet-apiv3-go"
	"github.com/mailjet/mailjet-apiv3-go/resources"
)
func main () {
	mailjetClient := NewMailjetClient(os.Getenv("MJ_APIKEY_PUBLIC"), os.Getenv("MJ_APIKEY_PRIVATE"))
	var data []resources.Csvimport
	mr := &Request{
	  Resource: "csvimport",
	}
	fmr := &FullRequest{
	  Info: mr,
	  Payload: &resources.Csvimport {
      DataID: "$ID_DATA",
      Method: "excludemarketing",
    },
	}
	err := mailjetClient.Post(fmr, &data)
	if err != nil {
	  fmt.Println(err)
	}
	fmt.Printf("Data array: %+v\n", data)
}
```

C#
```csharp
using Mailjet.Client;
using Mailjet.Client.Resources;
using System;
using Newtonsoft.Json.Linq;
namespace Mailjet.ConsoleApplication
{
   class Program
   {
      /// <summary>
      /// Create: A wrapper for the CSV importer
      /// </summary>
      static void Main(string[] args)
      {
         RunAsync().Wait();
      }
      static async Task RunAsync()
      {
         MailjetClient client = new MailjetClient(Environment.GetEnvironmentVariable("MJ_APIKEY_PUBLIC"), Environment.GetEnvironmentVariable("MJ_APIKEY_PRIVATE"));
         MailjetRequest request = new MailjetRequest
         {
            Resource = Csvimport.Resource,
         }
            .Property(Csvimport.DataID, "$ID_DATA")
            .Property(Csvimport.Method, "excludemarketing");
         MailjetResponse response = await client.PostAsync(request);
         if (response.IsSuccessStatusCode)
         {
            Console.WriteLine(string.Format("Total: {0}, Count: {1}\n", response.GetTotal(), response.GetCount()));
            Console.WriteLine(response.GetData());
         }
         else
         {
            Console.WriteLine(string.Format("StatusCode: {0}\n", response.StatusCode));
            Console.WriteLine(string.Format("ErrorInfo: {0}\n", response.GetErrorInfo()));
            Console.WriteLine(response.GetData());
            Console.WriteLine(string.Format("ErrorMessage: {0}\n", response.GetErrorMessage()));
         }
      }
   }
}
```