sendgrid_api/
contacts.rs

1use crate::Client;
2use crate::ClientResult;
3
4pub struct Contacts {
5    pub client: Client,
6}
7
8impl Contacts {
9    #[doc(hidden)]
10    pub fn new(client: Client) -> Self {
11        Contacts { client }
12    }
13
14    /**
15     * Get Sample Contacts.
16     *
17     * This function performs a `GET` to the `/marketing/contacts` endpoint.
18     *
19     * **This endpoint will return up to 50 of the most recent contacts uploaded or attached to a list**.
20     *
21     * This list will then be sorted by email address.
22     *
23     * The full contact count is also returned.
24     *
25     * Please note that pagination of the contacts has been deprecated.
26     */
27    pub async fn get_mc_contats(
28        &self,
29    ) -> ClientResult<crate::Response<crate::types::GetMcContatsResponse>> {
30        let url = self.client.url("/marketing/contacts", None);
31        self.client
32            .get(
33                &url,
34                crate::Message {
35                    body: None,
36                    content_type: None,
37                },
38            )
39            .await
40    }
41    /**
42     * Add or Update a Contact.
43     *
44     * This function performs a `PUT` to the `/marketing/contacts` endpoint.
45     *
46     * **This endpoint allows the [upsert](https://en.wiktionary.org/wiki/upsert) (insert or update) of up to 30,000 contacts, or 6MB of data, whichever is lower**.
47     *
48     * Because the creation and update of contacts is an asynchronous process, the response will not contain immediate feedback on the processing of your upserted contacts. Rather, it will contain an HTTP 202 response indicating the contacts are queued for processing or an HTTP 4XX error containing validation errors. Should you wish to get the resulting contact's ID or confirm your contacts have been updated or added, you can use the "Get Contacts by Emails" endpoint.
49     *
50     * Please note that custom fields need to have been already created if you wish to set their values for the contacts being upserted. To do this, please use the "Create Custom Field Definition" endpoint.
51     *
52     * You will see a `job_id` in the response to your request. This can be used to check the status of your upsert job. To do so, please use the "Import Contacts Status" endpoint.
53     *
54     * If the contact already exists in the system, any entries submitted via this endpoint will update the existing contact. The contact to update will be determined only by the `email` field and any fields omitted from the request will remain as they were. A contact's ID cannot be used to update the contact.
55     *
56     * The email field will be changed to all lower-case. If a contact is added with an email that exists but contains capital letters, the existing contact with the all lower-case email will be updated.
57     */
58    pub async fn put_mc(
59        &self,
60        body: &crate::types::PutMcContactsRequest,
61    ) -> ClientResult<crate::Response<crate::types::PutMcContactsResponse>> {
62        let url = self.client.url("/marketing/contacts", None);
63        self.client
64            .put(
65                &url,
66                crate::Message {
67                    body: Some(reqwest::Body::from(serde_json::to_vec(body)?)),
68                    content_type: Some("application/json".to_string()),
69                },
70            )
71            .await
72    }
73    /**
74     * Delete Contacts.
75     *
76     * This function performs a `DELETE` to the `/marketing/contacts` endpoint.
77     *
78     * **This endpoint can be used to delete one or more contacts**.
79     *
80     * The query parameter `ids` must set to a comma-separated list of contact IDs for bulk contact deletion.
81     *
82     * The query parameter `delete_all_contacts` must be set to `"true"` to delete **all** contacts.
83     *
84     * You must set either `ids` or `delete_all_contacts`.
85     *
86     * Deletion jobs are processed asynchronously.
87     *
88     * **Parameters:**
89     *
90     * * `delete_all_contacts: &str` -- The license key provided with your New Relic account.
91     * * `ids: &str` -- The license key provided with your New Relic account.
92     */
93    pub async fn delete_mc(
94        &self,
95        delete_all_contacts: &str,
96        ids: &str,
97    ) -> ClientResult<crate::Response<crate::types::DeleteMcContactsResponse>> {
98        let mut query_args: Vec<(String, String)> = Default::default();
99        if !delete_all_contacts.is_empty() {
100            query_args.push((
101                "delete_all_contacts".to_string(),
102                delete_all_contacts.to_string(),
103            ));
104        }
105        if !ids.is_empty() {
106            query_args.push(("ids".to_string(), ids.to_string()));
107        }
108        let query_ = serde_urlencoded::to_string(&query_args).unwrap();
109        let url = self
110            .client
111            .url(&format!("/marketing/contacts?{}", query_), None);
112        self.client
113            .delete(
114                &url,
115                crate::Message {
116                    body: None,
117                    content_type: None,
118                },
119            )
120            .await
121    }
122    /**
123     * Get Total Contact Count.
124     *
125     * This function performs a `GET` to the `/marketing/contacts/count` endpoint.
126     *
127     * **This endpoint returns the total number of contacts you have stored.**
128     */
129    pub async fn get_mc_count(
130        &self,
131    ) -> ClientResult<crate::Response<crate::types::GetMcContactsCountResponse>> {
132        let url = self.client.url("/marketing/contacts/count", None);
133        self.client
134            .get(
135                &url,
136                crate::Message {
137                    body: None,
138                    content_type: None,
139                },
140            )
141            .await
142    }
143    /**
144     * Get All Existing Exports.
145     *
146     * This function performs a `GET` to the `/marketing/contacts/exports` endpoint.
147     *
148     * **Use this endpoint to retrieve details of all current exported jobs**.
149     *
150     * It will return an array of objects, each of which records an export job in flight or recently completed.
151     *
152     * Each object's `export_type` field will tell you which kind of export it is and its `status` field will indicate what stage of processing it has reached. Exports which are `ready` will be accompanied by a `urls` field which lists the URLs of the export's downloadable files — there will be more than one if you specified a maximum file size in your initial export request.
153     *
154     * Use this endpoint if you have exports in flight but do not know their IDs, which are required for the "Export Contacts Status" endpoint.
155     */
156    pub async fn get_marketing_exports(
157        &self,
158    ) -> ClientResult<crate::Response<crate::types::GetMarketingContactsExportsResponse>> {
159        let url = self.client.url("/marketing/contacts/exports", None);
160        self.client
161            .get(
162                &url,
163                crate::Message {
164                    body: None,
165                    content_type: None,
166                },
167            )
168            .await
169    }
170    /**
171     * Export Contacts.
172     *
173     * This function performs a `POST` to the `/marketing/contacts/exports` endpoint.
174     *
175     * **Use this endpoint to export lists or segments of contacts**.
176     *
177     * If you would just like to have a link to the exported list sent to your email set the `notifications.email` option to `true` in the `POST` payload.
178     *
179     * If you would like to download the list, take the `id` that is returned and use the "Export Contacts Status" endpoint to get the `urls`. Once you have the list of URLs, make a `GET` request to each URL provided to download your CSV file(s).
180     *
181     * You specify the segements and or/contact lists you wish to export by providing the relevant IDs in, respectively, the `segment_ids` and `list_ids` fields in the request body.
182     *
183     * The lists will be provided in either JSON or CSV files. To specify which of these you would required, set the request body `file_type` field to `json` or `csv`.
184     *
185     * You can also specify a maximum file size (in MB). If the export file is larger than this, it will be split into multiple files.
186     */
187    pub async fn post_mc_export(
188        &self,
189        body: &crate::types::PostMcContactsExportsRequest,
190    ) -> ClientResult<crate::Response<crate::types::PostMcContactsExportsResponse>> {
191        let url = self.client.url("/marketing/contacts/exports", None);
192        self.client
193            .post(
194                &url,
195                crate::Message {
196                    body: Some(reqwest::Body::from(serde_json::to_vec(body)?)),
197                    content_type: Some("application/json".to_string()),
198                },
199            )
200            .await
201    }
202    /**
203     * Get a Contact by ID.
204     *
205     * This function performs a `GET` to the `/marketing/contacts/{id}` endpoint.
206     *
207     * **This endpoint returns the full details and all fields for the specified contact**.
208     *
209     * The "Get Contacts by Emails" endpoint can be used to get the ID of a contact.
210     */
211    pub async fn get_mc(
212        &self,
213        id: &str,
214    ) -> ClientResult<crate::Response<crate::types::ContactDetails3>> {
215        let url = self.client.url(
216            &format!(
217                "/marketing/contacts/{}",
218                crate::progenitor_support::encode_path(id),
219            ),
220            None,
221        );
222        self.client
223            .get(
224                &url,
225                crate::Message {
226                    body: None,
227                    content_type: None,
228                },
229            )
230            .await
231    }
232    /**
233     * Search Contacts.
234     *
235     * This function performs a `POST` to the `/marketing/contacts/search` endpoint.
236     *
237     * **Use this endpoint to locate contacts**.
238     *
239     * The request body's `query` field accepts valid [SGQL](https://sendgrid.com/docs/for-developers/sending-email/segmentation-query-language/) for searching for a contact.
240     *
241     * Because contact emails are stored in lower case, using SGQL to search by email address requires the provided email address to be in lower case. The SGQL `lower()` function can be used for this.
242     *
243     * Only the first 50 contacts that meet the search criteria will be returned.
244     *
245     * If the query takes longer than 20 seconds, a `408 Request Timeout` status will be returned.
246     *
247     * Formatting the `created_at` and `updated_at` values as Unix timestamps is deprecated. Instead they are returned as ISO format as string.
248     */
249    pub async fn post_mc_search(
250        &self,
251        body: &crate::types::PostMcContactsSearchRequest,
252    ) -> ClientResult<crate::Response<crate::types::PostMcContactsSearchResponse>> {
253        let url = self.client.url("/marketing/contacts/search", None);
254        self.client
255            .post(
256                &url,
257                crate::Message {
258                    body: Some(reqwest::Body::from(serde_json::to_vec(body)?)),
259                    content_type: Some("application/json".to_string()),
260                },
261            )
262            .await
263    }
264    /**
265     * Import Contacts.
266     *
267     * This function performs a `PUT` to the `/marketing/contacts/imports` endpoint.
268     *
269     * **This endpoint allows a CSV upload containing up to one million contacts or 5GB of data, whichever is smaller.**
270     *
271     * Imports take place asynchronously: the endpoint returns a URL (`upload_uri`) and HTTP headers (`upload_headers`) which can subsequently be used to `PUT` a file of contacts to be  imported into our system.
272     *
273     * Uploaded CSV files may also be [gzip-compressed](https://en.wikipedia.org/wiki/Gzip).
274     *
275     * In either case, you must include the field `file_type` with the value `csv` in your request body.
276     *
277     * The `field_mappings` paramter is a respective list of field definition IDs to map the uploaded CSV columns to. It allows you to use CSVs where one or more columns are skipped (`null`) or remapped to the contact field.
278     *
279     * For example, if `field_mappings` is set to `[null, "w1", "_rf1"]`, this means skip column 0, map column 1 to the custom field with the ID `w1`, and map column 2 to the reserved field with the ID `_rf1`. See the "Get All Field Definitions" endpoint to fetch your custom and reserved field IDs to use with `field_mappings`.
280     *
281     * Once you recieve the response body you can then initiate a **second** API call where you use the supplied URL and HTTP header to upload your file. For example:
282     *
283     * `curl --upload-file "file/path.csv" "URL_GIVEN" -H 'HEADER_GIVEN'`
284     *
285     * If you'd like to monitor the status of your import job, use the `job_id` and the "Import Contacts Status" endpoint.
286     */
287    pub async fn put_mc_imports(
288        &self,
289        body: &crate::types::PutMcContactsImportsRequest,
290    ) -> ClientResult<crate::Response<crate::types::PutMcContactsImportsResponse>> {
291        let url = self.client.url("/marketing/contacts/imports", None);
292        self.client
293            .put(
294                &url,
295                crate::Message {
296                    body: Some(reqwest::Body::from(serde_json::to_vec(body)?)),
297                    content_type: Some("application/json".to_string()),
298                },
299            )
300            .await
301    }
302    /**
303     * Import Contacts Status.
304     *
305     * This function performs a `GET` to the `/marketing/contacts/imports/{id}` endpoint.
306     *
307     * **This endpoint can be used to check the status of a contact import job**.
308     *
309     * Use the `job_id` from the "Improt Contacts," "Add or Update a Contact," or "Delete Contacts" endpoints as the `id` in the path parameter.
310     *
311     * If there is an error with your `PUT` request, download the `errors_url` file and open it to view more details.
312     *
313     * The job `status` field indicates whether the job is `pending`, `completed`, `errored`, or `failed`.
314     *
315     * Pending means not started. Completed means finished without any errors. Errored means finished with some errors. Failed means finshed with all errors, or the job was entirely unprocessable: for example, if you attempt to import file format we do not support.
316     *
317     * The `results` object will have fields depending on the job type.
318     */
319    pub async fn get_marketing_import(
320        &self,
321        id: &str,
322    ) -> ClientResult<crate::Response<crate::types::ContactImport>> {
323        let url = self.client.url(
324            &format!(
325                "/marketing/contacts/imports/{}",
326                crate::progenitor_support::encode_path(id),
327            ),
328            None,
329        );
330        self.client
331            .get(
332                &url,
333                crate::Message {
334                    body: None,
335                    content_type: None,
336                },
337            )
338            .await
339    }
340    /**
341     * Export Contacts Status.
342     *
343     * This function performs a `GET` to the `/marketing/contacts/exports/{id}` endpoint.
344     *
345     * **This endpoint can be used to check the status of a contact export job**.
346     *
347     * To use this call, you will need the `id` from the "Export Contacts" call.
348     *
349     * If you would like to download a list, take the `id` that is returned from the "Export Contacts" endpoint and make an API request here to get the `urls`. Once you have the list of URLs, make a `GET` request on each URL to download your CSV file(s).
350     */
351    pub async fn get_mc_export(
352        &self,
353        id: &str,
354    ) -> ClientResult<crate::Response<crate::types::ContactExport>> {
355        let url = self.client.url(
356            &format!(
357                "/marketing/contacts/exports/{}",
358                crate::progenitor_support::encode_path(id),
359            ),
360            None,
361        );
362        self.client
363            .get(
364                &url,
365                crate::Message {
366                    body: None,
367                    content_type: None,
368                },
369            )
370            .await
371    }
372    /**
373     * Get Batched Contacts by IDs.
374     *
375     * This function performs a `POST` to the `/marketing/contacts/batch` endpoint.
376     *
377     * **This endpoint is used to retrieve a set of contacts identified by their IDs.**
378     *
379     * This can be more efficient endpoint to get contacts than making a series of individual `GET` requests to the "Get a Contact by ID" endpoint.
380     *
381     * You can supply up to 100 IDs. Pass them into the `ids` field in your request body as an array or one or more strings.
382     */
383    pub async fn post_marketing_batch(
384        &self,
385        body: &crate::types::PostMarketingContactsBatchRequest,
386    ) -> ClientResult<crate::Response<crate::types::PostMarketingContactsBatchResponse>> {
387        let url = self.client.url("/marketing/contacts/batch", None);
388        self.client
389            .post(
390                &url,
391                crate::Message {
392                    body: Some(reqwest::Body::from(serde_json::to_vec(body)?)),
393                    content_type: Some("application/json".to_string()),
394                },
395            )
396            .await
397    }
398    /**
399     * Get Contacts by Emails.
400     *
401     * This function performs a `POST` to the `/marketing/contacts/search/emails` endpoint.
402     *
403     * **This endpoint allows you to retrieve up to 100 contacts matching the searched `email` address(es), including any `alternate_emails`.**
404     *
405     * 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.
406     *
407     * 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.
408     *
409     * 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)](https://sendgrid.com/docs/for-developers/sending-email/segmentation-query-language/) filters when searching.
410     *
411     * If you need to access a large percentage of your contacts, we recommend exporting your contacts with the "Export Contacts" endpoint and filtering the results client side.
412     *
413     * 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.
414     *
415     * This endpoint returns a `404` status code when no contacts are found for the provided email address(es).
416     *
417     * A `400` status code is returned if any searched addresses are invalid.
418     */
419    pub async fn post_marketing_search_email(
420        &self,
421        body: &crate::types::PostMarketingContactsSearchEmailsRequest,
422    ) -> ClientResult<crate::Response<crate::types::PostMarketingContactsSearchEmailsResponse>>
423    {
424        let url = self.client.url("/marketing/contacts/search/emails", None);
425        self.client
426            .post(
427                &url,
428                crate::Message {
429                    body: Some(reqwest::Body::from(serde_json::to_vec(body)?)),
430                    content_type: Some("application/json".to_string()),
431                },
432            )
433            .await
434    }
435}