# General API resources (/general) Here you’ll find all information about the endpoints’ authorizations, possible statuses of your emails, and validation errors. ## Authentication [#authentication] Authentication is done by adding an `Authorization` header containing an API token as a value to your API request. To do this, you need to add an *Authorization* header with the contents of the header being `Bearer XXX` where `XXX` is your API token. ```http Authorization: Bearer XXX ``` API tokens are generated for sending domains and can have different permissions to limit which areas of your account they may be used to access. [Read more](https://www.mailersend.com/help/managing-api-tokens) ## API response [#api-response] MailerSend follows the REST architectural style for it's API and conforms to generic HTTP response standards. ### HTTP status codes [#http-status-codes] MailerSend returns standard HTTP response codes. | Code | Name | Explanation | | ---- | ---------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | 200 | OK | The request was accepted. | | 201 | Created | Resource was created. | | 202 | Accepted | The request was accepted and further actions are taken in the background. | | 204 | No Content | The request was accepted and there is no content to return. | | 400 | Bad Request | There was an error when processing your request. Please adjust your request based on the endpoint requirements and try again. | | 401 | Unauthorized | The provided API token is invalid. [Read more](https://www.mailersend.com/help/managing-api-tokens) | | 403 | Forbidden | The action is denied for that account or a particular API token. Please make sure your account is allowed API access and check your API token permissions. [Read more](https://www.mailersend.com/help/managing-api-tokens) | | 404 | Not Found | The requested resource does not exist on the system. | | 405 | Method Not Allowed | HTTP method is not supported by the requested endpoint. | | 408 | Request Timeout | There is an error on our system. [Please contact support](https://www.mailersend.com/contact-us) | | 421 | Service isn't available, try again later | We are currently running maintenance. | | 422 | Unprocessable Entity | There was a validation error found when processing the request. Please adjust it based on the endpoint requirements and try again. [Read more](#validation-errors) | | 429 | Too Many Requests | There were too many requests made to the API. Read more on [rate limits](#rate-limits) and [daily request quota](#daily-request-quota). | | 500 | Internal Server Error | There was an error on our system. [Please contact support](https://www.mailersend.com/contact-us) | | 502 | Bad Gateway | There was an error on our system. [Please contact support](https://www.mailersend.com/contact-us) | | 503 | Service Unavailable | There was an error on our system. [Please contact support](https://www.mailersend.com/contact-us) | | 504 | Gateway Timeout | There was an error on our system. [Please contact support](https://www.mailersend.com/contact-us) | More info on HTTP response codes can be found on [Mozilla Developer Network](https://developer.mozilla.org/en-US/docs/Web/HTTP/Status). ### Other error response messages [#other-error-response-messages] | Code | Message | Explanation | | ------- | ------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | MS40001 | The bulk request sent is malformed. | The request payload provided is malformed. Please check the payload and contact Customer Support for more help. | | MS40301 | The custom API token you're using doesn't have the required permissions. | The custom API token used doesn't have the required permissions. For example, this error would be returned if youe send a request to the email endpoint using a token that does not allow email access. If you receive this error, check that you are using a token with the required permission.

See more information about token scopes: [Possible scopes](/api/v1/tokens#possible-scopes) | | MS40302 | Your account's access to API/SMTP has been switched off. | The Customer Support team has switched off the account's API/SMTP access. Please check your account status on the MailerSend app or see if we sent an email with the next steps. | | MS40303 | Your account is not authorized to perform this action. | The account tried to send a request to the MailerSend servers but is not authorized to do so. Please check your account status on the MailerSend app or see if we sent an email with the next steps | | MS40304 | Your account is suspended, you can't do any more requests. | The account tried to send a request to the MailerSend servers but is suspended. Please check your account status on the MailerSend app or see if we sent an email with the next steps. | | MS40305 | Your IP address is not allowlisted. | The account tried to send a request to the MailerSend servers from an IP address that is not allowlisted. Please ensure that your IP address is added to the allowlist. You can update your allowlisted IP addresses in the MailerSend app or contact Customer Support for further assistance. | | MS42201 | “\{recipient email} is duplicated in the \{$field} recipients list.” | The request contains duplicated recipients. Turn on your domain's Ignore duplicated recipients advanced setting to avoid this error.

Find out more about this setting: [What is a sending domain](https://www.mailersend.com/help/what-is-a-sending-domain#advanced-settings) | | MS42202 | Could not validate the attached file. Filename and attached file does not match. | The file name and file type do not match. For example, the filetype is a GIF file but the file name is image.png. | | MS42204 | Your account reached its email quota limit. Contact support to increase it. | The account has a custom email quota due to compliance concerns and it reached it. Contact customer support to clarify how your business uses MailerSend. | | MS42205 | The \{$field} recipient limit is exceeded. | The limit of TO, CC or BCC recipients in a single email object has been reached. Approved accounts can include up to 50 TO, 10 CC and 10 BCC recipients. Unapproved acounts can include up to 10 TO, 1 CC and 1 BCC recipients. Get your account approved to send to more recipients or use our bulk email endpoint.

See the request parameter of the /email endpoint: [Request parameters](./api/v1/email.md#request-parameters) | | MS42206 | The attachments.0.content size exceeds the threshold of 25 MB.” | The attachment size exceeds the limit of 25MB. Zip the file or use a cloud storage service to send your file.

See more information about the list of all supported filetypes: [Supported file types](./api/v1/email.md#supported-file-types) | | MS42207 | The from.email domain must be verified in your account to send emails. | The from.email domain must be verified in your account to be able to send emails. Please make sure the domain you want to send from has a is\_verified value set to 'true' via the API or the app. Users on Starter plans and above can also add the from email address as a sender identity.

See more information about verifying your domain: [How to verify and authenticate a sending domain](https://www.mailersend.com/help/how-to-verify-and-authenticate-a-sending-domain) | | MS42208 | The \{$field} must be a valid email address. | There was a formatting problem in your request. The to/from/cc/bcc/reply-to.email must be a valid email address.

See more information about the request parameters: [Request parameters](./api/v1/email.md#request-parameters) | | MS42209 | The \{$field} field is required.” | There was either a formatting problem in your request or you're missing one of the following parameters: to, from, subject.

See more information about the request parameters: [Request parameters](./api/v1/email.md#request-parameters) | | MS42210 | This file type is not supported.” | This file type is not supported.

See more information about the list of all supported filetypes: [Supported file types](./api/v1/email.md#supported-file-types) | | MS42211 | You must provide one of html, text or template\_id.” | There was either a formatting problem in your request or you're missing one of the following parameters: html, text or template\_id. See more information about request parameters: [Request parameters](./api/v1/email.md#request-parameters) | | MS42213 | The value you provided in :attribute failed to compile. Please check the submitted text/html. | There are some errors in the text or HTML provided, please make sure there are no errors to avoid conflicts. | | MS42214 | You have used an app reserved variable. Please use another variable | The email you're trying to send has one or more variables that are reserved by the MailerSend application. Please consider changing the variables to avoid conflicts. | | MS42215 | The attachment content must be a Base64 encoded string. | All attachments have to be encoded in a Base64 string. Find an encoder to convert your file before attaching it to your email. | | MS42216 | This feature requires a Hobby plan or higher. Upgrade to use it. | There are some limits to each plan and the action you'd like to do is not available on your current plan. Please take a look at the current limits and consider upgrading to a higher plan.

See more information about the plan limits: [Pricing](https://www.mailersend.com/pricing) | | MS42217 | One or more emails in the variables field do not exist in the recipients field. | The email addresses on the recipient and personalization fields do not match, please make sure you're adding the same email address on both the TO and personalization fields. | | MS42218 | The send\_at timestamp does not match the Unix format | The timestamp used for the send\_at parameter is not written in the Unix format. The send\_at parameter has to be written in Unix format and be no longer than 72 hours in the future from the moment the call is made.

Use [unixtimestamp](https://www.unixtimestamp.com/) to convert a date to the Unix timestamp format. | | MS42219 | The send\_at must be a date in the future. | The timestamp used for the send\_at parameter is not in the future. The send\_at parameter has to be written in Unix format and be no longer than 72 hours in the future from the moment the call is made. | | MS42220 | The \{$field} may only contain alphanumeric characters and hyphens. | The value submitted must be a string consisting of only alphanumeric characters and hyphens. | | MS42221 | The \{$field} must be a string. | The value submitted must be a string | | MS42222 | Your trial domain reached its email quota limit. | The email quota limit for your trial domain was reached. | | MS42223 | You already have a trial account. | | | MS42224 | Templates require a read own templates permission. | The read own templates permission must be assigned to the user in order to allow the user to read the templates provided. | | MS42225 | You have reached the trial domain unique recipients limit. | Each trial domain has a limit of unique recipients allowed to send an email to. This limit has been reached, and to continue sending emails please use the already created recipients. | | MS42226 | Your default template domain must be verified in your account to send emails. | The template in use has an associated default domain that is not verified. To send emails the domain must be verified or disassociated from the template. | | MS42227 | JSON contains a syntax error. | The request payload provided contains a JSON syntax error. Please check the payload and contact Customer Support for more help. | | MS42228 | JSON contains a decoding error. | The request payload provided contains a decoding error. Please check the payload and contact Customer Support for more help. | | MS42229 | The number of email objects must not be greater than 500. | The request payload provided contains a number of email objects surpassing the limit of 500. | | MS42230 | The email objects are required. | The request payload provided does not contain any email object. Please check the payload and contact Customer Support for more help. | | MS42231 | The bulk request item is invalid. | The email object provided is invalid. Please check the payload and contact Customer Support for more help. | | MS42232 | The \{$field} field is required when role is custom user. | When the user in question has the custom user role, it's mandatory to provide the permission details for that user. | | MS42901 | Your account reached its API daily quota limit. Upgrade to increase it. | The account making the request reached its API daily quota limit. Upgrade to raise your quota.
Every request is counted against the quota and the quota is reset daily at midnight UTC.

Trial plan accounts have a daily limit of 100 API requests. Hobby plan accounts are limited to 1,000 daily requests. Starter plan accounts can send up to 100,000 daily requests, and Professional or Enterprise plan accounts can send up to 500,000 requests.

See more information about quotas and learn how to avoid this error: [Daily request quota](#daily-request-quota) | | MS42903 | Your account reached its rate limit of \{$limit} requests/min. Please wait before trying again. | The account making the request reached its rate limit. The default rate limit is 120 requests per minute for /email endpoints, 10 requests per minute for /bulk-email endpoints and 60 requests per minute for all other endpoints. Please wait for the amount of seconds indicated by 'retry-after' and try again.

See more information about rate limits: [Rate limits](#rate-limits) | | MS5001 | Something unexpected happened while processing the bulk request. Please contact Customer Support if the problem persists. | An unexpected error occurred in our servers while processing your bulk request. We are aware it happened and are working on finding a fix. Please contact Customer Support if the problem persists. | ### SMS delivery codes [#sms-delivery-codes] | **Code** | **Description** | **Friendly Description** | **Explanation Of Error** | **Billable** | | -------- | ----------------------------------------- | ---------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | ------------ | | 4001 | service-not-allowed | Message was rejected for reasons other than those covered by other 4xxx codes | This is a general error that the service you are attempting to use is not allowed; you may have inaccurate permissions, formatting or may not be enable to use that service. | NO | | 4301 | malformed-invalid-encoding | Malformed message encoding | The message contains invalid characters that are not supported. MailerSend cannot re-encode message for destination. | NO | | 4302 | malformed-invalid-from-number | Malformed From number | The From number associated with the message is a number not routable to a carrier or valid in the industry (Ex: a 9 digit number). | NO | | 4303 | malformed-invalid-to-number | Malformed To Number | The To number associated with the message is a number not routable to a carrier or valid in the industry (Ex: a 9 digit number). | NO | | 4350 | malformed-for-destination | Malformed message encoding | Message passed validation on receive stage, but failed on send. This is likely because the destination number (To) is an invalid number. | NO | | 4360 | message-not-sent-expiration-date-passed | Message expired | Message was not sent because the specified expiration date passed before the message was able to send | NO | | 4401 | rejected-routing-error | BW is unable to route the message | Message is unable to be routed within MailerSend particularly when the source and destination are the same number. The destination or To number is mis-provisioned or there is a configuration with the message that is causing a situation where a message is being sent repeatedly between the same numbers. | NO | | 4403 | rejected-forbidden-from-number | Messaging forbidden on From number | Messaging on this From number is forbidden most commonly because the number does not belong to MailerSend or the account. Other reasons include: the TN is not enabled in the MailerSend Dashboard, the account associated with this number is not enabled for this type of messaging, the TN is disconnected, or it is an invalid number (i.e., 11111111111). | NO | | 4404 | rejected-forbidden-to-number | Messaging forbidden on To number | Messaging on this To number is forbidden. This could be the number is not active, not enabled for messaging or is an invalid number (i.e. 11111111111) | NO | | 4405 | rejected-unallocated-from-number | Unallocated from number | The From telephone number is considered unallocated when the number does not exist in our database as an active number. This number is either not enabled for messaging at the industry level, or the number is not yet released in the industry | NO | | 4406 | rejected-unallocated-to-number | Unallocated to number | The To number associated with this message, while a valid North American number, is not yet assigned to a carrier and the message cannot be sent downstream. | NO | | 4407 | rejected-account-not-defined-from-number | From Number is associated with account | Undefined source account id. The From number associated with this message is not associated with this account, is an invalid number or not configured appropriately to send messages. | NO | | 4408 | rejected-account-not-defined-to-number | To Number not associated with account | Undefined destination account id. The To (destination) number is not associated with an account, is an invalid number or not configured correctly to receive messages. | NO | | 4409 | rejected-invalid-from-profile | Invalid destination profile | MailerSend failed to create destination. The destination profile is considered invalid, most often this is because the destination number does not support MMS. | NO | | 4410 | media-unavailable | Could not download media | There was an error retrieving the media from the media web server. Check the media URL and try to access directly to see if the media can be fetched successfully. | NO | | 4411 | rejected-message-size-limit-exceeded | Combined size of media too large | The total size of MMS message media/attachments exceeded the max file size supported | NO | | 4412 | media-content-invalid | Failed to parse Content-Type for media | The media content type is not a supported media content type. | NO | | 4420 | rejected-carrier-does-not-exist | No Route to Destination Carrier | The upstream carrier associated with the message does not exist in MailerSend configuration | NO | | 4421 | rejected-forbidden-no-destination | No Route to Destination Carrier | The message cannot be sent downstream as the account associated with the message does not have permission to send to this destination. You may not be provisioned to send to this destination. | NO | | 4432 | rejected-forbidden-country | Messaging to country forbidden | MailerSend system indicates the account associated with the message is not enabled for messaging this zone, this country or this country is outside of messaging reach (specifically for MMS). | NO | | 4433 | rejected-forbidden-tollfree | Messaging on Toll Free Number Forbidden | The account associated with this message is not enabled for toll free messaging | NO | | 4434 | rejected-forbidden-tollfree-for-recipient | Messaging to Toll Free Number Forbidden | Messaging to this toll free number is not allowed. Number is likely not enabled for messaging or not active. | NO | | 4470 | rejected-spam-detected | Rejected as SPAM | This message has been filtered and blocked by MailerSend for spam. Messages can be blocked for a variety of reason, including but not limited to volumetric filtering, content blocking, SHAFT violation, etc. | YES | | 4481 | rejected-from-number-in-blacklist | From Number in black list | The From number has been flagged by MailerSend as prohibited from sending messages. This is typically because MailerSend or a downstream carriers has several violations; reports of spam, P2P violations, associated with this number. | NO | | 4482 | rejected-to-number-in-blacklist | To Number in black list | The number you are attempting to send to is blocked from receiving messages. | NO | | 4492 | reject-emergency | Message to emergency number forbidden | Messaging to an emergency number is forbidden | NO | | 4493 | rejected-unauthorized | Unauthorized | MailerSend service indicates the sender is not authorized to send messages from the account. | NO | | 4700 | invalid-service-type | Carrier Rejected as Invalid Service Type | Carrier rejected message for invalid service type. This usually means messaging (SMS or MMS) is not supported by the carrier or handset. | YES | | 4701 | destination-service-unavailable | Destination is not reachable and SMS service is not available. | Carrier service is reporting the destination is not reachable or the SMS service is not available. | YES | | 4702 | destination-subscriber-unavailable | Destination subscriber is unavailable. | This error indicates the subscriber is unavailable. There are several reasons for this; the subscriber has turned off handset, the destination is unreachable or barred, the GSM subscriber is busy for outbound SMS, SIM card is full, voicemail is full, or cannot reach the destination handset and has stored the message for retry in its « Store & Forward » function. | YES | | 4711 | rejected-message-size-limit-exceeded | Media size too large | Downstream vendor cannot retrieve the media as the MMS attachment is too large | YES | | 4712 | media-content-invalid | The media content type is not supported | The media content type is not supported. | YES | | 4720 | invalid-destination-address | Carrier Rejected as Invalid Destination Address | Carrier Rejected as Invalid Destination Address. This could mean the number is not in the numbering plan (area code does not exist or the number is just invalid) or the number is not enabled for messaging (like a landline). Additionally, for toll free messages to TMobile, this could also mean the user has opted to block all toll free and short code traffic | YES | | 4721 | destination-tn-deactivated | TN on deactivation list | The phone number you are attempting to send to is on the deactivation list. It is not associated with a carrier to be able to receive messages or is inactive. | YES | | 4730 | no-route-to-destination-carrier | No route to destination carrier or no roaming route exists. | Carrier is reporting there is no route available for message. This could be because no routing exists to destination, no roaming route is available, the destination handset is roaming on a network that cannot be reached, no SS7 route, or routing was denied | YES | | 4740 | invalid-source-address-address | Carrier Rejected as Invalid Source Address | Carrier is rejecting the message due to invalid source address - the number does not exist in the numbering plan. Other reasons for this error code is the source carrier is invalid or disabled or source not authorized or the number type is not supported. | YES | | 4750 | destination-rejected-message | Carrier Rejected Message | The destination carrier has rejected the message but provided no specific reason. For AT\&T traffic, this could be a prepaid user whose account is out of money, a subscriber that is provisioned to not receive this type of SMS or it was identified as Spam | YES | | 4751 | destination-rejected-message-size-invalid | Message is too long or message length is invalid for the carrier. | Carrier has rejected for message length is invalid or too long. | YES | | 4752 | destination-rejected-malformed | Message is malformed for the carrier. | Carrier is rejecting the message malformed; this could be because of a blank message, unacceptable data value, the receiving SMSC or SME does not accept messages with more than 160 characters, syntax error, content is invalid, message ID is invalid, invalid parameter length, expected TLV missing, invalid TLV value, invalid data coding scheme, invalid number of destinations, error in the optional part of the PDU body, TLV not allowed, or XML validation error. | YES | | 4753 | destination-rejected-handset | The destination handset has rejected the message | The handset has rejected the message | YES | | 4770 | destination-spam-detected | Carrier Rejected as SPAM | The Carrier is reporting this message as blocked for SPAM. Spam blocks could be a result of content, SHAFT violations (including specific keywords), originating address has been flagged for repeated spam content | YES | | 4771 | rejected-shortened-url | Rejected due to shortened url | There was an error with the shortened URL used. MailerSend recommends customers obtain their own dedicated domain if shortened links are needed for their messaging campaign. | YES | | 4772 | rejected-tn-blocked | Blocked sender or receiver | This error indicates a blocked Sender or Receiver on the downstream platform. Please reach out to MailerSend support so we can determine which telephone number is blocked and why. | YES | | 4775 | destination-rejected-due-to-user-opt-out | Carrier Rejected due to user opt out | User has opted out of receiving messages from a particular sender. Remove the destination TN from subscriber list and cease communication with the destination. | YES | | 4781 | volume-violation-att | AT\&T rejected due to 10DLC volumetric violation or throttling | AT\&T rejected due to volumetric violation. You have sent over the rate limit for your toll-free number. Please review your number throughput limit to ensure you are not exceeding the approved volumes. This error can also indicate throttling by AT\&T for other reasons, including high spam rates. | YES | | 4785 | volumetric-violation | Carrier rejected due to volumetric violation | The carrier rejected the message due to a volumetric violation. You have sent over the allotted limit and need to back off sending. Please retry after some time. | YES | | 4795 | tfn-not-verified | Toll Free number is not verified | The message was blocked due to the toll free number not being verified. This can also be because there is SPAM on the unverified TFN. Please review [unverified sending limits](https://support.bandwidth.com/hc/en-us/articles/1500006962542-Bandwidth-toll-free-verification-handbook-) and submit TFN for verification as soon as possible. | YES | | 5100 | temporary-app-error | Application Error | An application within the MailerSend service is experiencing a temporary error that is preventing the message from being processed. | NO | | 5101 | temporary-app-shutdown | Application Error | App going down. Message not received. Sender should send this messages later or to other host. | NO | | 5106 | impossible-to-route | Impossible to route / Attempt to deliver through retries has failed. | Impossible to route / Attempt to deliver through retries has failed. | NO | | 5111 | temporary-app-connection-closed | Application Error | Received messaged for connection which is already removed. | NO | | 5201 | temporary-rout-error-retries-exceeded | Application Error | MailerSend service expired the message after attempts to deliver through retries failed. | NO | | 5211 | temporary-app-error-app-busy | Application Error | MailerSend service application is temporarily busy so it cannot receive messages at this time | NO | | 5220 | temporary-store-error | Application Error | Message not received. Cannot save message to store. | NO | | 5231 | discarded-concatenation-timeout | Application Error | MailerSend did not receive all parts of message. Message can not be sent. | NO | | 5500 | message-send-failed | General Message Send Failure | The destination carrier has reported a general service failure with sending the message. | NO | | 5501 | message-send-failed | General Message Send Failure | The message is unable to send as no destination is available. | NO | | 5600 | destination-carrier-queue-full | Carrier Service Unavailable | Carrier Service Unavailable. This could result from network congestion, messaging queue full on the vendor side, throttling error on the vendor side. | YES | | 5610 | submit \_ sm-or-submit \_ multi-failed | Carrier Service Failure | The downstream carrier application is experiencing an error. submitting the message has failed or cancelling message has failed | YES | | 5620 | destination-app-error | Carrier Application Error | The carrier is reporting a general error associated with their application processing the message. | YES | | 5630 | message-not-acknowle | Carrier Application Error | NACK - no response or acknowledgement received from the carrier | YES | | 5650 | destination-failed | Carrier Service Failure | Carrier Service is reporting a failure to send to destination (mobile operator or handset). | YES | | 5999 | unknown-error | Unknown error from MailerSend | Unknown error generated by MailerSend when MailerSend core reports an unknown error | NO | | 9902 | delivery-receipt-expired | Timed out waiting for delivery receipt. The reason a delivery receipt was not received is not known. | MailerSend timed out waiting for the delivery receipt, this could be because the downstream provider did not send the requested delivery receipt or they sent after the system timed out at two hours. | YES | | 9999 | unknown-error | Unknown error from downstream. Carrier reported a failure code that is unknown to MailerSend. | MailerSend does not recognize the vendor's error response or does not have the vendor code mapped internally | YES | ### Validation errors [#validation-errors] You might experience some of the errors described below when a request fails to pass validation. The response will return an `array` that contains the names of fields that failed as a *key* and an `array` of `strings` as a *value*. ```http Response Code: 422 Unprocessable Entity Response Headers: content-type: application/json ``` ```json { "message": "The given data was invalid.", "errors": { "from.email": [ "The from.email domain must be verified in your account to send emails. #MS42207" ] } } ``` [Get more information on validation errors in our knowledge base](https://www.mailersend.com/help/how-to-start-sending-emails#rest-api) ### Rate limits [#rate-limits] MailerSend has a default rate limit of 60 requests per minute on general API endpoints. If you exceed that rate limit, you will receive a 429 error response with a “Too Many Attempts.” message. Please wait for the amount of seconds indicated by `retry-after` and try again. | Request type | Rate limit | | ------------------------------------------------------------------------------------- | ------------------- | | All API requests (excluding email endpoints) | 60 requests/minute | | API requests to [`POST` /v1/email](/api/v1/email#send-an-email) | 120 requests/minute | | API requests to [`POST` /v1/bulk-email](/api/v1/email#send-bulk-emails) | 10 requests/minute | | API requests to [`GET` /v1/activity](/api/v1/email/activity#get-a-list-of-activities) | 10 requests/minute | | SMTP | 120 requests/minute | #### Example response [#example-response] ```http HTTP/2 429 content-type: application/json x-ratelimit-limit: 60 x-ratelimit-remaining: 0 retry-after: 59 x-ratelimit-reset: 1629291024 { "message": "Your account reached its rate limit of 120 requests/min. Please wait before trying again. #MS42903" } ``` ### Daily request quota [#daily-request-quota] MailerSend has a daily request quota for API and SMTP relay services. Every request is counted against the quota and is reset daily at midnight UTC. | Plan | Quota / day | | ------------ | ----------- | | Trial | 100 | | Hobby | 1000 | | Starter | 100,000 | | Professional | 500,000 | | Enterprise | 500,000 | Two HTTP headers to indicate the quota limit and quota reset time will be returned with every API request. When the quota is hit, MailerSend will return a `429` HTTP error. ##### Example response [#example-response-1] ```http HTTP/2 429 content-type: application/json x-ratelimit-limit: 60 x-ratelimit-remaining: 59 retry-after: 59 x-apiquota-remaining: 0 x-apiquota-reset: 2022-03-05T00:00:00Z { "message": "Your account reached its API daily quota limit. Upgrade to increase it. #MS42901" } ``` ##### Tips [#tips] * Avoid sending repeated API requests that fail validation (HTTP `422` error) * To track email activity and status, use [webhooks](/api/v1/account/webhooks) * If you are sending emails in bulk, use [bulk endpoint](/api/v1/email#send-bulk-emails) * For more throughput, upgrade to a professional plan. ## Email resource [#email-resource] ### Activity status list [#activity-status-list] You can query the status of a sent email using the `GET` request with the ID of the email sent. | Status | Description | | ----------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `queued` | Your API request has been authorized and will be processed. | | `sent` | Your email was sent from our sending servers. We are now waiting for a response from the receiving servers. | | `delivered` | Your email was successfully delivered with no errors. | | `soft_bounced` | Your email was not delivered because it soft bounced. A soft bounce is a temporary rejection by a receiving recipient’s server. This may happen because the recipient's inbox is full. | | `hard_bounced` | Your message was not delivered. The message was returned to our servers because the recipient's address is invalid. A hard bounce may occur because the domain name does not exist or because the recipient is unknown. You will not be able to send future email messages to recipients that hard bounced. Use the Suppressions tool to check and manage all rejected recipients. | | `deferred` | Your email is temporarily delayed due to a hold by the recipient's server. | | `junk` | Your message was sent to your recipient’s junk folder. | | `opened` | The recipient received your message and opened it. Opens tracking is only available if you enabled it in your domain settings. | | `clicked` | The recipient clicked a link that’s in your message. Likewise, clicks tracking is only available if you enabled it in your domain settings. | | `unsubscribed` | Your message was rejected because the recipient's email address is in your Suppression list. | | `spam_complaints` | Similarly, your message was rejected because the recipient's email address is in your Suppression list. | ## SMS resource [#sms-resource] ### SMS status list [#sms-status-list] | Status | Description | | ----------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | | `processed` | Our servers have processed your request and your SMS has been passed to our sending servers. | | `queued` | Your API request has been authorized and will be processed. | | `sent` | Your SMS was sent from our sending servers and the downstream carrier has accepted the message. | | `delivered` | MailerSend has received a delivery receipt from the downstream carrier confirming successful delivery to the carrier or handset (when available). | | `failed` | The message could not be sent or the delivery receipt received from the downstream carrier indicated the message was not deliverable. Review error codes for more information. | # What is MailerSend? (/) MailerSend is a powerful transactional email system built for developers but designed so non-tech teams can contribute without coding. We believe that creating, sending and tracking transactional emails is a team effort. Everyone can contribute to analyzing and optimizing email engagement with MailerSend's intuitive interface, combined with a powerful sending infrastructure to scale quickly. At the moment, transactional emails can be sent through MailerSend’s Email API or using SMTP relay. ## MailerSend API [#mailersend-api] MailerSend API is RESTful, fully featured, and easy to integrate with. ## Base URL [#base-url] All API requests should start with the following base part: ``` https://api.mailersend.com/v1/ ``` ## Official libraries [#official-libraries] MailerSend supports this list of official libraries for your favorite programming language. This is the easiest way to integrate MailerSend with your application. * [MailerSend PHP](https://github.com/mailersend/mailersend-php) * [MailerSend for Laravel](https://github.com/mailersend/mailersend-laravel-driver) * [MailerSend Node.js](https://github.com/mailersend/mailersend-nodejs) * [MailerSend Golang](https://github.com/mailersend/mailersend-go) * [MailerSend Python](https://github.com/mailersend/mailersend-python) * [MailerSend Ruby](https://github.com/mailersend/mailersend-ruby) * [MailerSend Java](https://github.com/mailersend/mailersend-java) * [MailerSend OpenAPI collection](https://app.swaggerhub.com/apis/MailerSend/mailersend-api/1.0.0-oas3.1) See the full list of integrations we support [here](https://www.mailersend.com/integrations). *** We try to keep our documentation as clear and simple as possible. If there is something you’d like to see, your [feedback](https://www.mailersend.com/contact-us) is always encouraged. # Sending emails with MailerSend SDKs (/sdk) MailerSend ships official SDKs for PHP, Node.js, Python, Go, Ruby, and Java. Pick your language below for the install, configure, and send-an-email steps. ## Prerequisites [#prerequisites] * A MailerSend account with at least one verified sending domain * An API token generated in **Settings → API Tokens** * The runtime for your chosen language installed locally ## Install the SDK and send an email [#install-the-sdk-and-send-an-email] **Install the SDK** Run the following command in your project directory to install the MailerSend Node.js SDK and the `dotenv` module: ```shell npm install mailersend dotenv ``` **Set your API key** Create a `.env` file in your project root and add your API key: ```shell title=".env" MAILERSEND_API_KEY= ``` **Send an email** Create `app.js` with the following: ```js title="app.js" import 'dotenv/config'; import { MailerSend, EmailParams, Sender, Recipient } from "mailersend"; const mailerSend = new MailerSend({ apiKey: process.env.MAILERSEND_API_KEY, }); const sentFrom = new Sender("you@yourdomain.com", "Your name"); const recipients = [new Recipient("recipient@example.com", "Recipient name")]; const emailParams = new EmailParams() .setFrom(sentFrom) .setTo(recipients) .setSubject("Hello from MailerSend") .setHtml("This is the HTML content") .setText("This is the text content"); mailerSend.email .send(emailParams) .then((response) => console.log(response)) .catch((error) => console.log(error)); ``` Run it: ```shell node app.js ``` **Install the SDK** The PHP SDK uses PSR-7 and PSR-18, so install an HTTP adapter alongside the SDK: ```shell composer require php-http/guzzle7-adapter nyholm/psr7 composer require mailersend/mailersend ``` **Set your API key** Initialise the client with your API key: ```php use MailerSend\MailerSend; $mailersend = new MailerSend(['api_key' => 'YOUR_API_KEY']); ``` **Send an email** Build the email and send it: ```php use MailerSend\Helpers\Builder\EmailParams; use MailerSend\Helpers\Builder\Recipient; $recipients = [ new Recipient('recipient@example.com', 'Recipient Name'), ]; $email = (new EmailParams()) ->setFrom('you@yourdomain.com') ->setFromName('Your Name') ->setRecipients($recipients) ->setSubject('Hello from MailerSend') ->setHtml('

Hello world!

') ->setText('Hello world!'); $mailersend->email->send($email); ```
**Install the SDK** Install the SDK with pip: ```shell pip install mailersend ``` **Set your API key** Export it as an env var: ```shell export MAILERSEND_API_KEY= ``` **Send an email** ```python import os from mailersend import emails mailer = emails.NewEmail(os.environ['MAILERSEND_API_KEY']) mail_body = {} mail_from = { "name": "Your Name", "email": "you@yourdomain.com", } recipients = [ {"name": "Recipient Name", "email": "recipient@example.com"}, ] mailer.set_mail_from(mail_from, mail_body) mailer.set_mail_to(recipients, mail_body) mailer.set_subject("Hello from MailerSend", mail_body) mailer.set_html_content("

This is the HTML content

", mail_body) mailer.set_plaintext_content("This is the text content", mail_body) mailer.send(mail_body) ```
**Install the SDK** ```shell go get github.com/mailersend/mailersend-go ``` **Set your API key** ```go import "github.com/mailersend/mailersend-go" ms := mailersend.NewMailersend("YOUR_API_KEY") ``` **Send an email** ```go package main import ( "context" "log" "github.com/mailersend/mailersend-go" ) func main() { ms := mailersend.NewMailersend("YOUR_API_KEY") from := mailersend.From{ Name: "Your Name", Email: "you@yourdomain.com", } recipients := []mailersend.Recipient{ {Name: "Recipient Name", Email: "recipient@example.com"}, } message := ms.Email.NewMessage() message.SetFrom(from) message.SetRecipients(recipients) message.SetSubject("Hello from MailerSend") message.SetHTML("

This is the HTML content

") message.SetText("This is the text content") if _, err := ms.Email.Send(context.TODO(), message); err != nil { log.Fatal(err) } } ```
**Install the SDK** ```shell gem install mailersend-ruby ``` **Set your API key** Add the token to a `.env` file in your project root, or export it system-wide: ```shell title=".env" MAILERSEND_API_TOKEN= ``` **Send an email** ```ruby require "mailersend-ruby" ms_email = Mailersend::Email.new ms_email.add_from("email" => "you@yourdomain.com", "name" => "Your Name") ms_email.add_recipients("email" => "recipient@example.com", "name" => "Recipient Name") ms_email.add_subject("Hello from MailerSend") ms_email.add_html("

This is the HTML content

") ms_email.add_text("This is the text content") ms_email.send ```
**Install the SDK** Add the dependency to your build file: ```xml title="pom.xml (Maven)" com.mailersend java-sdk 1.0.0 ``` ```groovy title="build.gradle (Gradle)" implementation 'com.mailersend:java-sdk:1.0.0' ``` **Set your API key** ```java MailerSend ms = new MailerSend(); ms.setToken("YOUR_API_KEY"); ``` **Send an email** ```java Email email = new Email(); email.setFrom("Your Name", "you@yourdomain.com"); email.addRecipient("Recipient Name", "recipient@example.com"); email.subject = "Hello from MailerSend"; email.html = "

This is the HTML content

"; email.text = "This is the text content"; MailerSend ms = new MailerSend(); ms.setToken("YOUR_API_KEY"); MailerSendResponse response = ms.emails().send(email); System.out.println(response.responseStatusCode); ```
## What's next? [#whats-next] * SDK source on GitHub: * [mailersend-nodejs](https://github.com/mailersend/mailersend-nodejs) * [mailersend-php](https://github.com/mailersend/mailersend-php) * [mailersend-python](https://github.com/mailersend/mailersend-python) * [mailersend-go](https://github.com/mailersend/mailersend-go) * [mailersend-ruby](https://github.com/mailersend/mailersend-ruby) * [mailersend-java](https://github.com/mailersend/mailersend-java) * [Email API Reference](/api/v1/email) # Adding Attachments to Emails (/guides/adding-attachments-to-emails) MailerSend allows you to attach files to your emails to provide additional information or context for your recipients. In this guide, we'll walk you through the process of adding attachments to your emails using cURL calls. You can also use any of our SDKs. ## What do I need? [#what-do-i-need] * MailerSend account * Add and verify at least one sending domain * Generate an API token * Ensure you have cURL installed on your machine ## How do I add attachments to my email? [#how-do-i-add-attachments-to-my-email] Here’s an example request using cURL ```bash curl --request POST \ --url https://api.mailersend.com/v1/email \ --header 'Authorization: Bearer API_KEY_HERE' \ --header 'content-type: application/json' \ --data '{ "to": [ { "email": "recipient@email.com" } ], "from": { "email": "your@email.com" }, "subject": "New Attachment Test", "html": "

Hello world!

", "attachments": [ { "filename": "attachment.jpg", "content": "BASE64_ENCODED_CONTENT_HERE" } ] }' ``` * Copy and paste the cURL command into your terminal * Replace `from` , `to` , `API_KEY_HERE` and `BASE64_ENCODED_CONTENT_HERE` with your values * Press the enter key Note: * The `attachments` array includes information about the file you want to attach, such as the filename, and base64-encoded content. * You can also pass `"disposition": "inline" | "attachment"` to the attachment object. Use `inline` to make it accessible for content. Use `attachment` for normal attachments. * Attachment size cannot be more than `25MB` after decoding. * You can encode files using online services such as [Base64 guru](https://base64.guru/converter/encode) or [Base64 Encode](https://www.base64encode.org/) * For a complete list of supported file types, see [Supported File Types](https://developers.mailersend.com/api/v1/email.html#supported-file-types) ## What if my filetype is not supported by MailerSend? [#what-if-my-filetype-is-not-supported-by-mailersend] If your file type is not supported by MailerSend, you can use a file conversion tool to convert your file to a supported format and try again. There are many online conversion tools available that can help you convert files between different formats. Congratulations! You've now sent an email with an attachment via MailerSend's API using cURL. We're excited to have you on board and look forward to helping you integrate our service seamlessly into your application. If you have any questions or encounter any issues, don't hesitate to reach out to our support team for assistance. ## What’s next? [#whats-next] {/* - Scheduling emails */} * [Sending emails with MailerSend SDKs](/sdk) * [Setting up webhooks](/guides/setting-up-webhooks) * [Handling Maintenance Modes](/guides/handling-maintenance-modes) * [API Reference](/api/v1/email) # Checking your API quota (/guides/checking-api-quota) The `/v1/api-quota` endpoint reports how many requests you have remaining and when your limit resets. Requests to this endpoint do **not** count toward your quota. ```http GET https://api.mailersend.com/v1/api-quota ``` ```php use MailerSend\MailerSend; $mailersend = new MailerSend(); $mailersend->apiQuota->get(); ``` [More examples](https://github.com/mailersend/mailersend-php) ```javascript import 'dotenv/config'; import { MailerSend } from "mailersend"; const mailerSend = new MailerSend({ apiKey: process.env.API_KEY, }); mailerSend.apiQuota.get() .then((response) => console.log(response.body)) .catch((error) => console.log(error.body)); ``` [More examples](https://github.com/mailersend/mailersend-nodejs) ```python from mailersend import MailerSendClient ms = MailerSendClient() response = ms.api_quota.get_quota() ``` [More examples](https://github.com/mailersend/mailersend-python) ```go package main import ( "context" "log" "time" "github.com/mailersend/mailersend-go" ) var APIKey = "Api Key Here" func main() { // Create an instance of the mailersend client ms := mailersend.NewMailersend(APIKey) ctx := context.Background() ctx, cancel := context.WithTimeout(ctx, 5*time.Second) defer cancel() _, _, err := ms.ApiQuota.Get(ctx) if err != nil { log.Fatal(err) } } ``` [More examples](https://github.com/mailersend/mailersend-go) ```java import com.mailersend.sdk.MailerSend; import com.mailersend.sdk.apiquota.ApiQuota; import com.mailersend.sdk.exceptions.MailerSendException; public void GetApiQuota() { MailerSend ms = new MailerSend(); ms.setToken("api token"); try { ApiQuota quota = ms.apiQuota().getQuota(); System.out.println("Quota: " + quota.quota); System.out.println("Remaining: " + quota.remaining); System.out.println("Reset: " + quota.reset); } catch (MailerSendException e) { e.printStackTrace(); } } ``` [More examples](https://github.com/mailersend/mailersend-java) ```ruby require "mailersend-ruby" ms_api_quota = Mailersend::ApiQuota.new ms_api_quota.get ``` [More examples](https://github.com/mailersend/mailersend-ruby) ### Responses [#responses] #### Valid [#valid] ```json { "quota": 1000, "remaining": 752, "reset": "2023-04-15T00:00:00Z" } ``` #### Error [#error] ```http Response Code: 401 Unathorized ``` *See - [Validation errors](/../../general#validation-errors)* # Email Threads (/guides/creating-email-threads) Email threading, also known as email conversations or email chains, is a method used to organize and present related email messages as a cohesive thread or conversation. This feature is employed by email clients to simplify the management of ongoing discussions, making it easier for users to follow and understand the flow of communication. ## Key email Headers [#key-email-headers] 1. **In-Reply-To:** * The **`In-Reply-To`** header contains the message ID of the parent email to which the current email is a reply. This header helps email clients link replies to the original message and maintain the thread. 2. **References:** * The **`References`** header is similar to **`In-Reply-To`** and contains a list of message IDs that the current email is referencing. It helps in creating a complete chain of related messages in a thread. 3. **Subject:** * The **`Subject`** header often includes "Re:" (meaning "reply") or other prefixes to indicate that the email is part of an ongoing thread. The subject line may evolve as the conversation progresses. 4. **Message-ID:** * The **`Message-ID`** header uniquely identifies each email message. When you reply to an email, the new message typically includes the **`Message-ID`** of the original message in the **`In-Reply-To`** header. In this guide, we'll demonstrate how to leverage MailerSend to effectively reply to inbound emails and create a threaded conversation. Learn how to set the appropriate headers for seamless communication. ## What do I need? [#what-do-i-need] * MailerSend account * Generate an API token * Add and verify at least one sending domain * Add an inbound route with a webhook ## Set up an inbound route on your verified domain [#set-up-an-inbound-route-on-your-verified-domain] Let's take a moment to set up an inbound route in MailerSend, enabling your users to contact your Customer Support team for any technical challenges or general inquiries. This will streamline communication and ensure a seamless experience for your users. Add Inbound Route * Begin by logging into your MailerSend account. * Head to the `Email` section and locate `Domains.` * Choose the relevant domain and click on `Manage.` * Scroll down to find `Inbound Routing` and click on `Add an Inbound Route` button. * Provide a name for your inbound route and specify the webhook URL where you want to receive inbound email data. ## Send email to your Inbound address [#send-email-to-your-inbound-address] Now that your inbound route is set up, users can easily contact your support team using the provided inbound address. In this guide, we'll demonstrate using Microsoft Outlook, but feel free to choose any email client you're comfortable with. Let's proceed! Send email using outlook * Begin by logging into your preferred email client * Open a new email and address it to the provided `inbound address`. ## Reply to the Inbound email [#reply-to-the-inbound-email] To reply to the email and initiate a threaded conversation, it's crucial to include either the `Thread-Topic` or `Subject` from the inbound email data, along with the `Message-ID`. This ensures that users can effortlessly follow the context of the conversation without the need to search through individual messages. Inbound activity log You can get this information from the inbound activity log or same data sent to your webhook. * Navigate to **`Domains`** on the left-side menu. * Select your domain and click on `Manage` * Scroll down to `Inbound Routing` and choose your inbound route. * On the inbound details page, expand the `Forwarded` activity log. * Search for and copy the `Subject` and `Message-ID.` Now, let's use the MailerSend email API or any of the SDKs to seamlessly send the reply email. MailerSend Email API * Ensure a smooth thread continuation by setting the **`in_reply_to`** header parameter to the received **`Message-ID`** * Keep the `subject` the same or consider prefixing it with **`Re:`** to signify a reply * Proceed to submit the request to send the reply email through MailerSend’s email API or SDKs. * Open your email client app and navigate to your inbox. * Locate the received email and click to view it. Observe how the thread is now seamlessly created, streamlining your communication. Outlook Email Congratulations! You've successfully set up an inbound route and replied to an inbound email, creating a threaded conversation. This makes it easy for both users and our support team to track and follow conversations seamlessly. ## What’s next? [#whats-next] To ensure a comprehensive chain of related messages in a thread, consider passing the References header using MailerSend API, SMTP or SDKs. This valuable piece of information can also be extracted directly from the inbound email data. Inbound References By including the References header, you contribute to the seamless flow of conversation within the email thread. This additional step enhances the context and organization of your email communication. Feel free to explore this option to further optimize and enrich your threaded conversations in MailerSend. If you have any questions or need assistance, our support team is here to help! You can find more info on how to manage your inbound route from our [developer docs](https://developers.mailersend.com/api/v1/inbound.html#inbound-routing) {/* - Scheduling emails */} {/* - Handling Errors */} * [Sending emails with MailerSend SDKs](/sdk) * [Handling Maintenance Modes](/guides/handling-maintenance-modes) * [API Reference](/api/v1) # Customizing Email Content (/guides/customizing-email-content) Personalization is simple with MailerSend’s API. Simply add a structure for the appropriate variables and call them in the parameters. In this guide, we'll walk you through the process of sending a personalized email using cURL calls. You can also use any of our SDKs. ## What do I need? [#what-do-i-need] * MailerSend account * Add and verify at least one sending domain * Generate an API token * Ensure you have curl installed on your machine When sending emails using the MailerSend API, you can input basic data for each recipient using variables in the **`{{variable}}`** format. This allows you to personalize the **`subject`**, **`html`**, and **`text`** fields in your email. An example could be: “*Hi*\*`{{name}}`\*\*. Thank you for shopping with us all the way from \*\*`{{country}}**!`\*” ## Personalization email [#personalization-email] Here’s an example request using cURL ```bash curl --request POST \ --url https://api.mailersend.com/v1/email \ --header 'Authorization: Bearer API_KEY_HERE' \ --header 'content-type: application/json' \ --data '{ "to": [ { "email": "recipient@email.com" } ], "from": { "email": "your@email.com" }, "subject": "Personalization", "html": "

Hi {{name|default('there')}}, Thank you for shopping with us all the way from {{country}}.

", "personalization": [ { "email": "test@mailersend.com", "data": { "name": "Recipient name", "country": "Recipient Country" } } ] } ``` * Copy and paste the cURL command into your terminal * Replace `API_KEY_HERE` with your actual MailerSend API key and customize the other fields to match your needs * Finally, hit the enter key to execute the command. Notes about variables: * They must be surrounded by double curly brackets `{{var}}` * They may contain alphanumeric characters and underscores (\_) * They must not start with a number or underscore * They are case sensitive, meaning that `{{VAR}}` is different from `{{var}}` ### Examples of combinations: [#examples-of-combinations] | Syntax | Output | Details | | --------------------- | ------------ | ------------------------------------------------------------------ | | `{{var}}` | value | Display a simple variable (no array or object). | | `{{object.key}}` | object-value | Display the key value of an object. | | `{{number + number}}` | 4 | A simple calculation of two simple variables (no array or object). | Congratulations! You've now sent an email with personalization via MailerSend's API using cURL. We're excited to have you on board and look forward to helping you integrate our service seamlessly into your application. If you have any questions or encounter any issues, don't hesitate to contact our support team for assistance. ## What’s next? [#whats-next] {/* - Scheduling email */} * [Sending emails with MailerSend SDKs](/sdk) * [Setting up webhooks](/guides/setting-up-webhooks) * [Handling Maintenance Modes](/guides/handling-maintenance-modes) * [API Reference](/api/v1/email) # Handling Maintenance Modes (/guides/handling-maintenance-modes) ## Introduction [#introduction] System downtime can have a significant impact on email sending operations. Downtimes, whether planned or unexpected, can disrupt the flow of emails, potentially causing delays, missed opportunities, or confusion. For this reason, efficient handling of maintenance mode is not just a technical necessity but a business imperative. Handling the disruption to minimize its impact on end-users involves several steps, from receiving and processing webhooks for maintenance events, temporarily storing emails to be sent via API during maintenance, resuming email sending after receiving the maintenance end webhook, handling SMTP retries during maintenance, managing inbound email retries, and utilizing multiple or backup ESPs during maintenance. In this guide, we will take a detailed look at each step, providing practical advice and best practices to help you navigate maintenance mode so that you can maintain trust and reliability with your users. ## Understanding Webhooks for Maintenance Events [#understanding-webhooks-for-maintenance-events] In the context of maintenance events for MailerSend, webhooks signal the start and end of a maintenance period. These are the `maintenance.start` and `maintenance.end` webhooks. When a maintenance period begins, MailerSend will send a `maintenance.start` webhook to all the connected systems. Similarly, when the maintenance period ends, a `maintenance.end` webhook is sent out. These webhooks are crucial as they could trigger various processes to handle the maintenance period efficiently. Setting up and receiving these webhooks involves providing MailerSend with a URL in your system where the webhooks should be sent. You can do so via the [Create a webhook](https://developers.mailersend.com/api/v1/webhooks.html#create-a-webhook) endpoint and selecting the appropriate maintenance events. ## Processing Webhooks for Maintenance Events [#processing-webhooks-for-maintenance-events] Once you’ve set up your system to receive webhooks, the next step is to process them appropriately. This involves parsing the incoming webhook payload, validating it to ensure it's from a trusted source, and performing appropriate actions based on the webhook type. Here is a general outline of how you might set up a PHP script to handle this: ```php ### SMTP Username and Password [#smtp-username-and-password] 1. Log in to your [MailerSend dashboard](https://app.mailersend.com/dashboard). 2. Navigate to "Domains" in the left sidebar. 3. Select the affected domain name in the list. 4. Scroll down to the “SMTP” section and click the "Reset Password" button to create a new SMTP password. This will invalidate the old password and prevent unauthorized access using the leaked credentials. Reset SMTP password ## Remove the Leaked Credential from Git Repositories (GitHub, GitLab, etc.) [#remove-the-leaked-credential-from-git-repositories-github-gitlab-etc] Leaked credentials may remain in your repository's commit history even after being removed from your code's current version. To remove the leaked credentials from your Git history, follow these steps: 1. Clone the repository locally if you haven't already. 2. Use a tool like [BFG Repo-Cleaner](https://rtyley.github.io/bfg-repo-cleaner/) or [git-filter-repo](https://github.com/newren/git-filter-repo) to remove sensitive data from your repository's history. 3. Force-push the cleaned repository to overwrite the remote repository's history. Note that this may cause conflicts for other users, so communicate the changes to your team. You may also just remove the credentials from your Git repo if doing a complete cleanup isn’t feasible. ## Create New Credentials [#create-new-credentials] After removing and revoking the leaked credentials, generate new ones to regain access to MailerSend services. ### MailerSend API Token [#mailersend-api-token-1] 1. Return to the [MailerSend dashboard](https://app.mailersend.com/dashboard) and navigate to "Domains" in the left sidebar. 2. Select your domain name in the list. 3. Scroll to the "API Token" section and click the "Create new token" button. 4. Assign a name to the new token and select the necessary permissions. Create API Token ### SMTP Username and Password [#smtp-username-and-password-1] Use the new SMTP password you generated in the previous step. The SMTP username remains unchanged. ## Securely Store and Use the New Credentials [#securely-store-and-use-the-new-credentials] To prevent future leaks, store and use your new credentials securely. Here are some best practices: * Avoid hardcoding credentials in your source code * Use environment variables to store sensitive information and access them in your code * If you need to store credentials in a file, use a secure file format (such as .env) and add the file to your `.gitignore` to prevent it from being accidentally committed * Utilize a secret management service, such as HashiCorp Vault or AWS Secrets Manager, to securely store and manage sensitive information * Educate your team about the importance of credential security and best practices Following these steps, you can effectively remediate credential leaks and protect your MailerSend API tokens and SMTP credentials from unauthorized access. # Setting Up Webhooks (/guides/setting-up-webhooks) Webhooks are a way for MailerSend to notify your application or service when certain events occur, such as when an email is sent or opened. This allows your application to respond in real time to these events and take action based on the data provided by MailerSend. In this guide, we'll show you how to use MailerSend webhooks with your application. ## What do I need? [#what-do-i-need] * MailerSend account * Add and verify at least one sending domain * Generate an API token ## How do I set up a webhook? [#how-do-i-set-up-a-webhook] The first step is to create an endpoint in your application that can receive webhook events from MailerSend. This can be done using any web framework or language that can handle HTTP requests. The example below uses Node.js with Express: ```js const express = require('express'); const bodyParser = require('body-parser'); const app = express(); const port = 3000; app.use(bodyParser.urlencoded({ extended: true })); app.use(bodyParser.json()); app.post('/ms/webhook', (req, res) => { console.log(req.body); // Handle webhook event data here res.status(200).end(); // Always respond with a 200 status code }); app.listen(port, () => { console.log(`Example app listening at http://your_server.com:${port}`); }); ``` This creates a simple webhook endpoint at **`/ms/webhook`** that logs the incoming webhook data and responds with a 200 status code. ## Register the webhook with MailerSend [#register-the-webhook-with-mailersend] We need to provide the URL of our webhook endpoint to MailerSend and select which events we want to receive notifications for. For example, you might want to receive notifications when an email is `sent`, `opened`, or `clicked`. * Login into MailerSend * Navigate to Domains under the Email section * Click on Manage * Scroll down to `Webhooks` and click on `Add webhook` Add Webhook * Give your webhook a name * Enter your webhook URL, eg `http://your_server.com/ms/webhook` * Select the webhook version, we recommend using V2. * Select the events to receive notification for e.g., `activity.sent`, `activity.delivered` * Click on `Save webhook` Note: You can also register your webhook with MailerSend using our API or any of our SDKs. Check out examples [here](https://developers.mailersend.com/api/v1/webhooks.html#create-a-webhook). ## What now? [#what-now] Next is for you to handle the webhook events in your application. When MailerSend sends a webhook event to your endpoint, it will include a JSON payload with information about the event. For example, here's what an `activity.sent` event might look like: ```json { "type": "activity.sent", "created_at": "2025-08-05T21:23:54.000000Z", "data": { "id": "6892766a5b66e2daf3dc9155", "domain_id": "yv69oxl5kl785kw2", "message_id": "6892766ae78995a317577aa1", "email_id": "6892766a8d52ba62543d5e71", "type": "sent", "subject": "Test email", "email": "test@mailersend.com", "tags": ["test", "test2"], "meta": [] } } ``` Your application can then parse this JSON data and take action based on the event. For example, you might want to update your database to track which emails have been sent or opened. ```js app.post('/ms/webhook', (req, res) => { const event = req.body.type; const data = req.body.data; switch (event) { case 'activity.sent': console.log(`Email sent: ${data.email.subject}`); // Update database or take other action break; case 'activity.opened': console.log(`Email opened: ${data.email.subject}`); // Update database or take other action break; default: console.log(`Unknown event: ${event}`); } res.status(200).end(); }); ``` ## Handling failures [#handling-failures] If your endpoint goes down, MailerSend will retry delivery automatically with backoff for a few days. You'll receive notification emails as failures persist. If the endpoint stays down too long, the webhook will be paused. Re-enable it from your dashboard once you've fixed the issue. To minimize unnecessary retries, return a `2xx` response from your endpoint as quickly as possible and move heavy processing into a background job. Congratulations! You’ve set up a webhook in your application to trigger reactions based on events received from MailerSend automatically. We're excited to have you on board and look forward to helping you integrate our service seamlessly into your application. If you have any questions or encounter any issues, don't hesitate to contact our support team for assistance. ## What’s next? [#whats-next] You can find more info on how to manage and secure your webhooks from our [developer docs](https://developers.mailersend.com/api/v1/webhooks.html#webhooks-overview) {/* - Scheduling emails */} {/* - Handling Errors */} * [Sending emails with MailerSend SDKs](/sdk) * [Handling Maintenance Modes](/guides/handling-maintenance-modes) * [API Reference](/api/v1) # MailerSend MCP Use Cases (/mcp/examples) ## Email Management [#email-management] Your AI assistant handles critical emails with reliability and precision. ### Analytics & Insights: [#analytics--insights] * "Show me the delivery rate for emails sent in the last 24 hours" * "Which email templates have the highest open rates?" * "What's the average delivery time for password reset emails?" * "Show me any failed order confirmation emails from today" ### Actions & Creation: [#actions--creation] * **\[ACTION]** "Send a password reset email to [user@example.com](mailto:user@example.com) using the 'password-reset' template with reset\_link: [https://app.example.com/reset/abc123](https://app.example.com/reset/abc123)" * **\[ACTION]** "Send order confirmation emails to these 10 customers with their specific order details and tracking numbers" * **\[ACTION]** "Send a verification email to [new-user@example.com](mailto:new-user@example.com) with verification\_code: ABC123" * **\[ACTION]** "Send invoice #INV-2024-001 to [billing@customer.com](mailto:billing@customer.com) with the attached PDF" ## Domain & Deliverability Management [#domain--deliverability-management] Ensure your emails reach the inbox with proper domain configuration. ### Analytics & Insights: [#analytics--insights-1] * "Check the verification status of my sending domain" * "Show me the reputation score for api.mycompany.com" * "Are there any SPF/DKIM issues with my domain?" * "What's the bounce rate for my sending domain?" ### Actions & Creation: [#actions--creation-1] * **\[ACTION]** "Add api.mycompany.com as a new sending domain and give me the DNS records" * **\[ACTION]** "Verify the domain setup for app.mysite.com and check if all DNS records are properly configured" * **\[ACTION]** "Update domain settings to enable click tracking for notifications.mybrand.com" * **\[ACTION]** "Set up a dedicated IP pool for my high-volume domain" ## Message Tracking & Monitoring [#message-tracking--monitoring] Monitor your email delivery in real-time. ### Analytics & Insights: [#analytics--insights-2] * "Show me all emails sent in the last hour with their delivery status" * "Find all order confirmation emails that bounced today and show me the bounce reasons" * "What's the average delivery time for account verification emails?" * "Show me any emails stuck in queue" ### Actions & Creation: [#actions--creation-2] * **\[ACTION]** "Get detailed information about message ID xyz123 including all activity events" * **\[ACTION]** "Show me the delivery status of the password reset email sent to [user@example.com](mailto:user@example.com)" * **\[ACTION]** "List all failed emails from the last 2 hours" * **\[ACTION]** "Show me the full activity trail for the order confirmation sent to [customer@example.com](mailto:customer@example.com)" ## Email Verification [#email-verification] Verify emails before sending to protect your reputation. ### Analytics & Insights: [#analytics--insights-3] * "Check if this customer email is valid before sending their invoice" * "Show me invalid emails from today's send attempts" * "What percentage of account registration emails are going to invalid addresses?" ### Actions & Creation: [#actions--creation-3] * **\[ACTION]** "Verify [customer@example.com](mailto:customer@example.com) before sending their order confirmation" * **\[ACTION]** "Check if this list of customer emails are valid before importing" * **\[ACTION]** "Validate the email address from this new user registration" ## Webhooks for Real-time Events [#webhooks-for-real-time-events] Monitor email events as they happen. ### Analytics & Insights: [#analytics--insights-4] * "Show me all active webhooks" * "Which webhook endpoints are failing for delivery notifications?" * "How many bounce notifications were sent to our webhook today?" ### Actions & Creation: [#actions--creation-4] * **\[ACTION]** "Set up a webhook to notify [https://app.mysite.com/email-delivered](https://app.mysite.com/email-delivered) when emails are delivered" * **\[ACTION]** "Create a webhook for all bounce events to update our user database automatically" * **\[ACTION]** "Add a webhook that triggers on failed delivery to alert our support team" * **\[ACTION]** "Set up a webhook to track when invoices are opened by customers" ## Template Management [#template-management] Manage your email templates efficiently. ### Analytics & Insights: [#analytics--insights-5] * "Show me all templates and their usage statistics" * "Which templates have the best engagement?" * "List all templates used for account-related emails" * "Show me templates that include dynamic order variables" ### Actions & Creation: [#actions--creation-5] * **\[ACTION]** "Show me the HTML content of the 'order-confirmation' template" * **\[ACTION]** "Find the 'password-reset' template and check what variables it expects" * **\[ACTION]** "List all available templates" * **\[ACTION]** "Get the 'invoice' template details including personalization tags" ## Performance Analytics [#performance-analytics] Get insights into your email performance. ### Analytics & Insights: [#analytics--insights-6] * "Show me delivery rates for different types of emails" * "What's the open rate for password reset emails vs order confirmations?" * "Which emails have the fastest delivery times?" * "Show me email performance by hour of day" ### Actions & Creation: [#actions--creation-6] * **\[ACTION]** "Get activity logs for all emails sent today" * **\[ACTION]** "Generate a report on email performance this week" * **\[ACTION]** "Show me delivery statistics for invoice emails" * **\[ACTION]** "Analyze bounce reasons for failed emails" ## Common Workflows [#common-workflows] ### User Registration Flow [#user-registration-flow] 1. "Verify the email address provided during registration" 2. "Send a welcome email with account activation link" 3. "Track if the activation email was delivered" 4. "Monitor if the user clicked the activation link" ### Password Reset Flow [#password-reset-flow] 1. "Verify user exists with email address [user@example.com](mailto:user@example.com)" 2. "Send password reset email with secure token" 3. "Check delivery status of the reset email" 4. "Set up webhook to notify when link is clicked" ### Order Confirmation Flow [#order-confirmation-flow] 1. "Send order confirmation to [customer@example.com](mailto:customer@example.com) with order details" 2. "Track delivery status of the confirmation" 3. "Send shipping notification when order ships" 4. "Monitor if customer opened shipping notification" ### Critical Notification Setup [#critical-notification-setup] 1. "Add and verify dedicated domain" 2. "Set up webhooks for delivery and bounce events" 3. "Configure high-priority sending for critical alerts" 4. "Monitor delivery performance in real-time" ## Troubleshooting Email Delivery [#troubleshooting-email-delivery] ### Delivery Issues [#delivery-issues] * "Check why password reset emails to @company.com are bouncing" * "Show me all emails that failed in the last hour" * "What's causing delays in order confirmation delivery?" * "Analyze bounce patterns for emails" ### Authentication & Security [#authentication--security] * "Verify DKIM/SPF records for my domain" * "Check authentication status for critical email sends" * "Show me any authentication failures today" * "Ensure domain has proper security settings" # MailerSend MCP Server (/mcp) The MailerSend Model Context Protocol (MCP) server provides seamless integration with MailerSend's API. This server enables AI assistants to send emails and SMS, manage domains, templates, webhooks, suppressions, sender identities, users, and many other things through standardized MCP tools. ## How MCP Works [#how-mcp-works] The Model Context Protocol (MCP) is a standardized protocol for AI assistants to interact with external systems. Think of it as USB-C port for AI. You can connect multiple MCPs that talk to each-other and get things done for you. ## Connecting a Client [#connecting-a-client] You can connect any MCP-compatible client to the running server. The server supports a streamable HTTP endpoint up to the latest MCP server specifications. Usually, you would just add `https://mcp.mailersend.com/mcp` as a remote MCP address in any tooling that you are working with. ### Claude (desktop and web) [#claude-desktop-and-web] Open Claude (Desktop), go to Settings > Connectors, and then Add Custom Connector. Name can be whatever you want, but we suggest using MailerSend as name, and Remote MCP server URL is [https://mcp.mailersend.com/mcp](https://mcp.mailersend.com/mcp). Click connect and follow the login process. ### Claude Code [#claude-code] Execute this in terminal: ```bash claude mcp add --transport http mailersend https://mcp.mailersend.com/mcp ``` ### Gemini CLI [#gemini-cli] Add following lines in your `~/.gemini/settings.json` file: ```json { "mcpServers": { "mailersend": { "httpUrl": "https://mcp.mailersend.com/mcp", "timeout": 5000 } } } ``` ### VSCode [#vscode] You can use [one-click install](/vscode:mcp/install?%7B%22name%22%3A%22mailersend%22%2C%22gallery%22%3Afalse%2C%22url%22%3A%22https%3A%2F%2Fmcp.mailersend.com%2Fmcp%22%7D) to add it to VSCode. ### Cursor [#cursor] [![Install MCP Server](https://cursor.com/deeplink/mcp-install-dark.svg)](/cursor://anysphere.cursor-deeplink/mcp/install?name=MailerSend\&config=eyJ1cmwiOiJodHRwczovL21jcC5tYWlsZXJzZW5kLmNvbS9tY3AifQ==) ### ChatGPT [#chatgpt] *Eligibility: Available in beta to Pro and Plus accounts on the web.* * First, Enable developer mode: Go to: Settings → Connectors → Advanced → Developer mode. * Go to back to Connectors main screen, click **Create** next to Browse connectors and in the dialog that opens enter the following: Name: MailerLite Description: leave empty or fill as you wish MCP Server URL: [https://mcp.mailersend.com/mcp](https://mcp.mailersend.com/mcp) Authentication: OAuth Click on **I trust this application** checkbox and then click Create. It will guide you through the authentication process. In order to use connectors in conversations: Open a new convo, choose Developer mode from the Plus menu and select connectors. You may need to explore different prompting techniques to call the correct tools. # Available Tools [#available-tools] ## Email Management [#email-management] * **send\_email**: Send a single email with templates, personalization, and attachments * **send\_bulk\_email**: Send multiple emails in a single request * **get\_bulk\_email\_status**: Get the status of a bulk email send ## Domain Management [#domain-management] * **list\_domains**: List all sending domains * **get\_domain**: Get details of a specific domain * **add\_domain**: Add a new sending domain * **delete\_domain**: Delete a domain * **get\_domain\_recipients**: Get recipients for a domain * **update\_domain\_settings**: Update domain settings * **get\_dns\_records**: Get DNS records for domain verification * **verify\_domain**: Verify domain DNS configuration ## SMTP User Management [#smtp-user-management] * **list\_smtp\_users**: List SMTP users for a domain * **get\_smtp\_user**: Get details of a specific SMTP user * **create\_smtp\_user**: Add a new SMTP user to a domain * **update\_smtp\_user**: Update an SMTP user * **delete\_smtp\_user**: Delete an SMTP user ## Message Management [#message-management] * **list\_messages**: List sent messages with filtering * **get\_message**: Get details of a specific message * **list\_scheduled\_messages**: List scheduled messages * **get\_scheduled\_message**: Get details of a scheduled message * **delete\_scheduled\_message**: Delete/cancel a scheduled message ## Template Management [#template-management] * **list\_templates**: List email templates * **get\_template**: Get template details and content * **create\_template**: Create a new email template * **update\_template**: Update an email template (API-created templates only) * **delete\_template**: Delete a template ## Webhook Management [#webhook-management] * **list\_webhooks**: List all webhooks * **get\_webhook**: Get webhook details * **create\_webhook**: Create a new webhook * **update\_webhook**: Update webhook configuration * **delete\_webhook**: Delete a webhook ## Inbound Routing [#inbound-routing] * **list\_inbound\_routes**: List inbound routes * **get\_inbound\_route**: Get inbound route details * **create\_inbound\_route**: Add a new inbound route to a domain * **update\_inbound\_route**: Update an inbound route * **delete\_inbound\_route**: Delete an inbound route ## Recipient Management [#recipient-management] * **list\_recipients**: List recipients in your account * **get\_recipient**: Get recipient details * **delete\_recipient**: Delete a recipient ## Suppression Management [#suppression-management] * **list\_blocklist**: List blocklist entries (account or domain) * **list\_hard\_bounces**: List hard-bounced recipients * **list\_spam\_complaints**: List spam complaints * **list\_unsubscribes**: List unsubscribed recipients * **list\_on\_hold**: List on-hold recipients * **add\_to\_blocklist**: Add recipients or patterns to the blocklist * **add\_to\_hard\_bounces**: Add a hard bounce for recipients * **add\_to\_spam\_complaints**: Add a spam complaint for recipients * **add\_to\_unsubscribes**: Set recipients as unsubscribed * **delete\_from\_blocklist**: Delete blocklist entries * **delete\_from\_hard\_bounces**: Delete hard bounce entries * **delete\_from\_spam\_complaints**: Delete spam complaint entries * **delete\_from\_unsubscribes**: Delete unsubscribe entries * **delete\_from\_on\_hold**: Delete on-hold entries ## Activity Management [#activity-management] * **list\_activities**: List email activity events * **get\_activity**: Get specific activity details ## Analytics Management [#analytics-management] * **get\_analytics\_by\_date**: Get email analytics by date range * **get\_analytics\_by\_country**: Get email opens grouped by country * **get\_analytics\_by\_user\_agent\_name**: Get email opens grouped by user-agent name * **get\_analytics\_by\_user\_agent\_type**: Get email opens grouped by user-agent type ## Email Verification [#email-verification] * **verify\_email**: Verify single email address * **verify\_email\_async**: Start async email verification * **get\_async\_verification\_status**: Check async verification status * **list\_verification\_lists**: List email verification lists * **get\_verification\_list**: Get verification list details * **create\_verification\_list**: Create new verification list * **verify\_list**: Start list verification * **get\_verification\_results**: Get verification results ## DMARC Monitoring [#dmarc-monitoring] * **list\_dmarc\_monitors**: List DMARC monitors * **create\_dmarc\_monitor**: Create a DMARC monitor for a verified domain * **update\_dmarc\_monitor**: Update a DMARC monitor's wanted record * **delete\_dmarc\_monitor**: Delete a DMARC monitor * **get\_dmarc\_aggregated\_report**: Get aggregated reports (per IP) * **get\_dmarc\_ip\_report**: Get detailed reports for a specific IP * **get\_dmarc\_report\_sources**: List reporting organizations for a monitor * **favorite\_dmarc\_ip**: Mark an IP as a favorite * **unfavorite\_dmarc\_ip**: Remove an IP from favorites ## Blocklist Monitoring [#blocklist-monitoring] * **list\_blocklist\_monitors**: List blocklist monitors * **get\_blocklist\_monitor**: Get monitor details and current hits * **create\_blocklist\_monitor**: Create a monitor for a domain, IP, or CIDR block * **update\_blocklist\_monitor**: Update a monitor's name or notification settings * **delete\_blocklist\_monitor**: Delete a blocklist monitor ## Token Management [#token-management] * **list\_tokens**: List API tokens * **get\_token**: Get API token details * **create\_token**: Create an API token with scopes * **update\_token**: Update a token's name and/or status * **delete\_token**: Delete an API token ## User & Invite Management [#user--invite-management] * **list\_users**: List account users * **get\_user**: Get user details * **invite\_user**: Invite a new user * **update\_user**: Update a user's role, permissions, templates, or domains * **delete\_user**: Delete a user * **list\_invites**: List pending user invites * **get\_invite**: Get invite details * **resend\_invite**: Resend a pending invite * **cancel\_invite**: Cancel a pending invite ## Sender Identity Management [#sender-identity-management] * **list\_identities**: List sender identities * **create\_identity**: Add a new sender identity * **get\_identity**: Get identity details by ID * **update\_identity**: Update an identity by ID * **delete\_identity**: Delete an identity by ID * **get\_identity\_by\_email**: Get identity details by email * **update\_identity\_by\_email**: Update an identity by email * **delete\_identity\_by\_email**: Delete an identity by email * **resend\_identity**: Resend the verification email for an identity ## SMS [#sms] * **send\_sms**: Send an SMS message ## SMS Messages [#sms-messages] * **list\_sms\_messages**: List SMS messages * **get\_sms\_message**: Get an SMS message with sub-messages and activity ## SMS Activity [#sms-activity] * **list\_sms\_activity**: List SMS activity, filterable by number/date/status ## SMS Numbers [#sms-numbers] * **list\_sms\_numbers**: List SMS phone numbers * **get\_sms\_number**: Get SMS phone number details * **update\_sms\_number**: Update an SMS number (e.g. pause/unpause) * **delete\_sms\_number**: Delete an SMS number ## SMS Recipients [#sms-recipients] * **list\_sms\_recipients**: List SMS recipients * **get\_sms\_recipient**: Get SMS recipient details * **update\_sms\_recipient**: Update an SMS recipient's status ## SMS Webhooks [#sms-webhooks] * **list\_sms\_webhooks**: List SMS webhooks for a number * **get\_sms\_webhook**: Get SMS webhook details * **create\_sms\_webhook**: Create an SMS webhook * **update\_sms\_webhook**: Update an SMS webhook * **delete\_sms\_webhook**: Delete an SMS webhook ## SMS Inbound [#sms-inbound] * **list\_sms\_inbounds**: List SMS inbound routes * **get\_sms\_inbound**: Get SMS inbound route details * **create\_sms\_inbound**: Add an SMS inbound route * **update\_sms\_inbound**: Update an SMS inbound route * **delete\_sms\_inbound**: Delete an SMS inbound route ## Search & Fetch [#search--fetch] * **search**: Search across resources * **fetch**: Fetch related data ## Feedback [#feedback] We are always eager about feedback of the exciting things we are working on. If you have feedback about our MCP, feel free to send an email to [mcp@mailersend.com](mailto:mcp@mailersend.com). # MailerSend CLI (/tools/cli) A command-line interface for the MailerSend API. Send emails and SMS, manage domains, templates, webhooks, recipients, suppressions, and more — all from your terminal. The CLI also includes an interactive TUI dashboard for monitoring your email activity, analytics, domains, and suppressions in real time. [GitHub Repository](https://github.com/mailersend/mailersend-cli) ## Installation [#installation] ### Homebrew (macOS) [#homebrew-macos] ```bash brew install --cask mailersend/tap/mailersend ``` ### GitHub Releases [#github-releases] Download pre-built binaries for Linux, macOS, and Windows from the [releases page](https://github.com/mailersend/mailersend-cli/releases). ### Go install [#go-install] ```bash go install github.com/mailersend/mailersend-cli@latest ``` ### From source [#from-source] Requires Go 1.25+. ```bash git clone https://github.com/mailersend/mailersend-cli.git cd mailersend-cli go build -o mailersend . ``` Move the binary to somewhere on your `$PATH`: ```bash sudo mv mailersend /usr/local/bin/ ``` ### Nix [#nix] Run directly without installing: ```bash nix run git+ssh://git@github.com/mailersend/mailersend-cli.git ``` Or install into your profile: ```bash nix profile install git+ssh://git@github.com/mailersend/mailersend-cli.git ``` ## Authentication [#authentication] The CLI supports two authentication methods: **OAuth** (recommended) and **API token**. ### OAuth (recommended) [#oauth-recommended] ```bash mailersend auth login ``` This opens your browser to authorize the CLI with your MailerSend account. OAuth tokens are automatically refreshed when they expire. ### API Token [#api-token] ```bash mailersend auth login --method token ``` You'll be prompted to enter your MailerSend API token. You can generate one from your [MailerSend dashboard](https://www.mailersend.com/) under API Tokens. ### Environment variable [#environment-variable] You can also set the API token via environment variable: ```bash export MAILERSEND_API_TOKEN="mlsn.your_token_here" ``` Token resolution order: `MAILERSEND_API_TOKEN` env var > `--profile` flag > active profile > first profile. ### Multiple profiles [#multiple-profiles] Manage multiple profiles for different accounts or environments: ```bash # Add profiles mailersend profile add --name staging mailersend profile add --name production # List profiles mailersend profile list # Switch active profile mailersend profile switch staging # Use a specific profile for one command mailersend domain list --profile production ``` ### Auth status and logout [#auth-status-and-logout] ```bash # Check auth status mailersend auth status # Log out mailersend auth logout ``` ## Global flags [#global-flags] Every command supports these flags: | Flag | Description | | ------------------ | ------------------------------------------- | | `--json` | Output raw JSON instead of formatted tables | | `--verbose`, `-v` | Print HTTP request and response details | | `--profile ` | Use a specific auth profile | | `--help`, `-h` | Show help for any command | ## Commands [#commands] ### Email [#email] ```bash # Send an email mailersend email send \ --from "sender@yourdomain.com" \ --from-name "Sender Name" \ --to "recipient@example.com" \ --to-name "Recipient" \ --subject "Hello" \ --text "Plain text body" \ --html "

HTML body

" # Send from a file mailersend email send \ --from "sender@yourdomain.com" \ --to "recipient@example.com" \ --subject "Newsletter" \ --html-file ./newsletter.html \ --text-file ./newsletter.txt # Send using a template mailersend email send \ --from "sender@yourdomain.com" \ --to "recipient@example.com" \ --template-id "x2p0347z969lzdrn" # Schedule an email (unix timestamp) mailersend email send \ --from "sender@yourdomain.com" \ --to "recipient@example.com" \ --subject "Scheduled" \ --text "This is scheduled" \ --send-at 1735689600 # With tracking and tags mailersend email send \ --from "sender@yourdomain.com" \ --to "recipient@example.com" \ --subject "Tracked" \ --text "Body" \ --track-opens --track-clicks \ --tags "campaign,welcome" ``` #### Send email flags [#send-email-flags] | Flag | Type | Required | Description | | ----------------- | ------ | -------- | ------------------------------------------------------------------------------------- | | `--from` | string | yes\* | Sender email address. \*Not required if `--template-id` is set with a default sender. | | `--from-name` | string | no | Sender display name | | `--to` | string | yes | Recipient email address | | `--to-name` | string | no | Recipient display name | | `--cc` | string | no | CC email address | | `--bcc` | string | no | BCC email address | | `--reply-to` | string | no | Reply-to email address | | `--subject` | string | yes\* | Email subject. \*Not required if `--template-id` is set with a default subject. | | `--text` | string | yes\* | Plain text body. \*Only required if no `--html` or `--template-id` is present. | | `--html` | string | yes\* | HTML body. \*Only required if no `--text` or `--template-id` is present. | | `--html-file` | string | no | Path to file containing HTML body | | `--text-file` | string | no | Path to file containing plain text body | | `--template-id` | string | yes\* | Template ID. \*Only required if no `--text` or `--html` is present. | | `--tags` | string | no | Comma-separated email tags | | `--send-at` | int | no | Unix timestamp for scheduled sending (max now + 72 hours) | | `--track-clicks` | bool | no | Enable click tracking | | `--track-opens` | bool | no | Enable open tracking | | `--track-content` | bool | no | Enable content tracking | ### Bulk email [#bulk-email] ```bash # Send bulk email from a JSON file mailersend bulk-email send --file emails.json # Check bulk email status mailersend bulk-email status ``` The JSON file should contain an array of email objects matching the [email API request format](/api/v1/email#send-an-email): ```json [ { "from": {"email": "sender@yourdomain.com"}, "to": [{"email": "recipient1@example.com"}], "subject": "Bulk Email 1", "text": "Hello from bulk" }, { "from": {"email": "sender@yourdomain.com"}, "to": [{"email": "recipient2@example.com"}], "subject": "Bulk Email 2", "text": "Hello from bulk" } ] ``` ### Domains [#domains] ```bash # List domains mailersend domain list mailersend domain list --limit 10 --verified # Get domain details mailersend domain get yourdomain.com # Add a new domain mailersend domain add --name yourdomain.com # Show DNS records mailersend domain dns yourdomain.com # Verify domain mailersend domain verify yourdomain.com # Update domain settings mailersend domain update-settings yourdomain.com \ --track-clicks --track-opens # Delete a domain mailersend domain delete yourdomain.com ``` ### Recipients [#recipients] ```bash # List recipients mailersend recipient list --limit 20 # List recipients for a specific domain mailersend recipient list --domain yourdomain.com # Get recipient details mailersend recipient get # Delete a recipient mailersend recipient delete ``` ### Sender identities [#sender-identities] ```bash # List identities mailersend identity list --limit 10 mailersend identity list --domain yourdomain.com # Create an identity mailersend identity create \ --domain yourdomain.com \ --name "Support" \ --email "support@yourdomain.com" # Get identity (by ID or email) mailersend identity get mailersend identity get support@yourdomain.com # Update an identity mailersend identity update --name "Customer Support" # Delete an identity mailersend identity delete ``` ### Templates [#templates] ```bash # List templates mailersend template list mailersend template list --limit 10 --domain yourdomain.com # Get template details mailersend template get # Delete a template mailersend template delete ``` ### Messages [#messages] ```bash # List messages mailersend message list --limit 10 # Get message details mailersend message get # List scheduled messages mailersend message scheduled list --domain yourdomain.com # Get scheduled message mailersend message scheduled get # Cancel a scheduled message mailersend message scheduled delete ``` ### Activity [#activity] ```bash # List activity for a domain mailersend activity list \ --domain yourdomain.com \ --date-from 2025-01-01 \ --date-to 2025-01-31 # Filter by event type mailersend activity list \ --domain yourdomain.com \ --date-from 2025-01-01 \ --date-to 2025-01-31 \ --event delivered,opened # Get activity details mailersend activity get ``` ### Analytics [#analytics] ```bash # Analytics by date mailersend analytics date \ --date-from 2025-01-01 \ --date-to 2025-01-31 \ --event sent,delivered,opened \ --group-by days # Analytics by country mailersend analytics country \ --date-from 2025-01-01 \ --date-to 2025-01-31 # Analytics by user agent name mailersend analytics ua-name \ --date-from 2025-01-01 \ --date-to 2025-01-31 # Analytics by user agent type mailersend analytics ua-type \ --date-from 2025-01-01 \ --date-to 2025-01-31 ``` ### Webhooks [#webhooks] ```bash # List webhooks mailersend webhook list --domain yourdomain.com # Create a webhook mailersend webhook create \ --domain yourdomain.com \ --name "My Webhook" \ --url "https://example.com/webhook" \ --events "activity.sent,activity.delivered" # Get webhook details mailersend webhook get # Update a webhook mailersend webhook update --name "Updated Webhook" # Delete a webhook mailersend webhook delete ``` ### Suppressions [#suppressions] Manage blocklist, hard bounces, spam complaints, unsubscribes, and on-hold entries. ```bash # List suppressions (works for all types) mailersend suppression blocklist list --limit 10 mailersend suppression hard-bounces list --limit 10 mailersend suppression spam-complaints list --limit 10 mailersend suppression unsubscribes list --limit 10 mailersend suppression on-hold list --limit 10 # Filter by domain mailersend suppression blocklist list --domain yourdomain.com # Add to blocklist (by recipient email) mailersend suppression blocklist add \ --domain yourdomain.com \ --recipients "spam@example.com" # Add to blocklist (by pattern) mailersend suppression blocklist add \ --domain yourdomain.com \ --patterns "*@spamdomain.com" # Add hard bounce / spam complaint / unsubscribe mailersend suppression hard-bounces add \ --domain yourdomain.com \ --recipients "bounce@example.com" # Delete specific entries mailersend suppression blocklist delete --ids id1,id2 # Delete all entries for a domain mailersend suppression blocklist delete --all --domain yourdomain.com ``` ### Inbound routes [#inbound-routes] ```bash # List inbound routes mailersend inbound list --domain yourdomain.com --limit 10 # Create an inbound route mailersend inbound create \ --domain yourdomain.com \ --name "My Inbound Route" \ --match-filter-type match_all \ --inbound-domain yourdomain.com \ --inbound-priority 0 \ --catch-filter-type catch_all \ --forwards "https://example.com/inbound" # Get route details mailersend inbound get # Update a route mailersend inbound update --name "Updated Route" # Delete a route mailersend inbound delete ``` ### API tokens [#api-tokens] ```bash # List tokens mailersend token list --limit 10 # Get token details mailersend token get # Create a token mailersend token create \ --name "My Token" \ --domain yourdomain.com \ --scopes "email_full,domains_read" # Update token name mailersend token update --name "Renamed Token" # Pause / unpause a token mailersend token update-status --status pause mailersend token update-status --status unpause # Delete a token mailersend token delete ``` ### Account users [#account-users] ```bash # List users mailersend user list # Get user details mailersend user get # Update a user mailersend user update --role admin # Delete a user mailersend user delete # List invites mailersend user invite list # Create an invite mailersend user invite create --email "newuser@example.com" --role "custom" # Get invite details mailersend user invite get # Resend an invite mailersend user invite resend # Cancel an invite mailersend user invite cancel ``` ### SMTP users [#smtp-users] All SMTP commands require `--domain`. ```bash # List SMTP users mailersend smtp list --domain yourdomain.com # Get SMTP user details mailersend smtp get --domain yourdomain.com # Create an SMTP user mailersend smtp create --domain yourdomain.com --name "My SMTP User" # Update an SMTP user mailersend smtp update \ --domain yourdomain.com \ --name "Updated SMTP" # Delete an SMTP user mailersend smtp delete --domain yourdomain.com ``` ### Email verification [#email-verification] ```bash # Verify a single email mailersend verification verify user@example.com # Verify asynchronously mailersend verification verify-async user@example.com # Check async verification status mailersend verification status # List verification lists mailersend verification list list # Get verification list details mailersend verification list get # Create a verification list mailersend verification list create \ --name "My List" \ --emails "user1@example.com,user2@example.com" # Create from a file (one email per line) mailersend verification list create \ --name "My List" \ --emails-file ./emails.txt # Start verification mailersend verification list verify # Start and wait for completion mailersend verification list verify --wait # Get verification results mailersend verification list results # Filter by status mailersend verification list results --status valid ``` ### API quota [#api-quota] ```bash mailersend quota ``` ### SMS [#sms] SMS commands require SMS to be enabled on your MailerSend account. #### Send SMS [#send-sms] ```bash mailersend sms send \ --from "+1234567890" \ --to "+0987654321" \ --text "Hello from CLI" ``` #### SMS messages [#sms-messages] ```bash mailersend sms message list --limit 10 mailersend sms message get ``` #### SMS phone numbers [#sms-phone-numbers] ```bash mailersend sms number list --limit 10 mailersend sms number get mailersend sms number update --paused mailersend sms number update --paused=false mailersend sms number delete ``` #### SMS activity [#sms-activity] ```bash mailersend sms activity list --limit 10 mailersend sms activity list \ --sms-number-id \ --date-from 2025-01-01 \ --date-to 2025-12-31 ``` #### SMS recipients [#sms-recipients] ```bash mailersend sms recipient list --limit 10 mailersend sms recipient get mailersend sms recipient update --status opt_out ``` #### SMS inbound routes [#sms-inbound-routes] ```bash mailersend sms inbound list --limit 10 mailersend sms inbound create \ --sms-number-id \ --name "My SMS Route" \ --forward-url "https://example.com/sms-hook" mailersend sms inbound get mailersend sms inbound update --name "Updated SMS Route" mailersend sms inbound delete ``` #### SMS webhooks [#sms-webhooks] ```bash mailersend sms webhook list --sms-number-id mailersend sms webhook create \ --sms-number-id \ --name "My SMS Webhook" \ --url "https://example.com/sms-webhook" \ --events "sms.sent,sms.delivered" mailersend sms webhook get mailersend sms webhook update --name "Updated SMS Webhook" mailersend sms webhook delete ``` ### Interactive dashboard [#interactive-dashboard] Launch the TUI dashboard for a visual overview of your MailerSend account: ```bash mailersend dashboard ``` The dashboard provides real-time views for domains, activity, analytics, messages, and suppressions — all navigable with keyboard shortcuts. ## Domain name resolution [#domain-name-resolution] Any flag that accepts `--domain` will accept both a domain name (e.g. `yourdomain.com`) or a raw domain ID (e.g. `q3enl6kk0z042vwr`). When a domain name is provided, it is automatically resolved to the corresponding ID. ## JSON output [#json-output] Add `--json` to any command to get raw JSON output, useful for scripting and piping to tools like `jq`: ```bash # Pipe to jq mailersend domain list --json | jq '.[].name' # Extract an ID mailersend identity create \ --domain yourdomain.com \ --name "Test" \ --email "test@yourdomain.com" \ --json | jq -r '.data.id' ``` The CLI also respects the `NO_COLOR` environment variable to disable colored output. ## Shell completion [#shell-completion] Generate shell completions for your shell: ```bash # Bash source <(mailersend completion bash) # Zsh mailersend completion zsh > "${fpath[1]}/_mailersend" # Fish mailersend completion fish | source # PowerShell mailersend completion powershell | Out-String | Invoke-Expression ``` # Helpful Tools (/tools) ## Bounce testing [#bounce-testing] We are offering a few inboxes that will automatically respond with pre-defined error codes so that developers can more thoroughly test their implemenation with MailerSend (webhooks, etc.). The emails sent will count towards quota, but the results from said inboxes are not added to deliverability scores for accounts using them. | Email Address | SMTP Error Code | Reason | | --------------------------------------------------------------------------------------- | --------------- | -------------------------------------------------------------------------------------------------------------------- | | [hard-bounce@bounce-test.mailersend.net](mailto:hard-bounce@bounce-test.mailersend.net) | 550 | User's mailbox was unavailable (such as not found) | | [soft-bounce@bounce-test.mailersend.net](mailto:soft-bounce@bounce-test.mailersend.net) | 421 | The service is not available and the connection will be closed. | | [blocked@bounce-test.mailersend.net](mailto:blocked@bounce-test.mailersend.net) | 554 | The transaction has failed (or you're not allowed to send to this recipient). | | [transient@bounce-test.mailersend.net](mailto:transient@bounce-test.mailersend.net) | 450 | Requested mail action not taken: mailbox unavailable (e.g., mailbox busy or temporarily blocked for policy reasons). | | [dns-error@bounce-test.mailersend.net](mailto:dns-error@bounce-test.mailersend.net) | 450 | Requested mail action not taken: DNS error | | [dmarc@bounce-test.mailersend.net](mailto:dmarc@bounce-test.mailersend.net) | 550 | A DMARC policy issue. The recipient server did not accept our requests to connect. | # Blocklist Monitoring (/api/v1/account/blocklist-monitoring) Monitor your sending domains and IP addresses for blocklist hits. Create monitors for individual domains, single IPs, or entire CIDR ranges, configure notification endpoints, and track whether your addresses appear on any blocklists. ## List monitors [#list-monitors] If you want to retrieve a list of your blocklist monitors, use this `GET` request: ```http GET https://api.mailersend.com/v1/blocklist-monitoring ``` #### Request parameters \[!toc] [#request-parameters-toc] | Query parameter | Type | Required | Limitations | Details | | --------------- | --------- | -------- | ------------------------------------------------------------ | ------------------------- | | `limit` | `integer` | no | Min: `1`, Max: `100` | Default: `25` | | `page` | `integer` | no | Min: `1` | | | `query` | `string` | no | Max: `255` chars | Search by name or address | | `sort_by` | `string` | no | `name`, `address`, `created_at`, `updated_at`, `blocklisted` | Default: `created_at` | | `order` | `string` | no | `asc`, `desc` | Default: `desc` | ### Responses [#responses] #### Valid [#valid] ```http Response Code: 200 OK Response Headers: content-type: application/json ``` ```json { "data": [ { "id": "5d3e1c9f8b2a4d71", "name": "My Domain", "address": "example.com", "type": "domain", "in_progress": false, "notify": true, "blocklisted": false, "last_checks_count": 82, "last_check": "2026-03-28T12:00:00.000000Z", "next_check": "2026-03-29T12:00:00.000000Z", "has_children": false, "forwards": [ { "id": "a1b2c3d4e5f6", "type": "email", "value": "admin@example.com" } ], "created_at": "2026-01-15T08:00:00.000000Z", "updated_at": "2026-03-28T12:00:00.000000Z" } ] } ``` #### Error [#error] ```http Response Code: 422 Unprocessable Entity ``` *See - [Validation errors](/../../general#validation-errors)* ## Get a monitor [#get-a-monitor] If you want to retrieve information about a specific blocklist monitor, use this `GET` request: ```http GET https://api.mailersend.com/v1/blocklist-monitoring/{monitor_id} ``` #### Request parameters \[!toc] [#request-parameters-toc-1] | URL parameter | Type | Required | Limitations | Details | | ------------- | -------- | -------- | ----------- | ------- | | `monitor_id` | `string` | yes | | | ### Responses [#responses-1] #### Valid — single monitor (domain or IP) [#valid--single-monitor-domain-or-ip] For monitors where `has_children` is `false`, the response includes a `hits` array showing current blocklist hits. ```http Response Code: 200 OK Response Headers: content-type: application/json ``` ```json { "data": { "id": "5d3e1c9f8b2a4d71", "name": "My Domain", "address": "example.com", "type": "domain", "in_progress": false, "notify": true, "blocklisted": true, "last_checks_count": 82, "last_check": "2026-03-28T12:00:00.000000Z", "next_check": "2026-03-29T12:00:00.000000Z", "has_children": false, "forwards": [ { "id": "a1b2c3d4e5f6", "type": "email", "value": "admin@example.com" } ], "hits": [ { "blocklist_host": "zen.spamhaus.org", "address": "example.com", "listed_at": "2026-03-20T08:00:00.000000Z", "delisted_at": null, "last_checked_at": "2026-03-28T12:00:00.000000Z" } ], "created_at": "2026-01-15T08:00:00.000000Z", "updated_at": "2026-03-28T12:00:00.000000Z" } } ``` #### Valid — IP range monitor [#valid--ip-range-monitor] For monitors where `has_children` is `true` (created from a CIDR block), the response includes a `children` array with all child monitors and their current status. No `hits` array is returned. ```http Response Code: 200 OK Response Headers: content-type: application/json ``` ```json { "data": { "id": "9ae4f7b1c3d2e501", "name": "My IP Range", "address": "192.0.2.0", "type": "ip", "in_progress": false, "notify": true, "blocklisted": true, "last_checks_count": 246, "last_check": "2026-03-28T12:00:00.000000Z", "next_check": "2026-03-29T12:00:00.000000Z", "has_children": true, "children_count": 3, "forwards": [ { "id": "b2c3d4e5f601", "type": "webhook", "value": "https://example.com/hook" } ], "children": [ { "id": "c3d4e5f60102", "name": "192.0.2.1", "address": "192.0.2.1", "type": "ip", "in_progress": false, "notify": false, "blocklisted": true, "last_checks_count": 82, "last_check": "2026-03-28T12:00:00.000000Z", "next_check": "2026-03-29T12:00:00.000000Z", "has_children": false, "forwards": [], "created_at": "2026-01-15T08:00:00.000000Z", "updated_at": "2026-03-28T12:00:00.000000Z" } ], "created_at": "2026-01-15T08:00:00.000000Z", "updated_at": "2026-03-28T12:00:00.000000Z" } } ``` #### Error [#error-1] ```http Response Code: 404 Not Found ``` ## Create a monitor [#create-a-monitor] If you want to create a new blocklist monitor, use this `POST` request: ```http POST https://api.mailersend.com/v1/blocklist-monitoring ``` #### Request parameters \[!toc] [#request-parameters-toc-2] *JSON parameters are provided in dot notation* | JSON parameter | Type | Required | Limitations | Details | | ---------------- | --------- | -------- | --------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `address` | `string` | yes | Max: `255` chars | Domain name, IP address, or CIDR block (e.g. `192.0.2.0/24`). Domains must be verified sending domains on the account. IPv4 CIDR: `/24`–`/32`. IPv6 CIDR: `/120`–`/128`. Each address can only be monitored once. | | `name` | `string` | no | Max: `255` chars | Display name. Defaults to the address value. | | `notify` | `boolean` | no | | Whether to send notifications when a blocklist hit is detected. | | `notify_email` | `string` | no | Valid email. Max: `255`. Required if `notify` is `true` and `notify_address` is absent. | Email address to notify. | | `notify_address` | `string` | no | Valid URL. Max: `500`. Required if `notify` is `true` and `notify_email` is absent. | Webhook URL to notify. | ### Request body \[!toc] [#request-body-toc] ```json { "address": "example.com", "name": "My Domain", "notify": true, "notify_email": "admin@example.com" } ``` ### Responses [#responses-2] #### Valid [#valid-1] ```http Response Code: 201 CREATED Response Headers: content-type: application/json ``` ```json { "data": { "id": "5d3e1c9f8b2a4d71", "name": "My Domain", "address": "example.com", "type": "domain", "in_progress": true, "notify": true, "blocklisted": false, "last_checks_count": 0, "last_check": null, "next_check": null, "has_children": false, "forwards": [ { "id": "a1b2c3d4e5f6", "type": "email", "value": "admin@example.com" } ], "created_at": "2026-03-30T10:00:00.000000Z", "updated_at": "2026-03-30T10:00:00.000000Z" } } ``` When creating a monitor for a CIDR block, one parent monitor and one child monitor per IP in the range are created automatically. The `in_progress` field will be `true` while the initial check is running. **IP range example request:** ```json { "address": "192.0.2.0/30", "name": "My IP Range" } ``` **IP range example response:** ```json { "data": { "id": "9ae4f7b1c3d2e501", "name": "My IP Range", "address": "192.0.2.0", "type": "ip", "in_progress": true, "notify": false, "blocklisted": false, "last_checks_count": 0, "last_check": null, "next_check": null, "has_children": true, "children_count": 4, "forwards": [], "created_at": "2026-03-30T10:00:00.000000Z", "updated_at": "2026-03-30T10:00:00.000000Z" } } ``` #### Error [#error-2] ```http Response Code: 422 Unprocessable Entity ``` *See - [Validation errors](/../../general#validation-errors)* ## Update a monitor [#update-a-monitor] If you want to update an existing blocklist monitor, use this `PUT` request: ```http PUT https://api.mailersend.com/v1/blocklist-monitoring/{monitor_id} ``` #### Request parameters \[!toc] [#request-parameters-toc-3] | URL parameter | Type | Required | Limitations | Details | | ------------- | -------- | -------- | ----------- | ------- | | `monitor_id` | `string` | yes | | | *JSON parameters are provided in dot notation* | JSON parameter | Type | Required | Limitations | Details | | ---------------- | --------- | -------- | --------------------------------------------------------------------------------------- | -------------------------------- | | `name` | `string` | no | Max: `255` chars | New display name. | | `notify` | `boolean` | no | | Enable or disable notifications. | | `notify_email` | `string` | no | Valid email. Max: `255`. Required if `notify` is `true` and `notify_address` is absent. | Email address to notify. | | `notify_address` | `string` | no | Valid URL. Max: `500`. Required if `notify` is `true` and `notify_email` is absent. | Webhook URL to notify. | ### Request body \[!toc] [#request-body-toc-1] ```json { "name": "Updated Name", "notify": true, "notify_email": "alerts@example.com" } ``` ### Responses [#responses-3] #### Valid [#valid-2] ```http Response Code: 200 OK Response Headers: content-type: application/json ``` The response has the same shape as the [Get a monitor](#get-a-monitor) response. #### Error [#error-3] ```http Response Code: 422 Unprocessable Entity ``` *See - [Validation errors](/../../general#validation-errors)* ## Delete a monitor [#delete-a-monitor] If you want to delete a blocklist monitor, use this `DELETE` request: ```http DELETE https://api.mailersend.com/v1/blocklist-monitoring/{monitor_id} ``` #### Request parameters \[!toc] [#request-parameters-toc-4] | URL parameter | Type | Required | Limitations | Details | | ------------- | -------- | -------- | ----------- | ------- | | `monitor_id` | `string` | yes | | | If the monitor is a parent (IP range), all child monitors are deleted automatically. ### Responses [#responses-4] #### Valid [#valid-3] ```http Response Code: 204 No Content ``` #### Error [#error-4] ```http Response Code: 404 Not Found ``` # DMARC Monitoring (/api/v1/account/dmarc-monitoring) Receive and analyze DMARC reports to identify potential sending issues. Create and manage monitors for your domains, retrieve aggregated and IP-specific reports, and track DMARC compliance across your email infrastructure. ## List monitors [#list-monitors] If you want to retrieve information about multiple DMARC monitors, use this `GET` request: ```http GET https://api.mailersend.com/v1/dmarc-monitoring ``` #### Request parameters \[!toc] [#request-parameters-toc] | Query parameter | Type | Required | Limitations | Details | | --------------- | -------- | -------- | -------------------- | ----------------------------------------------------------------------- | | `page` | `int` | no | Min: `1` | | | `limit` | `int` | no | Min: `1`, Max: `100` | Default: `25` | | `query` | `string` | no | Max: `255` | Search/filter monitors | | `sort_by` | `string` | no | | Allowed values: `created_at`, `updated_at`, `dmarc_valid`, `spf_status` | | `order` | `string` | no | | Allowed values: `asc`, `desc` | ### Responses [#responses] #### Valid [#valid] ```http Response Code: 200 OK Response Headers: content-type: application/json ``` ```json { "data": [ { "id": "9dnxr7qvdqg6pm0e", "dmarc_record": "v=DMARC1; p=reject; rua=mailto:dmarc_agg@dmarc.example.org,mailto:rua-dev@tests.example.org,mailto:rua@example.org; ruf=mailto:dmarc_fr@dmarc.example.org; fo=1; pct=100; rf=afrf", "wanted_dmarc_record": "v=DMARC1; p=reject; rua=mailto:dmarc_agg@dmarc.example.org,mailto:rua-dev@tests.example.org,mailto:rua@example.org; ruf=mailto:dmarc_fr@dmarc.example.org; fo=1; pct=100; rf=afrf", "dmarc_valid": true, "dmarc_record_checked_at": "2025-11-05T09:06:35.000000Z", "spf_record": "v=spf1 include:_spf.example.org include:_spf.example.org include:example.org include:_spf.example.org ip4:192.0.2.1 include:example.org -all", "spf_status": "valid", "created_at": "2025-11-05T09:06:35.000000Z", "updated_at": "2025-11-05T09:06:35.000000Z", "domain": { "id": "5genxmqlgozlyvk7", "name": "example.org", "created_at": "2025-11-05T06:18:44.000000Z", "updated_at": "2025-11-05T06:19:14.000000Z" } } ] } ``` #### Error [#error] ```http Response Code: 422 Unprocessable Entity ``` *See - [Validation errors](/../../general#validation-errors)* ## Create a monitor [#create-a-monitor] If you want to create a new DMARC monitor for a domain, use this `POST` request: ```http POST https://api.mailersend.com/v1/dmarc-monitoring ``` #### Request parameters \[!toc] [#request-parameters-toc-1] *JSON parameters are provided in dot notation* | JSON Parameter | Type | Required | Limitations | Details | | -------------- | -------- | -------- | ----------- | ---------------------------------------------------------------------- | | `domain_id` | `string` | yes | | Must be a verified domain. Only one monitor can be created per domain. | ### Request body \[!toc] [#request-body-toc] ```json { "domain_id": "0z76k5jg0o3yeg2d" } ``` ### Responses [#responses-1] #### Valid [#valid-1] ```http Response Code: 201 CREATED Response Headers: content-type: application/json ``` ```json { "data": { "id": "lx1p78jk1o53rzn4", "dmarc_record": "", "wanted_dmarc_record": "rua=mailto:rua@example.org", "dmarc_valid": false, "dmarc_record_checked_at": null, "spf_record": null, "spf_status": "not_found", "created_at": "2025-11-06T10:27:34.000000Z", "updated_at": "2025-11-06T10:27:34.000000Z", "domain": { "id": "0z76k5jg0o3yeg2d", "name": "example.org", "created_at": "2025-11-06T10:24:03.000000Z", "updated_at": "2025-11-06T10:25:47.000000Z" } } } ``` #### Error [#error-1] ```http Response Code: 422 Unprocessable Entity ``` *See - [Validation errors](/../../general#validation-errors)* ## Update a monitor [#update-a-monitor] If you want to update a DMARC monitor, use this `PUT` request: ```http PUT https://api.mailersend.com/v1/dmarc-monitoring/{monitor_id} ``` #### Request parameters \[!toc] [#request-parameters-toc-2] | URL parameter | Type | Required | Limitations | Details | | ------------- | -------- | -------- | ----------- | ------- | | `monitor_id` | `string` | yes | | | *JSON parameters are provided in dot notation* | JSON Parameter | Type | Required | Limitations | Details | | --------------------- | -------- | -------- | ----------- | ------------------------------------------------------------------------------ | | `wanted_dmarc_record` | `string` | yes | Max: `1000` | Must be a valid DMARC record format (e.g. `v=DMARC1; p=none; rua=mailto:...`). | ### Request body \[!toc] [#request-body-toc-1] ```json { "wanted_dmarc_record": "v=DMARC1; p=reject; rua=mailto:dmarc_agg@dmarc.example.org" } ``` ### Responses [#responses-2] #### Valid [#valid-2] ```http Response Code: 200 OK Response Headers: content-type: application/json ``` ```json { "data": { "id": "lx1p78jk1o53rzn4", "dmarc_record": "", "wanted_dmarc_record": "v=DMARC1; p=reject; rua=mailto:dmarc_agg@dmarc.example.org,mailto:rua-ms@example.org", "dmarc_valid": false, "dmarc_record_checked_at": "2025-11-06T10:31:55.000000Z", "spf_record": null, "spf_status": "not_found", "created_at": "2025-11-06T10:27:34.000000Z", "updated_at": "2025-11-06T10:31:55.000000Z", "domain": { "id": "0z76k5jg0o3yeg2d", "name": "example.org", "created_at": "2025-11-06T10:24:03.000000Z", "updated_at": "2025-11-06T10:25:47.000000Z" } } } ``` #### Error [#error-2] ```http Response Code: 422 Unprocessable Entity ``` *See - [Validation errors](/../../general#validation-errors)* ## Delete a monitor [#delete-a-monitor] If you want to delete a DMARC monitor, use this `DELETE` request: ```http DELETE https://api.mailersend.com/v1/dmarc-monitoring/{monitor_id} ``` #### Request parameters \[!toc] [#request-parameters-toc-3] | URL parameter | Type | Required | Limitations | Details | | ------------- | -------- | -------- | ----------- | ------- | | `monitor_id` | `string` | yes | | | ### Responses [#responses-3] #### Valid [#valid-3] ```http Response Code: 204 No Content ``` #### Error [#error-3] ```http Response Code: 404 Not Found ``` ## Get aggregated reports [#get-aggregated-reports] If you want to retrieve aggregated DMARC reports for a monitor, use this `GET` request: ```http GET https://api.mailersend.com/v1/dmarc-monitoring/{monitor_id}/report ``` #### Request parameters \[!toc] [#request-parameters-toc-4] | URL parameter | Type | Required | Limitations | Details | | ------------- | -------- | -------- | ----------- | ------- | | `monitor_id` | `string` | yes | | | | Query parameter | Type | Required | Limitations | Details | | --------------- | -------- | -------- | -------------------- | --------------------------------------------------------------------------- | | `page` | `int` | no | | | | `limit` | `int` | no | Min: `1`, Max: `100` | Default: `25` | | `date_from` | `string` | no | | Filter by report date (from) | | `date_to` | `string` | no | | Filter by report date (to). Must be after `date_from` and not in the future | | `search` | `string` | no | Max: `255` | | | `category` | `string` | no | | | | `report_source` | `string` | no | Max: `255` | Filter by reporting organization | ### Responses [#responses-4] #### Valid [#valid-4] ```http Response Code: 200 OK Response Headers: content-type: application/json ``` ```json { "data": [ { "ip_address": "192.0.2.1", "total_volume": 2, "passed_dmarc": "100%", "passed_spf": "0%", "passed_dkim": "100%", "domain": "example.org", "country": "United States", "country_code": "US", "city": null, "is_favorite": true }, { "ip_address": "192.0.2.2", "total_volume": 2, "passed_dmarc": "100%", "passed_spf": "100%", "passed_dkim": "100%", "domain": "example.org", "country": "United States", "country_code": "US", "city": null } ] } ``` #### Error [#error-4] ```http Response Code: 404 Not Found ``` ## Get IP-specific reports [#get-ip-specific-reports] If you want to retrieve detailed DMARC reports for a specific IP address, use this `GET` request: ```http GET https://api.mailersend.com/v1/dmarc-monitoring/{monitor_id}/report/{ip} ``` #### Request parameters \[!toc] [#request-parameters-toc-5] | URL parameter | Type | Required | Limitations | Details | | ------------- | -------- | -------- | ----------- | ------- | | `monitor_id` | `string` | yes | | | | `ip` | `string` | yes | | | | Query parameter | Type | Required | Limitations | Details | | --------------- | -------- | -------- | -------------------- | --------------------------------------------------------------------------- | | `page` | `int` | no | | | | `limit` | `int` | no | Min: `1`, Max: `100` | Default: `25` | | `date_from` | `string` | no | | Filter by report date (from) | | `date_to` | `string` | no | | Filter by report date (to). Must be after `date_from` and not in the future | | `search` | `string` | no | Max: `255` | | | `category` | `string` | no | | | | `report_source` | `string` | no | Max: `255` | Filter by reporting organization | ### Responses [#responses-5] #### Valid [#valid-5] ```http Response Code: 200 OK Response Headers: content-type: application/json ``` ```json { "data": [ { "id": "690b12b39dc30891fc35d3da", "ip_address": "192.0.2.1", "ip_domain": "example.org", "total_volume": 2, "passed_dmarc": "100%", "passed_spf": "0%", "spf_domain": null, "aligned_spf": false, "passed_dkim": "100%", "aligned_dkim": true, "dkim_domain": null, "created_at": "2025-11-05T00:00:00.000000Z", "applied_policy": "none", "override_reason": null, "override_comment": null, "domain": null, "country": null, "country_code": null, "city": null, "report_source": "example.com", "spf_auth": [ { "type": "spf", "result": "pass", "domain": "example.org", "selector": null } ], "dkim_auth": [ { "type": "dkim", "result": "fail", "domain": "example.org", "selector": "example" } ] } ] } ``` #### Error [#error-5] ```http Response Code: 404 Not Found ``` ## Get report sources [#get-report-sources] If you want to retrieve a list of report sources for a monitor, use this `GET` request: ```http GET https://api.mailersend.com/v1/dmarc-monitoring/{monitor_id}/report-sources ``` #### Request parameters \[!toc] [#request-parameters-toc-6] | URL parameter | Type | Required | Limitations | Details | | ------------- | -------- | -------- | ----------- | ------- | | `monitor_id` | `string` | yes | | | | Query parameter | Type | Required | Limitations | Details | | --------------- | -------- | -------- | ----------- | ---------------------------------------------------------------------------------- | | `date_from` | `string` | yes | | Filter start date | | `date_to` | `string` | yes | | Filter end date. Must be after `date_from` and not in the future | | `status` | `string` | no | | Filter by acceptance status. Allowed values: `accepted`, `rejected`, `quarantined` | ### Responses [#responses-6] #### Valid [#valid-6] ```http Response Code: 200 OK Response Headers: content-type: application/json ``` ```json { "data": [ { "report_source": "example.com", "reports": 3 } ] } ``` #### Error [#error-6] ```http Response Code: 404 Not Found ``` ## Mark IP as favorite [#mark-ip-as-favorite] If you want to mark an IP address as a favorite for a monitor, use this `PUT` request: ```http PUT https://api.mailersend.com/v1/dmarc-monitoring/{monitor_id}/favorite/{ip} ``` #### Request parameters \[!toc] [#request-parameters-toc-7] | URL parameter | Type | Required | Limitations | Details | | ------------- | -------- | -------- | ----------- | ------- | | `monitor_id` | `string` | yes | | | | `ip` | `string` | yes | | | ### Responses [#responses-7] #### Valid [#valid-7] ```http Response Code: 200 OK Response Headers: content-type: application/json ``` ```json {} ``` #### Error [#error-7] ```http Response Code: 404 Not Found ``` ## Remove IP from favorites [#remove-ip-from-favorites] If you want to remove an IP address from favorites for a monitor, use this `DELETE` request: ```http DELETE https://api.mailersend.com/v1/dmarc-monitoring/{monitor_id}/favorite/{ip} ``` #### Request parameters \[!toc] [#request-parameters-toc-8] | URL parameter | Type | Required | Limitations | Details | | ------------- | -------- | -------- | ----------- | ------- | | `monitor_id` | `string` | yes | | | | `ip` | `string` | yes | | | ### Responses [#responses-8] #### Valid [#valid-8] ```http Response Code: 204 No Content ``` #### Error [#error-8] ```http Response Code: 404 Not Found ``` # SMTP Users (/api/v1/account/smtp-users) ## Get a list of SMTP users [#get-a-list-of-smtp-users] Retrieve information about account SMTP users with this `GET` request: ```http GET https://api.mailersend.com/v1/domains/{domain_id}/smtp-users ``` #### Request parameters \[!toc] [#request-parameters-toc] | URL parameter | Type | Required | Limitations | Details | | ------------- | -------- | -------- | ----------- | ------- | | `domain_id` | `string` | yes | | | | Query Parameter | Type | Required | Limitations | Details | | --------------- | ----- | -------- | --------------------- | ------------- | | `limit` | `int` | no | Min: `10`, Max: `100` | Default: `25` | | `page` | `int` | no | Min: `1` | | ```php use MailerSend\MailerSend; $mailersend = new MailerSend(['api_key' => 'key']); $mailersend->smtpUser->getAll('domain-id', 25); ``` [More examples](https://github.com/mailersend/mailersend-php) ```javascript import 'dotenv/config'; import { MailerSend } from "mailersend"; const mailerSend = new MailerSend({ apiKey: process.env.API_KEY, }); mailerSend.email.smtpUser.list("domain-id") .then((response) => console.log(response.body)) .catch((error) => console.log(error.body)); ``` [More examples](https://github.com/mailersend/mailersend-nodejs) ```python from mailersend import MailerSendClient, SmtpUsersBuilder ms = MailerSendClient() request = (SmtpUsersBuilder() .domain_id("domain-id") .build_smtp_users_list()) response = ms.smtp_users.list_smtp_users(request) ``` [More examples](https://github.com/mailersend/mailersend-python) ```go package main import ( "context" "log" "time" "github.com/mailersend/mailersend-go" ) var APIKey = "Api Key Here" func main() { // Create an instance of the mailersend client ms := mailersend.NewMailersend(APIKey) ctx := context.Background() ctx, cancel := context.WithTimeout(ctx, 5*time.Second) defer cancel() domainID := "domain-id" options := &mailersend.ListSmtpUserOptions{ Limit: 25, } _, _, err := ms.SmtpUser.List(ctx, domainID, options) if err != nil { log.Fatal(err) } } ``` [More examples](https://github.com/mailersend/mailersend-go) ```java import com.mailersend.sdk.MailerSend; import com.mailersend.sdk.smtpusers.SmtpUser; import com.mailersend.sdk.smtpusers.SmtpUsersList; import com.mailersend.sdk.exceptions.MailerSendException; public void ListSmtpUsers() { MailerSend ms = new MailerSend(); ms.setToken("api token"); try { SmtpUsersList list = ms.smtpUsers().getSmtpUsers("domain-id", 25); for (SmtpUser smtpUser : list.smtpUsers) { System.out.println(smtpUser.id); System.out.println(smtpUser.name); } } catch (MailerSendException e) { e.printStackTrace(); } } ``` [More examples](https://github.com/mailersend/mailersend-java) ```ruby require "mailersend-ruby" ms_smtp_user = Mailersend::SmtpUser.new ms_smtp_user.list("domain-id") ``` [More examples](https://github.com/mailersend/mailersend-ruby) ### Responses [#responses] #### Valid [#valid] ```http Response Code: 200 OK Response Headers: content-type: application/json ``` ```json { "data": [ { "id": "0wkg2zj19ovx5py7", "name": "Support SMTP", "username": "MS_bGQ0nV@mailerlite.com", "enabled": true, "accessed_at": null, "server": "127.0.0.1", "port": 465, "domain_id": "7nxe3yjmeq28vp0k", "created_at": "2024-02-20T09:39:44.000000Z" } ] } ``` #### Error [#error] ```http Response Code: 404 Not Found ``` ## Get a single SMTP user [#get-a-single-smtp-user] If you want to retrieve a single account SMTP user, use this `GET` request: ```http GET https://api.mailersend.com/v1/domains/{domain_id}/smtp-users/{smtp_user_id} ``` #### Request parameters \[!toc] [#request-parameters-toc-1] | URL parameter | Type | Required | Limitations | Details | | -------------- | -------- | -------- | ----------- | ------- | | `domain_id` | `string` | yes | | | | `smtp_user_id` | `string` | yes | | | ```php use MailerSend\MailerSend; $mailersend = new MailerSend(['api_key' => 'key']); $mailersend->smtpUser->find('domain-id', 'smtp-user-id'); ``` [More examples](https://github.com/mailersend/mailersend-php) ```javascript import 'dotenv/config'; import { MailerSend } from "mailersend"; const mailerSend = new MailerSend({ apiKey: process.env.API_KEY, }); mailerSend.email.smtpUser.single("domain-id", "smtp-user-id") .then((response) => console.log(response.body)) .catch((error) => console.log(error.body)); ``` [More examples](https://github.com/mailersend/mailersend-nodejs) ```python from mailersend import MailerSendClient, SmtpUsersBuilder ms = MailerSendClient() request = (SmtpUsersBuilder() .domain_id("domain-id") .smtp_user_id("smtp-user-id") .build_smtp_user_get()) response = ms.smtp_users.get_smtp_user(request) ``` [More examples](https://github.com/mailersend/mailersend-python) ```go package main import ( "context" "log" "time" "github.com/mailersend/mailersend-go" ) var APIKey = "Api Key Here" func main() { // Create an instance of the mailersend client ms := mailersend.NewMailersend(APIKey) ctx := context.Background() ctx, cancel := context.WithTimeout(ctx, 5*time.Second) defer cancel() domainID := "domain-id" smtpUserID := "smtp-user-id" _, _, err := ms.SmtpUser.Get(ctx, domainID, smtpUserID) if err != nil { log.Fatal(err) } } ``` [More examples](https://github.com/mailersend/mailersend-go) ```java import com.mailersend.sdk.MailerSend; import com.mailersend.sdk.smtpusers.SmtpUser; import com.mailersend.sdk.exceptions.MailerSendException; public void GetSmtpUser() { MailerSend ms = new MailerSend(); ms.setToken("api token"); try { SmtpUser smtpUser = ms.smtpUsers().getSmtpUser("domain-id", "smtp-user-id"); System.out.println(smtpUser.id); System.out.println(smtpUser.name); System.out.println(smtpUser.username); } catch (MailerSendException e) { e.printStackTrace(); } } ``` [More examples](https://github.com/mailersend/mailersend-java) ```ruby require "mailersend-ruby" ms_smtp_user = Mailersend::SmtpUser.new ms_smtp_user.get("domain-id", "smtp-user-id") ``` [More examples](https://github.com/mailersend/mailersend-ruby) ### Responses [#responses-1] #### Valid [#valid-1] ```http Response Code: 200 OK Response Headers: content-type: application/json ``` ```json { "data": { "id": "0wkg2zj19ovx5py7", "name": "Support SMTP", "username": "MS_bGQ0nV@mailerlite.com", "enabled": true, "accessed_at": null, "server": "127.0.0.1", "port": 465, "domain_id": "7nxe3yjmeq28vp0k", "created_at": "2024-02-20T09:39:44.000000Z" } } ``` #### Error [#error-1] ```http Response Code: 404 Not Found ``` ## Add SMTP user [#add-smtp-user] If you want to add a SMTP user to your domain, use this `POST` request: ```http POST https://api.mailersend.com/v1/domains/{domain_id}/smtp-users ``` #### Request parameters \[!toc] [#request-parameters-toc-2] | URL parameter | Type | Required | Limitations | Details | | ------------- | -------- | -------- | ----------- | ------- | | `domain_id` | `string` | yes | | | ### Request Parameters \[!toc] [#request-parameters-toc-3] *JSON parameters are provided in dot notation* | JSON Parameter | Type | Required | Limitations | Details | | -------------- | --------- | -------- | ------------------- | ------- | | `name` | `string` | yes | `Max` 50 characters | | | `enabled` | `boolean` | no | | | ```php use MailerSend\MailerSend; use MailerSend\Helpers\Builder\SmtpUserParams; $mailersend = new MailerSend(['api_key' => 'key']); $mailersend->smtpUser->create( 'domain-id', (new SmtpUserParams('SMTP User Name')) ->setEnabled(true) ); ``` [More examples](https://github.com/mailersend/mailersend-php) ```javascript import 'dotenv/config'; import { MailerSend, SmtpUser } from "mailersend"; const mailerSend = new MailerSend({ apiKey: process.env.API_KEY, }); const smtpUser = new SmtpUser() .setName("SMTP User Name") .setEnabled(true); mailerSend.email.smtpUser.create("domain-id", smtpUser) .then((response) => console.log(response.body)) .catch((error) => console.log(error.body)); ``` [More examples](https://github.com/mailersend/mailersend-nodejs) ```python from mailersend import MailerSendClient, SmtpUsersBuilder ms = MailerSendClient() request = (SmtpUsersBuilder() .domain_id("domain-id") .name("SMTP User Name") .enabled(True) .build_smtp_user_create()) response = ms.smtp_users.create_smtp_user(request) ``` [More examples](https://github.com/mailersend/mailersend-python) ```go package main import ( "context" "log" "time" "github.com/mailersend/mailersend-go" ) var APIKey = "Api Key Here" func main() { // Create an instance of the mailersend client ms := mailersend.NewMailersend(APIKey) ctx := context.Background() ctx, cancel := context.WithTimeout(ctx, 5*time.Second) defer cancel() domainID := "domain-id" options := &mailersend.CreateSmtpUserOptions{ Name: "SMTP User Name", Enabled: mailersend.Bool(true), } _, _, err := ms.SmtpUser.Create(ctx, domainID, options) if err != nil { log.Fatal(err) } } ``` [More examples](https://github.com/mailersend/mailersend-go) ```java import com.mailersend.sdk.MailerSend; import com.mailersend.sdk.smtpusers.SmtpUser; import com.mailersend.sdk.exceptions.MailerSendException; public void CreateSmtpUser() { MailerSend ms = new MailerSend(); ms.setToken("api token"); try { SmtpUser smtpUser = ms.smtpUsers().builder() .name("SMTP User Name") .enabled(true) .createSmtpUser("domain-id"); System.out.println(smtpUser.id); System.out.println(smtpUser.name); } catch (MailerSendException e) { e.printStackTrace(); } } ``` [More examples](https://github.com/mailersend/mailersend-java) ```ruby require "mailersend-ruby" ms_smtp_user = Mailersend::SmtpUser.new ms_smtp_user.create("domain-id", name: "SMTP User Name", enabled: true) ``` [More examples](https://github.com/mailersend/mailersend-ruby) ### Responses [#responses-2] | Response Key | Type | Details | | ------------ | ------ | ------------------------- | | data | object | SMTP user object created. | The `password` is returned **only once**, in the response to this create request. It is stored as a hash and cannot be retrieved again afterwards, so make sure to save it securely. If it is lost, delete the SMTP user and create a new one. #### Valid [#valid-2] ```http Response Code: 201 CREATED Response Headers: content-type: application/json ``` ```json { "data": { "id": "480xl1qpeorzeg65", "name": "Support", "username": "MS_8PerdM@mailerlite.com", "enabled": true, "accessed_at": null, "server": "127.0.0.1", "port": 465, "domain_id": "7nxe3yjmeq28vp0k", "created_at": "2024-02-20T09:39:44.000000Z", "password": "mssp.G7hR2kQ9vN4pL8xW" } } ``` #### Invalid [#invalid] ```http Response Code: 422 Unprocessable Entity ``` *See - [Validation errors](/../../general#validation-errors)* ## Update SMTP user [#update-smtp-user] If you want to update the information of an existing SMTP user, use this `PUT` request: ```http PUT https://api.mailersend.com/v1/domains/{domain_id}/smtp-users/{smtp_user_id} ``` ### Request Parameters \[!toc] [#request-parameters-toc-4] | URL parameter | Type | Required | Limitations | Details | | -------------- | -------- | -------- | ----------- | ------- | | `domain_id` | `string` | yes | | | | `smtp_user_id` | `string` | yes | | | *JSON parameters are provided in dot notation* | JSON Parameter | Type | Required | Limitations | Details | | -------------- | --------- | -------- | ------------------- | ------- | | `name` | `string` | no | `Max` 50 characters | | | `enabled` | `boolean` | no | | | ```php use MailerSend\MailerSend; use MailerSend\Helpers\Builder\SmtpUserParams; $mailersend = new MailerSend(['api_key' => 'key']); $mailersend->smtpUser->update( 'domain-id', 'smtp-user-id', (new SmtpUserParams('Updated SMTP User Name')) ->setEnabled(false) ); ``` [More examples](https://github.com/mailersend/mailersend-php) ```javascript import 'dotenv/config'; import { MailerSend, SmtpUser } from "mailersend"; const mailerSend = new MailerSend({ apiKey: process.env.API_KEY, }); const smtpUser = new SmtpUser() .setName("Updated SMTP User Name") .setEnabled(false); mailerSend.email.smtpUser.update("domain-id", "smtp-user-id", smtpUser) .then((response) => console.log(response.body)) .catch((error) => console.log(error.body)); ``` [More examples](https://github.com/mailersend/mailersend-nodejs) ```python from mailersend import MailerSendClient, SmtpUsersBuilder ms = MailerSendClient() request = (SmtpUsersBuilder() .domain_id("domain-id") .smtp_user_id("smtp-user-id") .name("Updated SMTP User Name") .enabled(False) .build_smtp_user_update()) response = ms.smtp_users.update_smtp_user(request) ``` [More examples](https://github.com/mailersend/mailersend-python) ```go package main import ( "context" "log" "time" "github.com/mailersend/mailersend-go" ) var APIKey = "Api Key Here" func main() { // Create an instance of the mailersend client ms := mailersend.NewMailersend(APIKey) ctx := context.Background() ctx, cancel := context.WithTimeout(ctx, 5*time.Second) defer cancel() domainID := "domain-id" smtpUserID := "smtp-user-id" options := &mailersend.UpdateSmtpUserOptions{ Name: mailersend.String("Updated SMTP User Name"), Enabled: mailersend.Bool(false), } _, _, err := ms.SmtpUser.Update(ctx, domainID, smtpUserID, options) if err != nil { log.Fatal(err) } } ``` [More examples](https://github.com/mailersend/mailersend-go) ```java import com.mailersend.sdk.MailerSend; import com.mailersend.sdk.smtpusers.SmtpUser; import com.mailersend.sdk.exceptions.MailerSendException; public void UpdateSmtpUser() { MailerSend ms = new MailerSend(); ms.setToken("api token"); try { SmtpUser smtpUser = ms.smtpUsers().builder() .name("Updated SMTP User Name") .enabled(false) .updateSmtpUser("domain-id", "smtp-user-id"); System.out.println(smtpUser.id); System.out.println(smtpUser.name); } catch (MailerSendException e) { e.printStackTrace(); } } ``` [More examples](https://github.com/mailersend/mailersend-java) ```ruby require "mailersend-ruby" ms_smtp_user = Mailersend::SmtpUser.new ms_smtp_user.update("domain-id", "smtp-user-id", name: "Updated SMTP User Name", enabled: false) ``` [More examples](https://github.com/mailersend/mailersend-ruby) ### Responses [#responses-3] | Response Key | Type | Details | | ------------ | ------ | ------------------------- | | data | object | SMTP user object updated. | #### Valid [#valid-3] ```http Response Code: 200 OK Response Headers: content-type: application/json ``` ```json { "data": { "id": "0z76k5jg0o3yeg2d", "name": "Support SMTP", "username": "MS_9sjABw@testing.com", "enabled": false, "accessed_at": null, "server": "127.0.0.1", "port": 465, "domain_id": "04mknvjymj87xp62", "created_at": "2024-02-20T09:39:44.000000Z" } } ``` #### Invalid [#invalid-1] ```http Response Code: 422 Unprocessable Entity ``` *See - [Validation errors](/../../general#validation-errors)* ## Delete SMTP user [#delete-smtp-user] If you want to remove SMTP user, use this `DELETE` request: ```http DELETE https://api.mailersend.com/v1/domains/{domain_id}/smtp-users/{smtp_user_id} ``` ### Request parameters \[!toc] [#request-parameters-toc-5] | URL parameter | Type | Required | Limitations | Details | | -------------- | -------- | -------- | ----------- | ------- | | `domain_id` | `string` | yes | | | | `smtp_user_id` | `string` | yes | | | ```php use MailerSend\MailerSend; $mailersend = new MailerSend(['api_key' => 'key']); $mailersend->smtpUser->delete('domain-id', 'smtp-user-id'); ``` [More examples](https://github.com/mailersend/mailersend-php) ```javascript import 'dotenv/config'; import { MailerSend } from "mailersend"; const mailerSend = new MailerSend({ apiKey: process.env.API_KEY, }); mailerSend.email.smtpUser.delete("domain-id", "smtp-user-id") .then((response) => console.log(response.body)) .catch((error) => console.log(error.body)); ``` [More examples](https://github.com/mailersend/mailersend-nodejs) ```python from mailersend import MailerSendClient, SmtpUsersBuilder ms = MailerSendClient() request = (SmtpUsersBuilder() .domain_id("domain-id") .smtp_user_id("smtp-user-id") .build_smtp_user_delete()) response = ms.smtp_users.delete_smtp_user(request) ``` [More examples](https://github.com/mailersend/mailersend-python) ```go package main import ( "context" "log" "time" "github.com/mailersend/mailersend-go" ) var APIKey = "Api Key Here" func main() { // Create an instance of the mailersend client ms := mailersend.NewMailersend(APIKey) ctx := context.Background() ctx, cancel := context.WithTimeout(ctx, 5*time.Second) defer cancel() domainID := "domain-id" smtpUserID := "smtp-user-id" _, _, err := ms.SmtpUser.Delete(ctx, domainID, smtpUserID) if err != nil { log.Fatal(err) } } ``` [More examples](https://github.com/mailersend/mailersend-go) ```java import com.mailersend.sdk.MailerSend; import com.mailersend.sdk.exceptions.MailerSendException; public void DeleteSmtpUser() { MailerSend ms = new MailerSend(); ms.setToken("api token"); try { ms.smtpUsers().deleteSmtpUser("domain-id", "smtp-user-id"); System.out.println("SMTP user deleted successfully"); } catch (MailerSendException e) { e.printStackTrace(); } } ``` [More examples](https://github.com/mailersend/mailersend-java) ```ruby require "mailersend-ruby" ms_smtp_user = Mailersend::SmtpUser.new ms_smtp_user.delete("domain-id", "smtp-user-id") ``` [More examples](https://github.com/mailersend/mailersend-ruby) ### Responses [#responses-4] #### Valid [#valid-4] ```http Response Code: 204 OK ``` #### Error [#error-2] ```http Response Code: 404 Not Found ``` # Tokens (/api/v1/account/tokens) You need to add a sending domain token to authenticate your API requests. API tokens are generated for sending domains and can have different permissions to limit which areas of your account they may be used to access. ## List tokens [#list-tokens] List API token with this `GET` request: ```http GET https://api.mailersend.com/v1/token ``` #### Request parameters \[!toc] [#request-parameters-toc] | Query parameter | Type | Required | Limitations | Details | | --------------- | ----- | -------- | --------------------- | ------------- | | `page` | `int` | no | | | | `limit` | `int` | no | Min: `10`, Max: `100` | Default: `25` | #### Request Body \[!toc] [#request-body-toc] ```php use MailerSend\MailerSend; use MailerSend\Helpers\Builder\TokenParams; $mailersend = new MailerSend(['api_key' => 'key']); $mailersend->token->getAll(); ``` [More examples](https://github.com/mailersend/mailersend-php) ### Responses [#responses] #### Valid [#valid] ```http Response Code: 200 OK Response Headers: content-type: application/json ``` ```json { "data": [ { "id": "481c8fdf59036be3f102b1ee6052e0f50a42051702dc5c820c1753d1752adc41ba5b1aaaaaaaaa", "name": "First token", "status": "unpause", "created_at": "2024-04-12T11:27:53.000000Z", "scopes": [ "email_full" ] }, { "id": "481c8fdf59036be3f102b1ee6052e0f50a42051702dc5c820c1753d1752adc41ba5b12aaaaaaaaa", "name": "Second token", "status": "unpause", "created_at": "2024-04-17T08:40:13.000000Z", "scopes": [ "domains_read", "analytics_full" ] } ] } ``` ## Show a token [#show-a-token] View API token with this `GET` request: ```http GET https://api.mailersend.com/v1/token/{token_id} ``` #### Request parameters \[!toc] [#request-parameters-toc-1] | URL parameter | Type | Required | Limitations | Details | | ------------- | -------- | -------- | ----------- | ------- | | `token_id` | `string` | yes | | | #### Request Body \[!toc] [#request-body-toc-1] ```php use MailerSend\MailerSend; use MailerSend\Helpers\Builder\TokenParams; $mailersend = new MailerSend(['api_key' => 'key']); $mailersend->token->find('token_id'); ``` [More examples](https://github.com/mailersend/mailersend-php) ### Responses [#responses-1] #### Valid [#valid-1] ```http Response Code: 200 OK Response Headers: content-type: application/json ``` ```json { "data": { "id": "481c8fdf59036be3f102b1ee6052e0f50a42051702dc5c820c1753d1752adc41ba5b1aaaaaaaaa", "name": "First token", "status": "unpause", "created_at": "2024-04-12T11:27:53.000000Z", "scopes": [ "email_full" ] } } ``` #### Error [#error] ```http Response Code: 404 Not Found ``` ## Create a token [#create-a-token] Create an API token with this `POST` request: ```http POST https://api.mailersend.com/v1/token ``` #### Request Body \[!toc] [#request-body-toc-2] ```json { "name": "API Token", "domain_id": "Domain ID", "scopes" : ["email_full", "analytics_read"] } ``` ```php use MailerSend\MailerSend; use MailerSend\Helpers\Builder\TokenParams; $mailersend = new MailerSend(['api_key' => 'key']); $mailersend->token->create( new TokenParams('token name', 'domainId', TokenParams::ALL_SCOPES) ); ``` [More examples](https://github.com/mailersend/mailersend-php) ```javascript import 'dotenv/config'; import { MailerSend, Token} from "mailersend"; const mailerSend = new MailerSend({ apiKey: process.env.API_KEY, }); const token = new Token() .setName("Token name") .setDomainId("domain_id") .setScopes([ "email_full", "domains_read", "domains_full", "activity_read", "activity_full", "analytics_read", "analytics_full", "tokens_full", ]); mailerSend.token.create(token) .then((response) => console.log(response.body)) .catch((error) => console.log(error.body)); ``` [More examples](https://github.com/mailersend/mailersend-nodejs) ```python from mailersend import MailerSendClient, TokensBuilder ms = MailerSendClient() request = (TokensBuilder() .name("My API Token") .scopes(["email_full", "analytics_read"]) .domain_id("domain-id") .build_token_create()) response = ms.tokens.create_token(request) ``` [More examples](https://github.com/mailersend/mailersend-python) ```go package main import ( "context" "log" "time" "github.com/mailersend/mailersend-go" ) var APIKey = "Api Key Here" func main() { // Create an instance of the mailersend client ms := mailersend.NewMailersend(APIKey) ctx := context.Background() ctx, cancel := context.WithTimeout(ctx, 5*time.Second) defer cancel() domainID := "domain-id" scopes := []string{ "tokens_full", "email_full", "domains_full", "activity_full", "analytics_full", "webhooks_full", "templates_full", } options := &mailersend.CreateTokenOptions{ Name: "token name", DomainID: domainID, Scopes: scopes, } newToken, _, err := ms.Token.Create(ctx, options) if err != nil { log.Fatal(err) } // Make sure you keep your access token secret log.Print(newToken.Data.AccessToken) } ``` [More examples](https://github.com/mailersend/mailersend-go) ```java import com.mailersend.sdk.MailerSend; import com.mailersend.sdk.exceptions.MailerSendException; import com.mailersend.sdk.tokens.Token; import com.mailersend.sdk.tokens.TokenAdd; import com.mailersend.sdk.tokens.TokenScopes; public void CreateToken() { MailerSend ms = new MailerSend(); ms.setToken(TestHelper.validToken); try { TokenAdd token = ms.tokens().addBuilder() .name("Test token") .domainId("domain id") .addScope(TokenScopes.activityFull) .addScope(TokenScopes.analyticsFull) .addToken(); System.out.println(token.id); System.out.println(token.name); System.out.println(token.accessToken); } catch (MailerSendException e) { e.printStackTrace(); } } ``` [More examples](https://github.com/mailersend/mailersend-java) ```ruby require "mailersend-ruby" ms_tokens = Mailersend::Tokens.new ms_tokens.create(name: "Very nice token", scopes: %w[ email_full domains_read ], domain_id: "yourdomainid") ``` [More examples](https://github.com/mailersend/mailersend-ruby) #### Request parameters \[!toc] [#request-parameters-toc-2] *JSON parameters are provided in dot notation.* | JSON parameter | Type | Required | Limitations | Details | | -------------- | -------- | -------- | ----------- | ------- | | `name` | `string` | yes | Max: `50` | | | `domain_id` | `string` | no | | | | `scopes` | `array` | yes | | | ##### Possible scopes [#possible-scopes] ``` [ "email_full", "domains_read", "domains_full", "activity_read", "activity_full", "analytics_read", "analytics_full", "tokens_full", "webhooks_full", "templates_full", "suppressions_read", "suppressions_full", "sms_full", "sms_read", "email_verification_read", "email_verification_full", "inbounds_full", "recipients_read", "recipients_full", "sender_identity_read", "sender_identity_full", "users_read", "users_full", "smtp_users_read", "smtp_users_full", "dmarc_monitoring_read", "dmarc_monitoring_full", "blocklist_monitoring_read", "blocklist_monitoring_full", "whatsapp_full" ] ``` ### Responses [#responses-2] #### Valid [#valid-2] ```http Response Code: 200 OK Response Headers: content-type: application/json ``` ```json { "data": { "id": "b74c547a741e199d29c2bb38703fc4642c486841ab568b9fddc83be12329727022f6fb98291efd62", "accessToken": "[redacted]", "name": "Token", "created_at": "2020-06-10 10:10:14" } } ``` #### Error [#error-1] ```http Response Code: 422 Unprocessable Entity ``` *See - [Validation errors](/../../general#validation-errors)* ## Update a token [#update-a-token] Update an API token with this `PUT` request: ```http PUT https://api.mailersend.com/v1/token/{token_id} ``` #### Request parameters \[!toc] [#request-parameters-toc-3] | URL parameter | Type | Required | Limitations | Details | | ------------- | -------- | -------- | ----------- | ------- | | `token_id` | `string` | yes | | | #### Request Body \[!toc] [#request-body-toc-3] ```json { "status": "pause" } ``` ```php use MailerSend\MailerSend; use MailerSend\Helpers\Builder\TokenParams; $mailersend = new MailerSend(['api_key' => 'key']); $mailersend->token->update('token_id', TokenParams::STATUS_PAUSE); // PAUSE $mailersend->token->update('token_id', TokenParams::STATUS_UNPAUSE); // UNPAUSE ``` [More examples](https://github.com/mailersend/mailersend-php) ```javascript import 'dotenv/config'; import { MailerSend} from "mailersend"; const mailerSend = new MailerSend({ apiKey: process.env.API_KEY, }); mailerSend.token.updateSettings("token_id", { status: "pause", }) .then((response) => console.log(response.body)) .catch((error) => console.log(error.body)); ``` [More examples](https://github.com/mailersend/mailersend-nodejs) ```python from mailersend import MailerSendClient, TokensBuilder ms = MailerSendClient() # Pause token request = (TokensBuilder() .token_id("token-id") .status("pause") .build_token_update()) response = ms.tokens.update_token(request) # Unpause token request = (TokensBuilder() .token_id("token-id") .status("unpause") .build_token_update()) response = ms.tokens.update_token(request) ``` [More examples](https://github.com/mailersend/mailersend-python) ```go package main import ( "context" "log" "time" "github.com/mailersend/mailersend-go" ) var APIKey = "Api Key Here" func main() { // Create an instance of the mailersend client ms := mailersend.NewMailersend(APIKey) ctx := context.Background() ctx, cancel := context.WithTimeout(ctx, 5*time.Second) defer cancel() tokenID := "token-id" updateOptions := &mailersend.UpdateTokenOptions{ TokenID: tokenID, Status: "pause", } _, _, err := ms.Token.Update(ctx, updateOptions) if err != nil { log.Fatal(err) } } ``` [More examples](https://github.com/mailersend/mailersend-go) ```java import com.mailersend.sdk.MailerSend; import com.mailersend.sdk.exceptions.MailerSendException; import com.mailersend.sdk.tokens.Token; public void CreateToken() { MailerSend ms = new MailerSend(); ms.setToken(TestHelper.validToken); try { MailerSend ms = new MailerSend(); ms.setToken(TestHelper.validToken); try { // true to pause it, false to unpause it Token token = ms.tokens().updateToken(T"token id", true); System.out.println(token.name); System.out.println(token.status); } catch (MailerSendException e) { e.printStackTrace(); fail(); } } ``` [More examples](https://github.com/mailersend/mailersend-java) ```ruby require "mailersend-ruby" ms_tokens = Mailersend::Tokens.new ms_tokens.update(token_id: "d2220fx04", status: "pause") ``` [More examples](https://github.com/mailersend/mailersend-ruby) #### Request parameters \[!toc] [#request-parameters-toc-4] *JSON parameters are provided in dot notation.* | JSON parameter | Type | Required | Limitations | Details | | -------------- | -------- | ------------------------- | ------------------ | ------- | | `name` | `string` | required without `status` | Max: `50` | | | `status` | `string` | no | `pause`, `unpause` | | ### Responses [#responses-3] #### Valid [#valid-3] ```http Response Code: 200 OK Response Headers: content-type: application/json ``` ```json { "data": { "id": "481c8fdf59036be3f102b1ee6052e0f50a42051702dc5c820c1753d1752adc41ba5b1aaaaaaaaa", "name": "First token", "status": "unpause", "created_at": "2024-04-12T11:27:53.000000Z", "scopes": [ "email_full" ] } } ``` #### Error [#error-2] ```http Response Code: 422 Unprocessable Entity ``` *See - [Validation errors](/../../general#validation-errors)* ## Change token name [#change-token-name] Change an API token name with this `PUT` request: ```http PUT https://api.mailersend.com/v1/token/{token_id} ``` #### Request parameters \[!toc] [#request-parameters-toc-5] | URL parameter | Type | Required | Limitations | Details | | ------------- | -------- | -------- | ----------- | ------- | | `token_id` | `string` | yes | | | #### Request Body \[!toc] [#request-body-toc-4] ```json { "name": "new name" } ``` ```php use MailerSend\MailerSend; use MailerSend\Helpers\Builder\TokenParams; $mailersend = new MailerSend(['api_key' => 'key']); $mailersend->token->changeName('token_id', 'new name'); ``` [More examples](https://github.com/mailersend/mailersend-php) #### Request parameters \[!toc] [#request-parameters-toc-6] *JSON parameters are provided in dot notation.* | JSON parameter | Type | Required | Limitations | Details | | -------------- | ------ | -------- | ------------------- | ------- | | `name` | string | no | max length 50 chars | | ### Responses [#responses-4] #### Valid [#valid-4] ```http Response Code: 200 OK Response Headers: content-type: application/json ``` ```json { "data": { "id": "481c8fdf59036be3f102b1ee6052e0f50a42051702dc5c820c1753d1752adc41ba5b1aaaaaaaaa", "name": "First token", "status": "unpause", "created_at": "2024-04-12T11:27:53.000000Z", "scopes": [ "email_full" ] } } ``` #### Error [#error-3] ```http Response Code: 422 Unprocessable Entity ``` *See - [Validation errors](/../../general#validation-errors)* ## Delete a token [#delete-a-token] Delete an API token with this `DELETE` request: ```http DELETE https://api.mailersend.com/v1/token/{token_id} ``` #### Request parameters \[!toc] [#request-parameters-toc-7] | URL parameter | Type | Required | Limitations | Details | | ------------- | ------ | -------- | ----------- | ------- | | `token_id` | string | yes | | | ```php use MailerSend\MailerSend; use MailerSend\Helpers\Builder\TokenParams; $mailersend = new MailerSend(['api_key' => 'key']); $mailersend->token->delete('token_id'); ``` [More examples](https://github.com/mailersend/mailersend-php) ```javascript import 'dotenv/config'; import { MailerSend} from "mailersend"; const mailerSend = new MailerSend({ apiKey: process.env.API_KEY, }); mailerSend.token.delete("token_id") .then((response) => console.log(response.body)) .catch((error) => console.log(error.body)); ``` [More examples](https://github.com/mailersend/mailersend-nodejs) ```python from mailersend import MailerSendClient, TokensBuilder ms = MailerSendClient() request = (TokensBuilder() .token_id("token-id") .build_token_delete()) response = ms.tokens.delete_token(request) ``` [More examples](https://github.com/mailersend/mailersend-python) ```go package main import ( "context" "log" "time" "github.com/mailersend/mailersend-go" ) var APIKey = "Api Key Here" func main() { // Create an instance of the mailersend client ms := mailersend.NewMailersend(APIKey) ctx := context.Background() ctx, cancel := context.WithTimeout(ctx, 5*time.Second) defer cancel() tokenID := "token-id" _, err := ms.Token.Delete(ctx, tokenID) if err != nil { log.Fatal(err) } } ``` [More examples](https://github.com/mailersend/mailersend-go) ```java import com.mailersend.sdk.MailerSend; import com.mailersend.sdk.exceptions.MailerSendException; import com.mailersend.sdk.tokens.Token; public void CreateToken() { MailerSend ms = new MailerSend(); ms.setToken(TestHelper.validToken); try { MailerSendResponse response = ms.tokens().deleteToken("token to delete"); System.out.println(response.responseStatusCode); } catch (MailerSendException e) { e.printStackTrace(); } } ``` [More examples](https://github.com/mailersend/mailersend-java) ```ruby require "mailersend-ruby" ms_tokens = Mailersend::Tokens.new ms_tokens.delete(token_id: "d2220fx04") ``` [More examples](https://github.com/mailersend/mailersend-ruby) ### Responses [#responses-5] #### Valid [#valid-5] ```http Response Code: 200 OK Response Body: [EMPTY] ``` #### Error [#error-4] ```http Response Code: 404 Not Found ``` # Users (/api/v1/account/users) ## Get a list of account users [#get-a-list-of-account-users] Retrieve information about account users with this `GET` request: ```http GET https://api.mailersend.com/v1/users ``` #### Request parameters \[!toc] [#request-parameters-toc] | Query parameter | Type | Required | Limitations | Details | | --------------- | ----- | -------- | --------------------- | ------------- | | `limit` | `int` | no | Min: `10`, Max: `100` | Default: `25` | | `page` | `int` | no | Min: `1` | | ```php use MailerSend\MailerSend; $mailersend = new MailerSend(['api_key' => 'key']); $mailersend->user->getAll(); ``` [More examples](https://github.com/mailersend/mailersend-php) ```javascript import 'dotenv/config'; import { MailerSend } from "mailersend"; const mailerSend = new MailerSend({ apiKey: process.env.API_KEY, }); mailerSend.user.list() .then((response) => console.log(response.body)) .catch((error) => console.log(error.body)); ``` [More examples](https://github.com/mailersend/mailersend-nodejs) ```python from mailersend import MailerSendClient, UsersBuilder ms = MailerSendClient() request = (UsersBuilder() .page(1) .limit(25) .build_users_list()) response = ms.users.list_users(request) ``` [More examples](https://github.com/mailersend/mailersend-python) ```go package main import ( "context" "log" "time" "github.com/mailersend/mailersend-go" ) var APIKey = "Api Key Here" func main() { // Create an instance of the mailersend client ms := mailersend.NewMailersend(APIKey) ctx := context.Background() ctx, cancel := context.WithTimeout(ctx, 5*time.Second) defer cancel() options := &mailersend.ListUserOptions{ Page: 1, Limit: 25, } _, _, err := ms.User.List(ctx, options) if err != nil { log.Fatal(err) } } ``` [More examples](https://github.com/mailersend/mailersend-go) ```java import com.mailersend.sdk.MailerSend; import com.mailersend.sdk.users.User; import com.mailersend.sdk.users.UsersList; import com.mailersend.sdk.exceptions.MailerSendException; public void ListUsers() { MailerSend ms = new MailerSend(); ms.setToken("api token"); try { UsersList list = ms.users().getUsers(1, 25); for (User user : list.users) { System.out.println(user.id); System.out.println(user.email); } } catch (MailerSendException e) { e.printStackTrace(); } } ``` [More examples](https://github.com/mailersend/mailersend-java) ```ruby require "mailersend-ruby" ms_user = Mailersend::User.new ms_user.list ``` [More examples](https://github.com/mailersend/mailersend-ruby) ### Responses [#responses] #### Valid [#valid] ```http Response Code: 200 OK Response Headers: content-type: application/json ``` ```json { "data": [ { "id": "83gwk2j7zqz1nxyd", "avatar": null, "email": "user@example.com", "last_name": "User", "name": "User", "2fa": false, "created_at": "2024-01-18T06:59:00.000000Z", "updated_at": "2024-01-18T07:01:26.000000Z", "role": "Custom User", "permissions": ["read-suppressions", "read-invoice", "read-own-templates"], "domains": [ { "id": "0z76k5jg0o3yeg2d", "name": "example-domain.com", "created_at": "2024-02-20T08:13:17.000000Z", "updated_at": "2024-02-20T08:13:22.000000Z" }, { "id": "9dnxr7qvdqg6pm0e", "name": "another-domain.com", "created_at": "2024-02-20T08:47:06.000000Z", "updated_at": "2024-02-20T08:47:11.000000Z" } ], "templates": [ { "id": "n3k6d1jreo50x4ve", "name": "Template", "type": "gh", "created_at": "2024-02-23T15:40:51.000000Z" } ] } ] } ``` #### Error [#error] ```http Response Code: 404 Not Found ``` ## Get a single account user [#get-a-single-account-user] If you want to retrieve a single account user, use this `GET` request: ```http GET https://api.mailersend.com/v1/users/{user_id} ``` #### Request parameters \[!toc] [#request-parameters-toc-1] | URL parameter | Type | Required | Limitations | Details | | ------------- | -------- | -------- | ----------- | ------- | | `user_id` | `string` | yes | | | ```php use MailerSend\MailerSend; $mailersend = new MailerSend(['api_key' => 'key']); $mailersend->user->find('userId'); ``` [More examples](https://github.com/mailersend/mailersend-php) ```javascript import 'dotenv/config'; import { MailerSend } from "mailersend"; const mailerSend = new MailerSend({ apiKey: process.env.API_KEY, }); mailerSend.user.single("user-id") .then((response) => console.log(response.body)) .catch((error) => console.log(error.body)); ``` [More examples](https://github.com/mailersend/mailersend-nodejs) ```python from mailersend import MailerSendClient, UsersBuilder ms = MailerSendClient() request = (UsersBuilder() .user_id("user-id") .build_user_get()) response = ms.users.get_user(request) ``` [More examples](https://github.com/mailersend/mailersend-python) ```go package main import ( "context" "log" "time" "github.com/mailersend/mailersend-go" ) var APIKey = "Api Key Here" func main() { // Create an instance of the mailersend client ms := mailersend.NewMailersend(APIKey) ctx := context.Background() ctx, cancel := context.WithTimeout(ctx, 5*time.Second) defer cancel() userID := "user-id" _, _, err := ms.User.Get(ctx, userID) if err != nil { log.Fatal(err) } } ``` [More examples](https://github.com/mailersend/mailersend-go) ```java import com.mailersend.sdk.MailerSend; import com.mailersend.sdk.users.User; import com.mailersend.sdk.exceptions.MailerSendException; public void GetUser() { MailerSend ms = new MailerSend(); ms.setToken("api token"); try { User user = ms.users().getUser("user-id"); System.out.println(user.id); System.out.println(user.email); System.out.println(user.name); } catch (MailerSendException e) { e.printStackTrace(); } } ``` [More examples](https://github.com/mailersend/mailersend-java) ```ruby require "mailersend-ruby" ms_user = Mailersend::User.new ms_user.get("user-id") ``` [More examples](https://github.com/mailersend/mailersend-ruby) ### Responses [#responses-1] #### Valid [#valid-1] ```http Response Code: 200 OK Response Headers: content-type: application/json ``` ```json { "data": { "id": "83gwk2j7zqz1nxyd", "avatar": null, "email": "user@example.com", "last_name": "User", "name": "User", "2fa": false, "created_at": "2024-01-18T06:59:00.000000Z", "updated_at": "2024-01-18T07:01:26.000000Z", "role": "Custom User", "permissions": ["read-suppressions", "read-invoice", "read-own-templates"], "domains": [ { "id": "0z76k5jg0o3yeg2d", "name": "example-domain.com", "created_at": "2024-02-20T08:13:17.000000Z", "updated_at": "2024-02-20T08:13:22.000000Z" }, { "id": "9dnxr7qvdqg6pm0e", "name": "another-domain.com", "created_at": "2024-02-20T08:47:06.000000Z", "updated_at": "2024-02-20T08:47:11.000000Z" } ], "templates": [ { "id": "n3k6d1jreo50x4ve", "name": "Template", "type": "gh", "created_at": "2024-02-23T15:40:51.000000Z" } ] } } ``` #### Error [#error-1] ```http Response Code: 404 Not Found ``` ## Invite a user to account [#invite-a-user-to-account] If you want to add a new user to your account, use this `POST` request: ```http POST https://api.mailersend.com/v1/users ``` ### Request Parameters \[!toc] [#request-parameters-toc-2] *JSON parameters are provided in dot notation* | JSON Parameter | Type | Required | Limitations | Details | | ----------------------------------- | ---------- | -------- | -------------------------------- | ----------------------------------------------------------------------------- | | `email` | `string` | yes | `Max` 320 characters, unique | | | `role` | `string` | yes | Must be the name of a role | [View roles](#roles) | | `permissions` | `string[]` | yes\* | Must be list of permission names | \*Only required if role is a `Custom User`. [View permissions](#permissions) | | `templates` | `string[]` | no | Must be list of template IDs | | | `domains` | `string[]` | no | Must be list of domain IDs | | | `requires_periodic_password_change` | `boolean` | no | | | ```php use MailerSend\MailerSend; use MailerSend\Helpers\Builder\UserParams; use MailerSend\Common\Roles; use MailerSend\Common\Permissions; $mailersend = new MailerSend(['api_key' => 'key']); // Basic invite with admin role $mailersend->user->create( (new UserParams('newuser@example.com', Roles::ADMIN)) ); // Custom invite with specific permissions and access $mailersend->user->create( (new UserParams('designer@example.com', Roles::CUSTOM_USER)) ->setDomains(['domain-id']) ->setTemplates(['template-id']) ->setPermissions([Permissions::READ_OWN_TEMPLATES]) ->setRequiresPeriodicPasswordChange(true) ); ``` [More examples](https://github.com/mailersend/mailersend-php) ```javascript import 'dotenv/config'; import { MailerSend, User } from "mailersend"; const mailerSend = new MailerSend({ apiKey: process.env.API_KEY, }); // Basic invite with admin role const user = new User() .setEmail("newuser@example.com") .setRole("admin"); mailerSend.user.create(user) .then((response) => console.log(response.body)) .catch((error) => console.log(error.body)); // Custom invite with specific permissions const customUser = new User() .setEmail("designer@example.com") .setRole("designer") .addPermission("read-all-templates") .addPermission("manage-template") .addTemplate("template-id") .addDomain("domain-id") .setRequiresPeriodicPasswordChange(true); mailerSend.user.create(customUser) .then((response) => console.log(response.body)) .catch((error) => console.log(error.body)); ``` [More examples](https://github.com/mailersend/mailersend-nodejs) ```python from mailersend import MailerSendClient, UsersBuilder ms = MailerSendClient() # Basic invite with admin role request = (UsersBuilder() .email("newuser@example.com") .admin_role() .build_user_invite()) response = ms.users.invite_user(request) # Custom invite with specific permissions and access request = (UsersBuilder() .email("designer@example.com") .designer_role() .add_permission("read-all-templates") .add_permission("manage-template") .add_template("template-id") .add_domain("domain-id") .requires_periodic_password_change(True) .build_user_invite()) response = ms.users.invite_user(request) ``` [More examples](https://github.com/mailersend/mailersend-python) ```go package main import ( "context" "log" "time" "github.com/mailersend/mailersend-go" ) var APIKey = "Api Key Here" func main() { // Create an instance of the mailersend client ms := mailersend.NewMailersend(APIKey) ctx := context.Background() ctx, cancel := context.WithTimeout(ctx, 5*time.Second) defer cancel() // Basic invite with admin role options := &mailersend.CreateUserOptions{ Email: "newuser@example.com", Role: mailersend.String("admin"), } _, _, err := ms.User.Create(ctx, options) if err != nil { log.Fatal(err) } // Custom invite with specific permissions customOptions := &mailersend.CreateUserOptions{ Email: "designer@example.com", Role: mailersend.String("designer"), Permissions: []string{"read-all-templates", "manage-template"}, TemplateIDs: []string{"template-id"}, DomainIDs: []string{"domain-id"}, RequiresPeriodicPasswordChange: mailersend.Bool(true), } _, _, err = ms.User.Create(ctx, customOptions) if err != nil { log.Fatal(err) } } ``` [More examples](https://github.com/mailersend/mailersend-go) ```java import com.mailersend.sdk.MailerSend; import com.mailersend.sdk.users.User; import com.mailersend.sdk.exceptions.MailerSendException; public void InviteUser() { MailerSend ms = new MailerSend(); ms.setToken("api token"); try { // Basic invite with admin role User user = ms.users().builder() .email("newuser@example.com") .role("admin") .createUser(); System.out.println(user.id); // Custom invite with specific permissions User customUser = ms.users().builder() .email("designer@example.com") .role("designer") .addPermission("read-all-templates") .addPermission("manage-template") .addTemplate("template-id") .addDomain("domain-id") .requiresPeriodicPasswordChange(true) .createUser(); System.out.println(customUser.id); } catch (MailerSendException e) { e.printStackTrace(); } } ``` [More examples](https://github.com/mailersend/mailersend-java) ```ruby require "mailersend-ruby" ms_user = Mailersend::User.new # Basic invite with admin role ms_user.create(email: "newuser@example.com", role: "admin") # Custom invite with specific permissions ms_user.create( email: "designer@example.com", role: "designer", permissions: ["read-all-templates", "manage-template"], templates: ["template-id"], domains: ["domain-id"], requires_periodic_password_change: true ) ``` [More examples](https://github.com/mailersend/mailersend-ruby) ### Responses [#responses-2] | Response Key | Type | Details | | ------------ | ------ | --------------------------- | | data | object | User invite object created. | #### Valid [#valid-2] ```http Response Code: 200 OK Response Headers: content-type: application/json ``` ```json { "data": { "id": "n3k6d1jrveq50x4v", "email": "user@example.com", "data": null, "permissions": ["manage-api-token", "read-filemanager"], "role": "Custom User", "requires_periodic_password_change": false, "created_at": "2024-01-24T06:40:19.000000Z", "updated_at": "2024-01-24T06:40:19.000000Z" } } ``` #### Invalid [#invalid] ```http Response Code: 422 Unprocessable Entity ``` *See - [Validation errors](/../../general#validation-errors)* ## Update account user [#update-account-user] If you want to update the information of an existing account user, use this `PUT` request: ```http PUT https://api.mailersend.com/v1/users/{user_id} ``` ### Request Parameters \[!toc] [#request-parameters-toc-3] | URL parameter | Type | Required | Limitations | Details | | ------------- | -------- | -------- | ----------- | ------- | | `user_id` | `string` | yes | | | *JSON parameters are provided in dot notation* | JSON Parameter | Type | Required | Limitations | Details | | ----------------------------------- | ---------- | -------- | -------------------------------- | ----------------------------------------------------------------------------- | | `role` | `string` | yes | Must be the name of a role | [View roles](#roles) | | `permissions` | `string[]` | yes\* | Must be list of permission names | \*Only required if role is a `Custom User`. [View permissions](#permissions) | | `templates` | `string[]` | no | Must be list of template IDs | | | `domains` | `string[]` | no | Must be list of domain IDs | | | `requires_periodic_password_change` | `boolean` | no | | | ```php use MailerSend\MailerSend; use MailerSend\Helpers\Builder\UserParams; use MailerSend\Common\Roles; use MailerSend\Common\Permissions; $mailersend = new MailerSend(['api_key' => 'key']); $mailersend->user->update( 'userId', (new UserParams()) ->setRole(Roles::CUSTOM_USER) ->setDomains(['domain-id']) ->setPermissions([Permissions::READ_OWN_TEMPLATES]) ->setRequiresPeriodicPasswordChange(true) ); ``` [More examples](https://github.com/mailersend/mailersend-php) ```javascript import 'dotenv/config'; import { MailerSend, User } from "mailersend"; const mailerSend = new MailerSend({ apiKey: process.env.API_KEY, }); const user = new User() .setRole("manager") .addPermission("read-analytics") .addPermission("read-activity") .addDomain("domain-id"); mailerSend.user.update("user-id", user) .then((response) => console.log(response.body)) .catch((error) => console.log(error.body)); ``` [More examples](https://github.com/mailersend/mailersend-nodejs) ```python from mailersend import MailerSendClient, UsersBuilder ms = MailerSendClient() request = (UsersBuilder() .user_id("user-id") .manager_role() .add_permission("read-analytics") .add_permission("read-activity") .add_domain("domain-id") .build_user_update()) response = ms.users.update_user(request) ``` [More examples](https://github.com/mailersend/mailersend-python) ```go package main import ( "context" "log" "time" "github.com/mailersend/mailersend-go" ) var APIKey = "Api Key Here" func main() { // Create an instance of the mailersend client ms := mailersend.NewMailersend(APIKey) ctx := context.Background() ctx, cancel := context.WithTimeout(ctx, 5*time.Second) defer cancel() userID := "user-id" options := &mailersend.UpdateUserOptions{ Role: mailersend.String("manager"), Permissions: []string{"read-analytics", "read-activity"}, DomainIDs: []string{"domain-id"}, } _, _, err := ms.User.Update(ctx, userID, options) if err != nil { log.Fatal(err) } } ``` [More examples](https://github.com/mailersend/mailersend-go) ```java import com.mailersend.sdk.MailerSend; import com.mailersend.sdk.users.User; import com.mailersend.sdk.exceptions.MailerSendException; public void UpdateUser() { MailerSend ms = new MailerSend(); ms.setToken("api token"); try { User user = ms.users().builder() .role("manager") .addPermission("read-analytics") .addPermission("read-activity") .addDomain("domain-id") .updateUser("user-id"); System.out.println(user.id); System.out.println(user.email); } catch (MailerSendException e) { e.printStackTrace(); } } ``` [More examples](https://github.com/mailersend/mailersend-java) ```ruby require "mailersend-ruby" ms_user = Mailersend::User.new ms_user.update( "user-id", role: "manager", permissions: ["read-analytics", "read-activity"], domains: ["domain-id"] ) ``` [More examples](https://github.com/mailersend/mailersend-ruby) ### Responses [#responses-3] | Response Key | Type | Details | | ------------ | ------ | -------------------- | | data | object | User object updated. | #### Valid [#valid-3] ```http Response Code: 200 OK Response Headers: content-type: application/json ``` ```json { "data": { "id": "4k386zo42j07xv52", "avatar": null, "email": "user@example.com", "last_name": "User", "name": "User", "2fa": false, "created_at": "2024-01-22T09:35:04.000000Z", "updated_at": "2024-01-22T23:40:44.000000Z", "role": "Manager" } } ``` #### Invalid [#invalid-1] ```http Response Code: 422 Unprocessable Entity ``` *See - [Validation errors](/../../general#validation-errors)* ## Delete a user from account [#delete-a-user-from-account] If you want to delete a user from account, use this `DELETE` request: ```http DELETE https://api.mailersend.com/v1/users/{user_id} ``` ### Request parameters \[!toc] [#request-parameters-toc-4] | URL parameter | Type | Required | Limitations | Details | | ------------- | -------- | -------- | ----------- | ------- | | `user_id` | `string` | yes | | | ```php use MailerSend\MailerSend; $mailersend = new MailerSend(['api_key' => 'key']); $mailersend->user->delete('userId'); ``` [More examples](https://github.com/mailersend/mailersend-php) ```javascript import 'dotenv/config'; import { MailerSend } from "mailersend"; const mailerSend = new MailerSend({ apiKey: process.env.API_KEY, }); mailerSend.user.delete("user-id") .then((response) => console.log(response.body)) .catch((error) => console.log(error.body)); ``` [More examples](https://github.com/mailersend/mailersend-nodejs) ```python from mailersend import MailerSendClient, UsersBuilder ms = MailerSendClient() request = (UsersBuilder() .user_id("user-id") .build_user_delete()) response = ms.users.delete_user(request) ``` [More examples](https://github.com/mailersend/mailersend-python) ```go package main import ( "context" "log" "time" "github.com/mailersend/mailersend-go" ) var APIKey = "Api Key Here" func main() { // Create an instance of the mailersend client ms := mailersend.NewMailersend(APIKey) ctx := context.Background() ctx, cancel := context.WithTimeout(ctx, 5*time.Second) defer cancel() userID := "user-id" _, _, err := ms.User.Delete(ctx, userID) if err != nil { log.Fatal(err) } } ``` [More examples](https://github.com/mailersend/mailersend-go) ```java import com.mailersend.sdk.MailerSend; import com.mailersend.sdk.exceptions.MailerSendException; public void DeleteUser() { MailerSend ms = new MailerSend(); ms.setToken("api token"); try { ms.users().deleteUser("user-id"); System.out.println("User deleted successfully"); } catch (MailerSendException e) { e.printStackTrace(); } } ``` [More examples](https://github.com/mailersend/mailersend-java) ```ruby require "mailersend-ruby" ms_user = Mailersend::User.new ms_user.delete("user-id") ``` [More examples](https://github.com/mailersend/mailersend-ruby) ### Responses [#responses-4] #### Valid [#valid-4] ```http Response Code: 204 No Content ``` #### Error [#error-2] ```http Response Code: 404 Not Found ``` ## Get a list of invites [#get-a-list-of-invites] Retrieve information about account invited users with this `GET` request: ```http GET https://api.mailersend.com/v1/invites ``` #### Request parameters \[!toc] [#request-parameters-toc-5] | Query parameter | Type | Required | Limitations | Details | | --------------- | ----- | -------- | --------------------- | ------------- | | `limit` | `int` | no | Min: `10`, Max: `100` | Default: `25` | | `page` | `int` | no | Min: `1` | | ```php use MailerSend\MailerSend; $mailersend = new MailerSend(['api_key' => 'key']); $mailersend->invite->getAll(); ``` [More examples](https://github.com/mailersend/mailersend-php) ```javascript import 'dotenv/config'; import { MailerSend } from "mailersend"; const mailerSend = new MailerSend({ apiKey: process.env.API_KEY, }); mailerSend.invite.list() .then((response) => console.log(response.body)) .catch((error) => console.log(error.body)); ``` [More examples](https://github.com/mailersend/mailersend-nodejs) ```python from mailersend import MailerSendClient, UsersBuilder ms = MailerSendClient() request = (UsersBuilder() .page(1) .limit(25) .build_invites_list()) response = ms.users.list_invites(request) ``` [More examples](https://github.com/mailersend/mailersend-python) ```go package main import ( "context" "log" "time" "github.com/mailersend/mailersend-go" ) var APIKey = "Api Key Here" func main() { // Create an instance of the mailersend client ms := mailersend.NewMailersend(APIKey) ctx := context.Background() ctx, cancel := context.WithTimeout(ctx, 5*time.Second) defer cancel() options := &mailersend.ListInviteOptions{ Page: 1, Limit: 25, } _, _, err := ms.Invite.List(ctx, options) if err != nil { log.Fatal(err) } } ``` [More examples](https://github.com/mailersend/mailersend-go) ```java import com.mailersend.sdk.MailerSend; import com.mailersend.sdk.invites.Invite; import com.mailersend.sdk.invites.InvitesList; import com.mailersend.sdk.exceptions.MailerSendException; public void ListInvites() { MailerSend ms = new MailerSend(); ms.setToken("api token"); try { InvitesList list = ms.invites().getInvites(1, 25); for (Invite invite : list.invites) { System.out.println(invite.id); System.out.println(invite.email); } } catch (MailerSendException e) { e.printStackTrace(); } } ``` [More examples](https://github.com/mailersend/mailersend-java) ```ruby require "mailersend-ruby" ms_invite = Mailersend::Invite.new ms_invite.list ``` [More examples](https://github.com/mailersend/mailersend-ruby) ### Responses [#responses-5] #### Valid [#valid-5] ```http Response Code: 200 OK Response Headers: content-type: application/json ``` ```json { "data": [ { "id": "dle1krod2jvn8gwm", "email": "user@example.com", "data": { "domains": ["n3k6d1jrveq50x4v"], "templates": ["0z76k5jg0o3yeg2d"] }, "role": "Custom User", "permissions": ["read-own-templates"], "requires_periodic_password_change": true, "created_at": "2024-04-25T17:09:23.000000Z", "updated_at": "2024-04-25T17:09:23.000000Z" } ] } ``` #### Error [#error-3] ```http Response Code: 404 Not Found ``` ## Get a single invite [#get-a-single-invite] If you want to retrieve a single invite, use this `GET` request: ```http GET https://api.mailersend.com/v1/invites/{invite_id} ``` #### Request parameters \[!toc] [#request-parameters-toc-6] | URL parameter | Type | Required | Limitations | Details | | ------------- | -------- | -------- | ----------- | ------- | | `invite_id` | `string` | yes | | | ```php use MailerSend\MailerSend; $mailersend = new MailerSend(['api_key' => 'key']); $mailersend->invite->find('inviteId'); ``` [More examples](https://github.com/mailersend/mailersend-php) ```javascript import 'dotenv/config'; import { MailerSend } from "mailersend"; const mailerSend = new MailerSend({ apiKey: process.env.API_KEY, }); mailerSend.invite.single("invite-id") .then((response) => console.log(response.body)) .catch((error) => console.log(error.body)); ``` [More examples](https://github.com/mailersend/mailersend-nodejs) ```python from mailersend import MailerSendClient, UsersBuilder ms = MailerSendClient() request = (UsersBuilder() .invite_id("invite-id") .build_invite_get()) response = ms.users.get_invite(request) ``` [More examples](https://github.com/mailersend/mailersend-python) ```go package main import ( "context" "log" "time" "github.com/mailersend/mailersend-go" ) var APIKey = "Api Key Here" func main() { // Create an instance of the mailersend client ms := mailersend.NewMailersend(APIKey) ctx := context.Background() ctx, cancel := context.WithTimeout(ctx, 5*time.Second) defer cancel() inviteID := "invite-id" _, _, err := ms.Invite.Get(ctx, inviteID) if err != nil { log.Fatal(err) } } ``` [More examples](https://github.com/mailersend/mailersend-go) ```java import com.mailersend.sdk.MailerSend; import com.mailersend.sdk.invites.Invite; import com.mailersend.sdk.exceptions.MailerSendException; public void GetInvite() { MailerSend ms = new MailerSend(); ms.setToken("api token"); try { Invite invite = ms.invites().getInvite("invite-id"); System.out.println(invite.id); System.out.println(invite.email); } catch (MailerSendException e) { e.printStackTrace(); } } ``` [More examples](https://github.com/mailersend/mailersend-java) ```ruby require "mailersend-ruby" ms_invite = Mailersend::Invite.new ms_invite.get("invite-id") ``` [More examples](https://github.com/mailersend/mailersend-ruby) ### Responses [#responses-6] #### Valid [#valid-6] ```http Response Code: 200 OK Response Headers: content-type: application/json ``` ```json { "data": { "id": "dle1krod2jvn8gwm", "email": "test7@user.com", "data": { "domains": ["n3k6d1jrveq50x4v"], "templates": ["0z76k5jg0o3yeg2d"] }, "role": "Custom User", "permissions": ["read-own-templates"], "requires_periodic_password_change": true, "created_at": "2024-04-25T17:09:23.000000Z", "updated_at": "2024-04-25T17:09:23.000000Z" } } ``` ## Resend an invite [#resend-an-invite] If you want to resend a user invite, use this `POST` request: ```http POST https://api.mailersend.com/v1/invites/{invite_id}/resend ``` #### Request parameters \[!toc] [#request-parameters-toc-7] | URL parameter | Type | Required | Limitations | Details | | ------------- | -------- | -------- | ----------- | ------- | | `invite_id` | `string` | yes | | | ```php use MailerSend\MailerSend; $mailersend = new MailerSend(['api_key' => 'key']); $mailersend->invite->resend('inviteId'); ``` [More examples](https://github.com/mailersend/mailersend-php) ```javascript import 'dotenv/config'; import { MailerSend } from "mailersend"; const mailerSend = new MailerSend({ apiKey: process.env.API_KEY, }); mailerSend.invite.resend("invite-id") .then((response) => console.log(response.body)) .catch((error) => console.log(error.body)); ``` [More examples](https://github.com/mailersend/mailersend-nodejs) ```python from mailersend import MailerSendClient, UsersBuilder ms = MailerSendClient() request = (UsersBuilder() .invite_id("invite-id") .build_invite_resend()) response = ms.users.resend_invite(request) ``` [More examples](https://github.com/mailersend/mailersend-python) ```go package main import ( "context" "log" "time" "github.com/mailersend/mailersend-go" ) var APIKey = "Api Key Here" func main() { // Create an instance of the mailersend client ms := mailersend.NewMailersend(APIKey) ctx := context.Background() ctx, cancel := context.WithTimeout(ctx, 5*time.Second) defer cancel() inviteID := "invite-id" _, _, err := ms.Invite.Resend(ctx, inviteID) if err != nil { log.Fatal(err) } } ``` [More examples](https://github.com/mailersend/mailersend-go) ```java import com.mailersend.sdk.MailerSend; import com.mailersend.sdk.exceptions.MailerSendException; public void ResendInvite() { MailerSend ms = new MailerSend(); ms.setToken("api token"); try { ms.invites().resendInvite("invite-id"); System.out.println("Invite resent successfully"); } catch (MailerSendException e) { e.printStackTrace(); } } ``` [More examples](https://github.com/mailersend/mailersend-java) ```ruby require "mailersend-ruby" ms_invite = Mailersend::Invite.new ms_invite.resend("invite-id") ``` [More examples](https://github.com/mailersend/mailersend-ruby) ### Responses [#responses-7] #### Valid [#valid-7] ```http Response Code: 200 OK Response Headers: content-type: application/json ``` ```json { "data": { "id": "dle1krod2jvn8gwm", "email": "test7@user.com", "data": { "domains": ["n3k6d1jrveq50x4v"], "templates": ["0z76k5jg0o3yeg2d"] }, "role": "Custom User", "permissions": ["read-own-templates"], "requires_periodic_password_change": true, "created_at": "2024-04-25T17:09:23.000000Z", "updated_at": "2024-04-25T17:09:23.000000Z" } } ``` #### Error [#error-4] ```http Response Code: 404 Not Found ``` ## Cancel an invite [#cancel-an-invite] If you want to cancel a user invite from account, use this `DELETE` request: ```http DELETE https://api.mailersend.com/v1/invites/{invite_id} ``` ### Request parameters \[!toc] [#request-parameters-toc-8] | URL parameter | Type | Required | Limitations | Details | | ------------- | -------- | -------- | ----------- | ------- | | `invite_id` | `string` | yes | | | ```php use MailerSend\MailerSend; $mailersend = new MailerSend(['api_key' => 'key']); $mailersend->invite->cancel('inviteId'); ``` [More examples](https://github.com/mailersend/mailersend-php) ```javascript import 'dotenv/config'; import { MailerSend } from "mailersend"; const mailerSend = new MailerSend({ apiKey: process.env.API_KEY, }); mailerSend.invite.cancel("invite-id") .then((response) => console.log(response.body)) .catch((error) => console.log(error.body)); ``` [More examples](https://github.com/mailersend/mailersend-nodejs) ```python from mailersend import MailerSendClient, UsersBuilder ms = MailerSendClient() request = (UsersBuilder() .invite_id("invite-id") .build_invite_cancel()) response = ms.users.cancel_invite(request) ``` [More examples](https://github.com/mailersend/mailersend-python) ```go package main import ( "context" "log" "time" "github.com/mailersend/mailersend-go" ) var APIKey = "Api Key Here" func main() { // Create an instance of the mailersend client ms := mailersend.NewMailersend(APIKey) ctx := context.Background() ctx, cancel := context.WithTimeout(ctx, 5*time.Second) defer cancel() inviteID := "invite-id" _, _, err := ms.Invite.Cancel(ctx, inviteID) if err != nil { log.Fatal(err) } } ``` [More examples](https://github.com/mailersend/mailersend-go) ```java import com.mailersend.sdk.MailerSend; import com.mailersend.sdk.exceptions.MailerSendException; public void CancelInvite() { MailerSend ms = new MailerSend(); ms.setToken("api token"); try { ms.invites().cancelInvite("invite-id"); System.out.println("Invite cancelled successfully"); } catch (MailerSendException e) { e.printStackTrace(); } } ``` [More examples](https://github.com/mailersend/mailersend-java) ```ruby require "mailersend-ruby" ms_invite = Mailersend::Invite.new ms_invite.cancel("invite-id") ``` [More examples](https://github.com/mailersend/mailersend-ruby) ### Responses [#responses-8] #### Valid [#valid-8] ```http Response Code: 204 OK ``` #### Error [#error-5] ```http Response Code: 404 Not Found ``` ## Roles [#roles] | Name | Description | | ----------- | ------------------------------------------------------------------------- | | Admin | Administrator has full access and can perform all actions in the account. | | Manager | Has full access, access API and billing. | | Designer | Designers can only view and create templates. | | Accountant | Can only manage payments and access invoices. | | Custom User | Select the sections of your account that the user should have access to. | ## Permissions [#permissions] | Name | Description | Group | | -------------------------- | ------------------------------- | ------------------ | | read-all-templates | View all templates | Templates | | read-own-templates | View specific templates | Templates | | manage-template | Manage templates | Templates | | read-filemanager | View the file manager | Templates | | manage-domain | Manage domain | Domains | | manage-inbound | Manage inbound routes | Domains | | manage-webhook | Manage webhooks | Domains | | control-sendings | Control sendings | Domains | | control-tracking-options | Control tracking option | Domains | | access-smtp-credentials | Access SMTP credentials | Domains | | view-smtp-users | View SMTP users | Domains | | manage-smtp-users | Manage SMTP users | Domains | | read-recipient | View recipients | Recipient | | read-activity | View email activity | Activity | | read-email | View email content | Activity | | read-analytics | View email analytics | Analytics | | read-sender-identities | View sender identities | Sender identities | | manage-sender-identities | Manage sender identities | Sender identities | | read-email-verification | View email verifications lists | Email verification | | manage-email-verification | Manage email verification lists | Email verification | | manage-sms | Manage numbers | SMS | | read-sms | View SMS activity | SMS | | manage-verified-recipients | Manage verified recipients | SMS | | view-sms-webhooks | View number webhooks | SMS | | manage-sms-webhooks | Manage number webhooks | SMS | | view-sms-inbound | View number inbound routes | SMS | | manage-sms-inbound | Manage number inbound routes | SMS | | update-plan | Manage plans | Plan and Billing | | manage-account | Edit account settings | Plan and Billing | | read-invoice | View invoices | Account settings | | manage-api-token | Manage API tokens | Account settings | | read-suppressions | View suppressions lists | Account settings | | manage-suppressions | Manage suppressions | Account settings | | read-ip-addresses | View IP allowlist | Account settings | | manage-ip-addresses | Manage IP allowlist | Account settings | | read-error-log | View error log | Account settings | # Webhooks (/api/v1/account/webhooks) Webhooks allow you to subscribe to real-time notifications about various events that occur in MailerSend. You can create a webhook directly from your MailerSend account and listen for events so your integration can automatically trigger reactions. ## Webhooks overview [#webhooks-overview] ### Setup [#setup] Currently, you can create a webhook using the API endpoints listed below or directly from your account. [Read more about webhooks](https://www.mailersend.com/help/webhooks). If your endpoint is unreachable or returns a non-2xx response, MailerSend automatically retries with exponential backoff for up to about 3 days. While your webhook is failing we'll send escalating email notifications. If the endpoint stays down too long, the webhook is automatically paused. You can re-enable it from your dashboard at any time. ### URL validation [#url-validation] When creating or updating a webhook, MailerSend will send a test request to the provided URL to verify that it is reachable. The endpoint must return a `2xx` response for the webhook to be saved successfully. The test request uses the following payload: ```json { "type": "webhook.test", "message": "This is a ping test message", "created_at": "2026-03-27T07:24:20.577080Z" } ``` This test request is signed with a fixed test secret: `test_Am3L1GuOIc4blLUuHqAPxxwkZaJyEk8G`. Use it to verify the signature of incoming test requests. ### Available events [#available-events] These are all the events you can listen to and send a notification for. | Event | Description | | --------------------------- | -------------------------------------------------------------------------------------------------------------------------- | | `activity.sent` | Fired when your email is sent from our sending servers. We are now waiting for a response from the receiving servers. | | `activity.delivered` | Fired when your email is successfully delivered with no errors. | | `activity.soft_bounced` | Fired when your email is not delivered because it soft bounced. | | `activity.hard_bounced` | Fired when your email is not delivered. | | `activity.deferred` | Fired when your email is temporarily delayed. `Please note that this is available to Paid plans only` | | `activity.opened` | Fired when the recipient receives your email and opens it. | | `activity.opened_unique` | Fired when the recipient receives your email and opens it only for the first time. | | `activity.clicked` | Fired when the recipient clicks a link in your email. | | `activity.clicked_unique` | Fired when the recipient clicks a link in your email only for the first time. | | `activity.unsubscribed` | Fired when the recipient unsubscribes from your emails. | | `activity.spam_complaint` | Fired when the recipient marks your emails as spam or junk. | | `activity.survey_opened` | Fired when the recipient opens an email containting a survey for the first time. | | `activity.survey_submitted` | Fired when the recipient answers all available questions in a survey based email or after an idle time of `30` minutes. | | `sender_identity.verified` | Fired when the sender identity has been successfully verified. | | `maintenance.start` | Fired when the maintenance period begins. (More info in [Handling Maintenance Modes](/guides/handling-maintenance-modes)). | | `maintenance.end` | Fired when the maintenance period ends. (More info in [Handling Maintenance Modes](/guides/handling-maintenance-modes)). | | `inbound_forward.failed` | Fired when an inbound message fail to forward. | | `inbound_message.rejected` | Fired when an inbound message is rejected. Possible reasons: `unsupported_attachment_type`, `attachment_size_exceeded`. | | `email_single.verified` | Fired when single email has been successfully verified. | | `email_list.verified` | Fired when email verification list has been successfully verified. | | `bulk_email.completed` | Fired when bulk email sending has been successfully completed. | | `recipient.on_hold_added` | Fired when recipient is added to on-hold suppression list. | | `recipient.on_hold_removed` | Fired when recipient is removed from on-hold suppression list. | ### Payload example [#payload-example] Select an event type to see an example of the payload sent to your webhook endpoint: ```json { "type":"activity.sent", "created_at":"2025-08-05T21:23:54.000000Z", "data":{ "id":"6892766a5b66e2daf3dc9155", "domain_id": "yv69oxl5kl785kw2", "message_id":"6892766ae78995a317577aa1", "email_id":"6892766a8d52ba62543d5e71", "type":"sent", "subject": "Test email", "email": "test@mailersend.com", "tags":[ "test", "test2" ], "meta": [] } } ``` ```json { "type": "activity.survey_submitted", "created_at": "2025-08-06T00:20:36.589903Z", "data": { "id": "68929fd47f916891ef12eba9", "domain_id": "7nxe3yjmeq28vp0k", "message_id": "68929fd402fd7079a02cf858", "email_id": "68929fd47f916891ef12eba9", "type": "survey_submitted", "subject": "Test email", "email": "test@mailersend.com", "tags": [ "test2", "test3" ], "meta": { "surveys": [ { "question_id": 1, "survey_id": 1, "answer": "test", "is_last_question": true } ] } } } ``` ```json { "type": "sender_identity.verified", "created_at": "2025-08-05 22:27:14", "data": { "object": "sender_identity", "id": "w942pzo81qnvm651", "email": "miller.erin@example.net", "name": "Prof. Luella Greenholt", "reply_to_email": "wdietrich@example.net", "reply_to_name": "Narciso Smitham", "is_verified": true, "resends": 0, "add_note": true, "personal_note": "porro doloribus quidem" } } ``` ```json { "type": "maintenance.start", "created_at": "2025-08-05 22:27:14", "data": { "domain_id": "7nxe3yjmeq28vp0k" } } ``` ```json { "type": "maintenance.end", "created_at": "2025-08-05 22:27:31", "data": { "domain_id": "7nxe3yjmeq28vp0k" } } ``` ```json { "type": "inbound_forward.failed", "created_at": "2025-08-05 22:27:14", "data": { "domain_id": "7nxe3yjmeq28vp0k", "inbound_id": "7nxe3yjmeq28vp0k", "inbound_message_id": "68929bf482496e1365e9bd71" } } ``` ```json { "type": "inbound_message.rejected", "created_at": "2025-08-05T22:27:14.000000Z", "data": { "domain_id": "7nxe3yjmeq28vp0k", "inbound_id": "7nxe3yjmeq28vp0k", "inbound_message_id": "68929bf482496e1365e9bd71", "reason": "unsupported_attachment_type" } } ``` ```json { "type": "email_single.verified", "created_at": "2025-08-05 22:27:14", "data": { "id": "68928a46a23f15a8bcbbafb6", "address": "aurore20@senger.net", "status": "completed", "result": "valid", "error": null } } ``` ```json { "type": "email_list.verified", "created_at": "2025-08-05 22:27:14", "data": { "id": "lx1p78jk1o53rzn4", "name": "verify-test - Sheet1.csv", "total": 1, "verification_started": "2025-08-05T22:50:31.000000Z", "verification_ended": null, "updated_at": "2025-08-05T22:50:41.000000Z", "status": { "name": "verified", "count": 0 }, "source": "api", "statistics": { "valid": 0, "catch_all": 0, "mailbox_full": 0, "role_based": 0, "unknown": 1, "syntax_error": 0, "typo": 0, "mailbox_not_found": 0, "disposable": 0, "mailbox_blocked": 0, "failed": 0, "not_verified": 0 } } } ``` ```json { "type": "bulk_email.completed", "created_at": "2025-08-05 22:27:14", "data": { "id": "689286b1cf375b31ffa45498", "state": "completed", "total_recipients_count": 11, "suppressed_recipients_count": 0, "suppressed_recipients": null, "validation_errors_count": 0, "validation_errors": null, "messages_id": null } } ``` ```json { "type": "recipient.on_hold_added", "created_at": "2026-03-18T16:38:48.607580Z", "data": { "domain_id": "8jy7zpl90l5vx6kq", "object": "on_hold_recipient", "email": "test@example.com", "added_at": "2026-03-18T16:38:48.000000Z", "on_hold_until": "2026-03-21T16:38:48.000000Z" } } ``` ```json { "type": "recipient.on_hold_removed", "created_at": "2026-03-18T16:38:48.607580Z", "data": { "domain_id": "8jy7zpl90l5vx6kq", "object": "on_hold_recipient", "email": "test@example.com", "added_at": "2026-03-18T16:38:48.000000Z", "on_hold_until": "2026-03-21T16:38:48.000000Z" } } ``` ### Security [#security] Webhook requests made by MailerSend include a `Signature` header. It contains a string generated by hashing the data sent to your webhook endpoint with an individual Signing Secret. A signing secret is a random string that is generated when you create a webhook. **Verifying a signature:** ```php // $signature - a header sent by MailerSend, please refer to your framework // or PHP manual on how to read the Signature header // $requestContent - please refer to your framework or PHP manual on how to read the request content $computedSignature = hash_hmac('sha256', $requestContent, $signingSecret); return hash_equals($signature, $computedSignature); ``` ```javascript import crypto from 'crypto' const requestContent = '{request payload from webhook}'; const receivedSignature = 'signature from webhook header'; const signingSecret = 'your-secret-key'; const computedSignature = crypto .createHmac('sha256', signingSecret) .update(requestContent, 'utf8') .digest('hex'); return crypto.timingSafeEqual( Buffer.from(receivedSignature, 'hex'), Buffer.from(computedSignature, 'hex') ); ``` ```python import hmac import hashlib # request_content - the raw request body received from the webhook # signature - the value of the "Signature" header sent by MailerSend # signing_secret - the signing secret generated when you created the webhook computed_signature = hmac.new( signing_secret.encode("utf-8"), request_content.encode("utf-8"), hashlib.sha256, ).hexdigest() # Constant-time comparison to prevent timing attacks return hmac.compare_digest(computed_signature, signature) ``` ```go package webhook import ( "bytes" "crypto/hmac" "crypto/sha256" "encoding/hex" "io" "net/http" ) func Handle(w http.ResponseWriter, r *http.Request) { // Read the entire request body bodyBytes, err := io.ReadAll(r.Body) if err != nil { http.Error(w, "Error reading request body", http.StatusBadRequest) return } defer r.Body.Close() // Restore the body so it can be read again by subsequent handlers r.Body = io.NopCloser(bytes.NewBuffer(bodyBytes)) // Create a new HMAC instance with your webhook secret secret := []byte("") hash := hmac.New(sha256.New, secret) // Write the body to the hash hash.Write(bodyBytes) // Calculate the expected signature expectedSignature := hex.EncodeToString(hash.Sum(nil)) // Get the actual signature from the request header actualSignature := r.Header.Get("Signature") // Compare signatures using a constant-time comparison to prevent timing attacks if !hmac.Equal([]byte(expectedSignature), []byte(actualSignature)) { http.Error(w, "Invalid signature", http.StatusForbidden) return } // Signature is valid, process the webhook // Your webhook handling logic here... w.WriteHeader(http.StatusOK) } ``` ```java import javax.crypto.Mac; import javax.crypto.spec.SecretKeySpec; import java.nio.charset.StandardCharsets; import java.security.MessageDigest; public boolean verifySignature(String requestContent, String signature, String signingSecret) throws Exception { // signature - the value of the "Signature" header sent by MailerSend // signingSecret - the signing secret generated when you created the webhook Mac mac = Mac.getInstance("HmacSHA256"); mac.init(new SecretKeySpec(signingSecret.getBytes(StandardCharsets.UTF_8), "HmacSHA256")); byte[] hash = mac.doFinal(requestContent.getBytes(StandardCharsets.UTF_8)); StringBuilder computedSignature = new StringBuilder(); for (byte b : hash) { computedSignature.append(String.format("%02x", b)); } // Constant-time comparison to prevent timing attacks return MessageDigest.isEqual( computedSignature.toString().getBytes(StandardCharsets.UTF_8), signature.getBytes(StandardCharsets.UTF_8) ); } ``` ```ruby require "openssl" # request_content - the raw request body received from the webhook # signature - the value of the "Signature" header sent by MailerSend # signing_secret - the signing secret generated when you created the webhook computed_signature = OpenSSL::HMAC.hexdigest("SHA256", signing_secret, request_content) # Constant-time comparison to prevent timing attacks OpenSSL.secure_compare(computed_signature, signature) ``` ### Retrying failed webhooks [#retrying-failed-webhooks] When your webhook receives a response other than a `2xx` code from your endpoint URL, or if the endpoint doesn’t respond within 3 seconds, it will show up as a failed attempt in the log section of your webhook. If it receives a `2xx`, then it will show as a success. If a webhook call fails, MailerSend automatically retries with exponential backoff for up to about 3 days. Some failures are considered unrecoverable and aren't retried. Examples include `4xx` client errors (other than `429`) and DNS resolution failures. In these cases only a single attempt is logged, so verify your endpoint URL is reachable before relying on retries. ### Recommendations [#recommendations] To ensure reliable handling of webhooks, we recommend that you: * Send a 2xx response as soon as possible to confirm receipt of the webhook. * Move any further processing logic to an asynchronous (async) background job. This allows your endpoint to respond quickly and avoids potential timeouts or repeated attempts. ### Useful tools [#useful-tools] * [Webhook.site](https://webhook.site/) or [Pipedream.com](https://pipedream.com/): These allow you to see the contents of a webhook and inspect what's being sent. * [Reqbin.com](https://reqbin.com): A versatile tool for testing webhooks and making HTTP requests in real time. ### FAQs [#faqs] * How do I track the Message I've sent via SMTP relay back to a webhook? If the message was sent successfully, our SMTP relay will send you back a `250 Message queued as XXXXXX` response. This can be parsed to an ID used in our [Messages](/api/v1/email/messages) endpoints, and in webhooks that Message ID can be found at `data.email.message.id`. *If you want full interoperability, we encourage you to use our Email API for the best results.* ## Get a list of webhooks [#get-a-list-of-webhooks] If you want to retrieve information about webhooks, use this `GET` request: ```http GET https://api.mailersend.com/v1/webhooks ``` #### Request parameters \[!toc] [#request-parameters-toc] | Query Parameter | Type | Required | Limitations | Details | | --------------- | -------- | -------- | --------------------- | ------------- | | `domain_id` | `string` | yes | | | | `limit` | `int` | no | Min: `10`, Max: `100` | Default: `25` | | `page` | `int` | no | Min: `1` | | ```php use MailerSend\MailerSend; $mailersend = new MailerSend(); $mailersend->webhooks->get('domain_id'); // With limit $mailersend->webhooks->get('domain_id', $limit = 25); ``` [More examples](https://github.com/mailersend/mailersend-php) ```javascript import 'dotenv/config'; import { MailerSend} from "mailersend"; const mailerSend = new MailerSend({ apiKey: process.env.API_KEY, }); mailerSend.email.webhook.list("domain_id") .then((response) => console.log(response.body)) .catch((error) => console.log(error.body)); ``` [More examples](https://github.com/mailersend/mailersend-nodejs) ```python from mailersend import MailerSendClient, WebhooksBuilder ms = MailerSendClient() request = (WebhooksBuilder() .domain_id("domain-id") .build_webhooks_list_request()) response = ms.webhooks.list_webhooks(request) for webhook in response.data: print(f"Webhook: {webhook.name} - {webhook.url}") ``` [More examples](https://github.com/mailersend/mailersend-python) ```go package main import ( "context" "log" "time" "github.com/mailersend/mailersend-go" ) var APIKey = "Api Key Here" func main() { // Create an instance of the mailersend client ms := mailersend.NewMailersend(APIKey) ctx := context.Background() ctx, cancel := context.WithTimeout(ctx, 5*time.Second) defer cancel() domainID := "domain-id" options := &mailersend.ListWebhookOptions{ DomainID: domainID, Limit: 25, } _, _, err := ms.Webhook.List(ctx, options) if err != nil { log.Fatal(err) } } ``` [More examples](https://github.com/mailersend/mailersend-go) ```java import com.mailersend.sdk.MailerSend; import com.mailersend.sdk.exceptions.MailerSendException; import com.mailersend.sdk.webhooks.Webhook; import com.mailersend.sdk.webhooks.WebhooksList; public void GetWebhooks() { MailerSend ms = new MailerSend(); ms.setToken("mailersend token"); try { WebhooksList list = ms.webhooks().getWebhooks("domain id"); for (Webhook webhook : list.webhooks) { System.out.println(webhook.name); } } catch (MailerSendException e) { e.printStackTrace(); } } ``` [More examples](https://github.com/mailersend/mailersend-java) ```ruby require "mailersend-ruby" ms_webhooks = Mailersend::Webhooks.new ms_webhooks.list(domain_id: "xxx2241ll") ``` [More examples](https://github.com/mailersend/mailersend-ruby) ## Get a webhook [#get-a-webhook] To retrieve information about a single webhook, use this `GET` request: ```http GET https://api.mailersend.com/v1/webhooks/{webhook_id} ``` #### Request parameters \[!toc] [#request-parameters-toc-1] | URL Parameter | Type | Required | Limitations | Details | | ------------- | -------- | -------- | ----------- | ------- | | `webhook_id` | `string` | yes | | | ```php use MailerSend\MailerSend; $mailersend = new MailerSend(); $mailersend->webhooks->find('webhook_id'); ``` [More examples](https://github.com/mailersend/mailersend-php) ```javascript import 'dotenv/config'; import { MailerSend} from "mailersend"; const mailerSend = new MailerSend({ apiKey: process.env.API_KEY, }); mailerSend.email.webhook.single("webhook_id") .then((response) => console.log(response.body)) .catch((error) => console.log(error.body)); ``` [More examples](https://github.com/mailersend/mailersend-nodejs) ```python from mailersend import MailerSendClient, WebhooksBuilder ms = MailerSendClient() request = (WebhooksBuilder() .webhook_id("webhook-id") .build_webhook_get_request()) response = ms.webhooks.get_webhook(request) print(f"Webhook: {response.name}") ``` [More examples](https://github.com/mailersend/mailersend-python) ```go package main import ( "context" "log" "time" "github.com/mailersend/mailersend-go" ) var APIKey = "Api Key Here" func main() { // Create an instance of the mailersend client ms := mailersend.NewMailersend(APIKey) ctx := context.Background() ctx, cancel := context.WithTimeout(ctx, 5*time.Second) defer cancel() webhookID := "webhook-id" _, _, err := ms.Webhook.Get(ctx, webhookID) if err != nil { log.Fatal(err) } } ``` [More examples](https://github.com/mailersend/mailersend-go) ```java import com.mailersend.sdk.MailerSend; import com.mailersend.sdk.exceptions.MailerSendException; import com.mailersend.sdk.webhooks.Webhook; public void GetSingleWebhook() { MailerSend ms = new MailerSend(); ms.setToken("mailersend token"); try { Webhook webhook = ms.webhooks().getWebhook("webhook id"); System.out.println(webhook.name); } catch (MailerSendException e) { e.printStackTrace(); } } ``` [More examples](https://github.com/mailersend/mailersend-java) ```ruby require "mailersend-ruby" ms_webhooks = Mailersend::Webhooks.new ms_webhooks.single(webhook_id: "zzz2241ll") ``` [More examples](https://github.com/mailersend/mailersend-ruby) ## Create a webhook [#create-a-webhook] Create a webhook using this `POST` request: ```http POST https://api.mailersend.com/v1/webhooks/ ``` #### Request parameters \[!toc] [#request-parameters-toc-2] *JSON parameters are provided in dot notation* | JSON Parameter | Type | Required | Limitations | Details | | -------------- | --------- | -------- | ----------- | -------------------------- | | `url` | `url` | yes | Max: `191` | | | `name` | `string` | yes | Max: `50` | | | `events` | `array` | yes | | | | `enabled` | `boolean` | optional | | | | `editable` | `boolean` | optional | | | | `version` | `integer` | optional | 1, 2 | 1 Legacy, 2 Recommended | | `domain_id` | `string` | yes | | Existing hashed domain ID. | ```php use MailerSend\Helpers\Builder\WebhookParams; use MailerSend\MailerSend; $mailersend = new MailerSend(); $mailersend->webhooks->create( new WebhookParams('https://webhook_url', 'Webhook name', WebhookParams::ALL_ACTIVITIES, 'domain_id') ); // Or a disabled webhook $mailersend->webhooks->create( new WebhookParams('https://webhook_url', 'Webhook name', WebhookParams::ALL_ACTIVITIES, 'domain_id', false) ); // Or with a specific webhook payload version (1 or 2) $mailersend->webhooks->create( new WebhookParams('https://webhook_url', 'Webhook name', WebhookParams::ALL_ACTIVITIES, 'domain_id', true, 2) ); // Or with editable flag $mailersend->webhooks->create( new WebhookParams('https://webhook_url', 'Webhook name', WebhookParams::ALL_ACTIVITIES, 'domain_id', true, 2, true) ); ``` [More examples](https://github.com/mailersend/mailersend-php) ```javascript import 'dotenv/config'; import { EmailWebhook, EmailWebhookEventType, MailerSend } from "mailersend"; const mailerSend = new MailerSend({ apiKey: process.env.API_KEY, }); const emailWebhook = new EmailWebhook() .setName("Webhook Name") .setUrl("https://example.com") .setDomainId("domain_id") .setEnabled(true) .setEvents([EmailWebhookEventType.SENT, EmailWebhookEventType.OPENED]); mailerSend.email.webhook.create(emailWebhook) .then((response) => console.log(response.body)) .catch((error) => console.log(error.body)); ``` [More examples](https://github.com/mailersend/mailersend-nodejs) ```python from mailersend import MailerSendClient, WebhooksBuilder ms = MailerSendClient() request = (WebhooksBuilder() .domain_id("domain-id") .url("https://webhook.example.com") .name("My Webhook") .events(["activity.sent", "activity.delivered", "activity.opened"]) .enabled(True) .build_webhook_create_request()) response = ms.webhooks.create_webhook(request) print(f"Created webhook with ID: {response.id}") ``` [More examples](https://github.com/mailersend/mailersend-python) ```go package main import ( "context" "log" "time" "github.com/mailersend/mailersend-go" ) var APIKey = "Api Key Here" func main() { // Create an instance of the mailersend client ms := mailersend.NewMailersend(APIKey) ctx := context.Background() ctx, cancel := context.WithTimeout(ctx, 5*time.Second) defer cancel() domainID := "domain-id" events := []string{"activity.sent", "activity.opened"} version := 2 createOptions := &mailersend.CreateWebhookOptions{ Name: "Webhook", DomainID: domainID, URL: "https://test.com", Enabled: mailersend.Bool(false), Events: events, Version: &version, } _, _, err := ms.Webhook.Create(ctx, createOptions) if err != nil { log.Fatal(err) } } ``` [More examples](https://github.com/mailersend/mailersend-go) ```java import com.mailersend.sdk.MailerSend; import com.mailersend.sdk.exceptions.MailerSendException; import com.mailersend.sdk.webhooks.Webhook; public void CreateWebhook() { MailerSend ms = new MailerSend(); ms.setToken("mailersend token"); try { Webhook webhook = ms.webhooks().builder() .name("Webhook name") .url("Webhook url") .addEvent(WebhookEvents.ACTIVITY_OPENED) .addEvent(WebhookEvents.ACTIVITY_CLICKED) .createWebhook("domain id"); System.out.println(webhook.name); } catch (MailerSendException e) { e.printStackTrace(); } } ``` [More examples](https://github.com/mailersend/mailersend-java) ```ruby require "mailersend-ruby" ms_webhooks = Mailersend::Webhooks.new ms_webhooks.create(domain_id: "xxx2241ll", url: "https://domain.com/hook", name: "Webhook", events: ["activity.sent", "activity.delivered"], enabled: true) ``` [More examples](https://github.com/mailersend/mailersend-ruby) ## Update a webhook [#update-a-webhook] Update a webhook using this `PUT` request: ```http PUT https://api.mailersend.com/v1/webhooks/{webhook_id} ``` #### Request parameters \[!toc] [#request-parameters-toc-3] | URL Parameter | Type | Required | Limitations | Details | | ------------- | -------- | -------- | ----------- | ------- | | `webhook_id` | `string` | yes | | | *JSON parameters are provided in dot notation* | JSON Parameter | Type | Required | Limitations | Details | | -------------- | --------- | -------- | ----------- | ----------------------- | | `url` | `url` | optional | | | | `name` | `string` | optional | Max: `50` | | | `events` | `array` | optional | | | | `enabled` | `boolean` | optional | | | | `version` | `integer` | optional | 1, 2 | 1 Legacy, 2 Recommended | ```php use MailerSend\MailerSend; use MailerSend\Helpers\Builder\WebhookParams; $mailersend = new MailerSend(); $mailersend->webhooks->update('webhook_id', 'https://webhook_url', 'Webhook name', WebhookParams::ALL_ACTIVITIES); // Update webhook to version 2 $mailersend->webhooks->update('webhook_id', 'https://webhook_url', 'Webhook name', WebhookParams::ALL_ACTIVITIES, true, 2); // Enable webhook $mailersend->webhooks->update('webhook_id', 'https://webhook_url', 'Webhook name', WebhookParams::ALL_ACTIVITIES, true); // Disable webhook $mailersend->webhooks->update('webhook_id', 'https://webhook_url', 'Webhook name', WebhookParams::ALL_ACTIVITIES, false); ``` [More examples](https://github.com/mailersend/mailersend-php) ```javascript import 'dotenv/config'; import { EmailWebhook, EmailWebhookEventType, MailerSend } from "mailersend"; const mailerSend = new MailerSend({ apiKey: process.env.API_KEY, }); const emailWebhook = new EmailWebhook() .setName("Webhook Name 2") .setEnabled(false) .setEvents([EmailWebhookEventType.SENT, EmailWebhookEventType.OPENED]); mailerSend.email.webhook.update("webhook_id", emailWebhook) .then((response) => console.log(response.body)) .catch((error) => console.log(error.body)); ``` [More examples](https://github.com/mailersend/mailersend-nodejs) ```python from mailersend import MailerSendClient, WebhooksBuilder ms = MailerSendClient() request = (WebhooksBuilder() .webhook_id("webhook-id") .name("Updated Webhook Name") .url("https://new-webhook.example.com") .enabled(True) .activity_events() .build_webhook_update_request()) response = ms.webhooks.update_webhook(request) ``` [More examples](https://github.com/mailersend/mailersend-python) ```go package main import ( "context" "log" "time" "github.com/mailersend/mailersend-go" ) var APIKey = "Api Key Here" func main() { // Create an instance of the mailersend client ms := mailersend.NewMailersend(APIKey) ctx := context.Background() ctx, cancel := context.WithTimeout(ctx, 5*time.Second) defer cancel() webhookID := "webhook-id" events := []string{"activity.clicked"} version := 2 updateOptions := &mailersend.UpdateWebhookOptions{ WebhookID: webhookID, Name: "Updated Webhook", URL: "https://updated-webhook.com", Enabled: mailersend.Bool(true), Events: events, Version: &version, } _, _, err := ms.Webhook.Update(ctx, updateOptions) if err != nil { log.Fatal(err) } } ``` [More examples](https://github.com/mailersend/mailersend-go) ```java import com.mailersend.sdk.MailerSend; import com.mailersend.sdk.exceptions.MailerSendException; import com.mailersend.sdk.webhooks.Webhook; public void UpdateWebhook() { MailerSend ms = new MailerSend(); ms.setToken("mailersend token"); try { Webhook webhook = ms.webhooks() .builder() .name("Updated webhook name") .updateWebhook("webhook id"); System.out.println(webhook.name); } catch (MailerSendException e) { e.printStackTrace(); } } ``` [More examples](https://github.com/mailersend/mailersend-java) ```ruby require "mailersend-ruby" ms_webhooks = Mailersend::Webhooks.new ms_webhooks.update(webhook_id: "zzz2241ll", enabled: false) ``` [More examples](https://github.com/mailersend/mailersend-ruby) ## Delete a webhook [#delete-a-webhook] Delete a webhook using this `DELETE` request: ```http DELETE https://api.mailersend.com/v1/webhooks/{webhook_id} ``` #### Request parameters \[!toc] [#request-parameters-toc-4] | URL Parameter | Type | Required | Limitations | Details | | ------------- | -------- | -------- | ----------- | ------- | | `webhook_id` | `string` | yes | | | ```php use MailerSend\MailerSend; $mailersend = new MailerSend(); $mailersend->webhooks->delete('webhook_id'); ``` [More examples](https://github.com/mailersend/mailersend-php) ```javascript import 'dotenv/config'; import { MailerSend} from "mailersend"; const mailerSend = new MailerSend({ apiKey: process.env.API_KEY, }); mailerSend.email.webhook.delete("webhook_id") .then((response) => console.log(response.body)) .catch((error) => console.log(error.body)); ``` [More examples](https://github.com/mailersend/mailersend-nodejs) ```python from mailersend import MailerSendClient, WebhooksBuilder ms = MailerSendClient() request = (WebhooksBuilder() .webhook_id("webhook-id") .build_webhook_delete_request()) response = ms.webhooks.delete_webhook(request) print("Webhook deleted") ``` [More examples](https://github.com/mailersend/mailersend-python) ```go package main import ( "context" "log" "time" "github.com/mailersend/mailersend-go" ) var APIKey = "Api Key Here" func main() { // Create an instance of the mailersend client ms := mailersend.NewMailersend(APIKey) ctx := context.Background() ctx, cancel := context.WithTimeout(ctx, 5*time.Second) defer cancel() webhookID := "webhook-id" _, err := ms.Webhook.Delete(ctx, webhookID) if err != nil { log.Fatal(err) } } ``` [More examples](https://github.com/mailersend/mailersend-go) ```java import com.mailersend.sdk.MailerSend; import com.mailersend.sdk.MailerSendResponse; import com.mailersend.sdk.exceptions.MailerSendException; public void DeleteWebhook() { MailerSend ms = new MailerSend(); ms.setToken("mailersend token"); try { MailerSendResponse response = ms.webhooks().deleteWebhook("webhook id"); System.out.println(response.responseStatusCode); } catch (MailerSendException e) { e.printStackTrace(); } } ``` [More examples](https://github.com/mailersend/mailersend-java) ```ruby require "mailersend-ruby" ms_webhooks = Mailersend::Webhooks.new ms_webhooks.delete(webhook_id: "zzz2241ll") ``` [More examples](https://github.com/mailersend/mailersend-ruby) # Activity (/api/v1/sms/activity) Get information about your SMS activity, including your sent SMS messages, and whether they were received by the recipient. ## Get a list of activities [#get-a-list-of-activities] With this endpoint, you can retrieve every single data point of the activity that happened for a specific phone number. Get a list of activities with the following `GET` request: ```http GET https://api.mailersend.com/v1/sms-activity ``` #### Request parameters \[!toc] [#request-parameters-toc] | Query parameter | Type | Required | Limitations | Details | | | --------------- | ---------- | -------- | ----------------------------------------------------------------- | ------------------------------------------------------------------------------ | - | | `sms_number_id` | `string` | no | | | | | `date_from` | `int` | no | Timestamp is assumed to be `UTC`. Must be lower than `date_to` | Format: `1443651141` | | | `date_to` | `int` | no | Timestamp is assumed to be `UTC`. Must be higher than `date_from` | Format: `1443651141` | | | `status[]` | `string[]` | no | Possible types: `processed`,`queued`,`sent`,`delivered`, `failed` | | | | `page` | `int` | no | Min: `1`, Max: `1000` | To reach older activity beyond the last page, narrow `date_from` and `date_to` | | | `limit` | `int` | no | Min: `10`, Max: `100` | Default: `25` | | ```php use MailerSend\MailerSend; use MailerSend\Helpers\Builder\SmsActivityParams; $mailersend = new MailerSend(['api_key' => 'key']); $smsActivityParams = (new SmsActivityParams()) ->setSmsNumberId('sms_number_id') ->setDateFrom(1623073576) ->setDateTo(1623074976) ->setStatus(['queued', 'delivered']) ->setPage(3) ->setLimit(15); $smsActivity = $mailersend->smsActivity->getAll($smsActivityParams); ``` [More examples](https://github.com/mailersend/mailersend-php) ```javascript import 'dotenv/config'; import { MailerSend, SmsActivityStatusType } from "mailersend"; const mailerSend = new MailerSend({ apiKey: process.env.API_KEY, }); mailerSend.sms.activity.list({ sms_number_id: "number_id", status: [SmsActivityStatusType.SENT, SmsActivityStatusType.DELIVERED], limit: 10, page: 1 }) .then((response) => console.log(response.body)) .catch((error) => console.log(error.body)); ``` [More examples](https://github.com/mailersend/mailersend-nodejs) ```python from mailersend import MailerSendClient, SmsActivityBuilder from datetime import datetime, timedelta ms = MailerSendClient() # Get activities from last 7 days date_from = int((datetime.now() - timedelta(days=7)).timestamp()) date_to = int(datetime.now().timestamp()) request = (SmsActivityBuilder() .sms_number_id("sms-number-id") .date_from(date_from) .date_to(date_to) .status(["sent", "delivered", "failed"]) .page(1) .limit(25) .build_list_request()) response = ms.sms_activity.list(request) ``` [More examples](https://github.com/mailersend/mailersend-python) ```go package main import ( "context" "log" "time" "github.com/mailersend/mailersend-go" ) var APIKey = "Api Key Here" func main() { // Create an instance of the mailersend client ms := mailersend.NewMailersend(APIKey) ctx := context.Background() ctx, cancel := context.WithTimeout(ctx, 5*time.Second) defer cancel() options := &mailersend.SmsActivityOptions{} _, _, err := ms.SmsActivityService.List(context.TODO(), options) if err != nil { log.Fatal(err) } } ``` [More examples](https://github.com/mailersend/mailersend-go) ```java import com.mailersend.sdk.MailerSend; import com.mailersend.sdk.exceptions.MailerSendException; import com.mailsend.sdk.sms.activities.SmsActivityList; import com.mailsend.sdk.sms.activities.SmsActivity; public void getActivities() { MailerSend ms = new MailerSend(); ms.setToken("mailersend token"); try { SmsActivityList list = ms.sms().activities().getActivities(); for (SmsActivity activity : lists.smsActivities) { System.out.println(activity.id); System.out.println(activity.content); } } catch (MailerSendException e) { e.printStackTrace(); } } ``` [More examples](https://github.com/mailersend/mailersend-java) ```ruby require "mailersend-ruby" # Intialize the SMS Recipient class ms_sms_activity = Mailersend::SMSActivity.new # Add parameters ms_sms_activity.list(page: 1, limit: 10) ``` [More examples](https://github.com/mailersend/mailersend-ruby) ### Responses [#responses] #### Valid [#valid] ```http Response Code: 200 OK Response Headers: content-type: application/json ``` ```json { "data": [ { "from": "+18332647501", "to": "+16203221059", "created_at": "2022-02-21T08:15:46.627000Z", "content": "Lorem Ipsum is simply dummy text", "status": "delivered", "sms_message_id": "62134a2d7de3253bf10d6642" }, { "from": "+18332647501", "to": "+16203221059", "created_at": "2022-02-21T08:15:42.508000Z", "content": "Lorem Ipsum is simply dummy text", "status": "processed", "sms_message_id": "62134a2d7de3253bf10d6642" }, { "from": "+18332647501", "to": "+16203221059", "created_at": "2022-02-21T08:15:42.579000Z", "content": "Lorem Ipsum is simply dummy text", "status": "queued", "sms_message_id": "62134a2d7de3253bf10d6642" }, { "from": "+18332647501", "to": "+16203221059", "created_at": "2022-02-21T08:15:43.624000Z", "content": "Lorem Ipsum is simply dummy text", "status": "sent", "sms_message_id": "62134a2d7de3253bf10d6642" } ], "links": { "first": "https:\/\/api.mailersend.com\/v1\/sms-activity?page=1", "last": null, "prev": null, "next": "https:\/\/api.mailersend.com\/v1\/sms-activity?page=2" }, "meta": { "current_page": 1, "from": 1, "path": "https:\/\/api.mailersend.com\/v1\/sms-activity", "per_page": 25, "to": 1 } } ``` #### Error [#error] ```http Response Code: 422 Unprocessable Entity ``` *See - [Validations errors](/../../general#validation-errors)* ## Get activity of a single message [#get-activity-of-a-single-message] With this endpoint, you can get every single activity data point that happened to a specific SMS message. Get a list of activities for the SMS message specified with this `GET` request: ```http GET https://api.mailersend.com/v1/sms-messages/{sms_message_id} ``` #### Request parameters \[!toc] [#request-parameters-toc-1] | URL parameter | Type | Required | Limitations | Details | | ---------------- | ------ | -------- | ----------- | ------- | | `sms_message_id` | string | yes | | | ```javascript import 'dotenv/config'; import { MailerSend } from "mailersend"; const mailerSend = new MailerSend({ apiKey: process.env.API_KEY, }); mailerSend.sms.activity.single("sms_message_id") .then((response) => console.log(response.body)) .catch((error) => console.log(error.body)); ``` [More examples](https://github.com/mailersend/mailersend-nodejs) ```python from mailersend import MailerSendClient, SmsActivityBuilder ms = MailerSendClient() request = (SmsActivityBuilder() .sms_message_id("sms-message-id") .build_get_request()) response = ms.sms_activity.get(request) ``` [More examples](https://github.com/mailersend/mailersend-python) ```go package main import ( "context" "log" "time" "github.com/mailersend/mailersend-go" ) var APIKey = "Api Key Here" func main() { // Create an instance of the mailersend client ms := mailersend.NewMailersend(APIKey) ctx := context.Background() ctx, cancel := context.WithTimeout(ctx, 5*time.Second) defer cancel() _, _, err := ms.SmsActivityService.Get(context.TODO(), "message-id") if err != nil { log.Fatal(err) } } ``` [More examples](https://github.com/mailersend/mailersend-go) ```java import com.mailersend.sdk.MailerSend; import com.mailersend.sdk.exceptions.MailerSendException; import com.mailsend.sdk.sms.activities.SmsActivity; public void getActivity() { MailerSend ms = new MailerSend(); ms.setToken("mailersend token"); try { SmsActivity activity = ms.sms().activities().getMessageActivity("message id"); System.out.println(activity.id); System.out.println(activity.content); } catch (MailerSendException e) { e.printStackTrace(); } } ``` [More examples](https://github.com/mailersend/mailersend-java) ### Responses [#responses-1] #### Valid [#valid-1] ```http Response Code: 200 OK Response Headers: content-type: application/json ``` ```json { "data": { "id": "62134a2d7de3253bf10d6642", "from": "+18332647501", "to": [ "+16203221059", "+18044064234" ], "text": "Lorem Ipsum is simply dummy text", "paused": false, "created_at": "2022-02-21T08:15:41.339000Z", "sms": [ { "id": "62134a2e4709ec689f72ea62", "from": "+18332647501", "to": "+16203221059", "text": "Lorem Ipsum is simply dummy text", "status": "delivered", "segment_count": 1, "error_type": null, "error_description": null } ], "sms_activity": [ { "from": "+18332647501", "to": "+16203221059", "created_at": "2022-02-21T08:15:46.627000Z", "status": "delivered", "sms_message_id": "62134a2d7de3253bf10d6642" }, { "from": "+18332647501", "to": "+16203221059", "created_at": "2022-02-21T08:15:42.508000Z", "status": "processed", "sms_message_id": "62134a2d7de3253bf10d6642" }, { "from": "+18332647501", "to": "+16203221059", "created_at": "2022-02-21T08:15:42.579000Z", "status": "queued", "sms_message_id": "62134a2d7de3253bf10d6642" }, { "from": "+18332647501", "to": "+16203221059", "created_at": "2022-02-21T08:15:43.624000Z", "status": "sent", "sms_message_id": "62134a2d7de3253bf10d6642" } ] } } ``` #### Error [#error-1] ```http Response Code: 422 Unprocessable Entity ``` *See - [Validations errors](/../../general#validation-errors)* # Inbound routing (/api/v1/sms/inbounds) ## Get a list of SMS inbound routes [#get-a-list-of-sms-inbound-routes] If you want to retrieve information about multiple SMS inbound routes, use this `GET` request: ```http GET https://api.mailersend.com/v1/sms-inbounds ``` #### Request parameters \[!toc] [#request-parameters-toc] | Query parameter | Type | Required | Limitations | Details | | --------------- | --------- | -------- | --------------------- | ------------- | | `sms_number_id` | `string` | no | | | | `enabled` | `boolean` | no | | | | `page` | `int` | no | | | | `limit` | `int` | no | Min: `10`, Max: `100` | Default: `25` | ```php use MailerSend\MailerSend; $mailersend = new MailerSend(['api_key' => 'key']); $smsRecipients = $mailersend->smsInbound->getAll($smsNumberId = 'sms_number_id', $enabled = true, $page = 3, $limit = 15); ``` [More examples](https://github.com/mailersend/mailersend-php) ```javascript import 'dotenv/config'; import { MailerSend } from "mailersend"; const mailerSend = new MailerSend({ apiKey: process.env.API_KEY, }); mailerSend.sms.inbound.list({ enabled: 1, sms_number_id: "sms_number_id", limit: 10, page: 1, }) .then((response) => console.log(response.body)) .catch((error) => console.log(error.body)); ``` [More examples](https://github.com/mailersend/mailersend-nodejs) ```python from mailersend import MailerSendClient, SmsInboundsBuilder ms = MailerSendClient() request = (SmsInboundsBuilder() .sms_number_id("sms-number-id") .enabled(True) .build_list_request()) response = ms.sms_inbounds.list_sms_inbounds(request) ``` [More examples](https://github.com/mailersend/mailersend-python) ```go package main import ( "context" "log" "time" "github.com/mailersend/mailersend-go" ) var APIKey = "Api Key Here" func main() { // Create an instance of the mailersend client ms := mailersend.NewMailersend(APIKey) ctx := context.Background() ctx, cancel := context.WithTimeout(ctx, 5*time.Second) defer cancel() listOptions := &mailersend.ListSmsInboundOptions{ SmsNumberId: "sms-number-id", } _, _, err := ms.SmsInbound.List(ctx, listOptions) if err != nil { log.Fatal(err) } } ``` [More examples](https://github.com/mailersend/mailersend-go) ```java import com.mailersend.sdk.MailerSend; import com.mailersend.sdk.exceptions.MailerSendException; import com.mailersend.sdk.sms.inboundroutes.SmsInboundRoute; import com.mailersend.sdk.sms.inboundroutes.SmsInboundRouteList; public void getSmsInboundRoutes() { MailerSend ms = new MailerSend(); ms.setToken("mailersend token"); try { SmsInboundRouteList routes = ms.sms().inboundRoutes().getSmsInboundRoutes(); for (SmsInboundRoute route : routes.routes) { System.out.println(route.id); } } catch (MailerSendException e) { e.printStackTrace(); } } ``` [More examples](https://github.com/mailersend/mailersend-java) ```ruby require "mailersend-ruby" # Intialize the SMS Inbounds class ms_sms_inbounds = Mailersend::SMSInbounds.new ms_sms_inbounds.list ``` [More examples](https://github.com/mailersend/mailersend-ruby) ### Responses [#responses] #### Valid [#valid] ```http Response Code: 200 OK Response Headers: content-type: application/json ``` ```json { "data": [ { "id": "7z3m5jgrogdpyo6n", "name": "Inbound", "filter": { "value": "START", "comparer": "equal" }, "forward_url": "https://yourapp.com/hook", "enabled": true, "secret": "jYhafGtTiZgw0qWxlkUA7cbqTG3Zfh2j", "created_at": "2022-01-01T12:00:00.000000Z" } ] } ``` #### Error [#error] ```http Response Code: 404 Not Found ``` ## Get a single SMS inbound route [#get-a-single-sms-inbound-route] If you want to retrieve a single SMS inbound route, use this `GET` request: ```http GET https://api.mailersend.com/v1/sms-inbounds/{sms_inbound_id} ``` #### Request parameters \[!toc] [#request-parameters-toc-1] | URL parameter | Type | Required | Limitations | Details | | ---------------- | -------- | -------- | ----------- | ------- | | `sms_inbound_id` | `string` | yes | | | ```php use MailerSend\MailerSend; $mailersend = new MailerSend(['api_key' => 'key']); $smsRecipients = $mailersend->smsInbound->find('sms_inbound_id'); ``` [More examples](https://github.com/mailersend/mailersend-php) ```javascript import 'dotenv/config'; import { MailerSend } from "mailersend"; const mailerSend = new MailerSend({ apiKey: process.env.API_KEY, }); mailerSend.sms.inbound.single("sms_inbound_id") .then((response) => console.log(response.body)) .catch((error) => console.log(error.body)); ``` [More examples](https://github.com/mailersend/mailersend-nodejs) ```python from mailersend import MailerSendClient, SmsInboundsBuilder ms = MailerSendClient() request = (SmsInboundsBuilder() .sms_inbound_id("inbound-id") .build_get_request()) response = ms.sms_inbounds.get_sms_inbound(request) ``` [More examples](https://github.com/mailersend/mailersend-python) ```go package main import ( "context" "log" "time" "github.com/mailersend/mailersend-go" ) var APIKey = "Api Key Here" func main() { // Create an instance of the mailersend client ms := mailersend.NewMailersend(APIKey) ctx := context.Background() ctx, cancel := context.WithTimeout(ctx, 5*time.Second) defer cancel() _, _, err := ms.SmsInbound.Get(ctx, "sms-inbound-id") if err != nil { log.Fatal(err) } } ``` [More examples](https://github.com/mailersend/mailersend-go) ```java import com.mailersend.sdk.MailerSend; import com.mailersend.sdk.exceptions.MailerSendException; import com.mailersend.sdk.sms.inboundroutes.SmsInboundRoute; public void getSmsInboundRoute() { MailerSend ms = new MailerSend(); ms.setToken("mailersend token"); try { SmsInboundRoute route = ms.sms().inboundRoutes().getSmsInboundRoute("route id"); System.out.println(route.id); } catch (MailerSendException e) { e.printStackTrace(); } } ``` [More examples](https://github.com/mailersend/mailersend-java) ```ruby require "mailersend-ruby" # Intialize the SMS Inbounds class ms_sms_inbounds = Mailersend::SMSInbounds.new # Add parameters ms_sms_inbounds.get_sms_inbound_route(sms_inbound_id: 'your-sms-inbound-id') ``` [More examples](https://github.com/mailersend/mailersend-ruby) ### Responses [#responses-1] #### Valid [#valid-1] ```http Response Code: 200 OK Response Headers: content-type: application/json ``` ```json { "data": { "id": "7z3m5jgrogdpyo6n", "name": "Inbound", "filter": { "value": "START", "comparer": "equal" }, "forward_url": "https://yourapp.com/hook", "enabled": true, "secret": "jYhafGtTiZgw0qWxlkUA7cbqTG3Zfh2j", "created_at": "2022-01-13T12:00:00.000000Z", "sms_number": { "id": "7z3m5jgrogdpyo6n", "telephone_number": "+19199876543", "paused": false, "created_at": "2022-01-13T12:00:00.000000Z" } } } ``` #### Error [#error-1] ```http Response Code: 404 Not Found ``` ## Add an SMS inbound route [#add-an-sms-inbound-route] If you want to add a new SMS inbound route to a domain, use this `POST` request: ```http POST https://api.mailersend.com/v1/sms-inbounds ``` ### Request body \[!toc] [#request-body-toc] ```json { "sms_number_id": "7z3m5jgrogdpyo6n", "name": "Inbound", "forward_url": "https://yourapp.com/hook", "filter": { "comparer": "equal", "value": "START" }, "enabled": true } ``` ```php use MailerSend\MailerSend; use MailerSend\Helpers\Builder\SmsInbound; use MailerSend\Helpers\Builder\SmsInboundFilter; $mailersend = new MailerSend(['api_key' => 'key']); $smsInboundParams = (new SmsInbound()) ->setSmsNumberId('sms_number_id') ->setName('Name') ->setForwardUrl('https://mailersend.com/inbound_webhook') ->setFilter(new SmsInboundFilter($comparer = 'starts-with', $value = 'Stop')) ->setEnabled(true); $smsRecipients = $mailersend->smsInbound->create($smsInboundParams); ``` [More examples](https://github.com/mailersend/mailersend-php) ```javascript import 'dotenv/config'; import { MailerSend, SmsInbound } from "mailersend"; const mailerSend = new MailerSend({ apiKey: process.env.API_KEY, }); const smsInbound = new SmsInbound() .setSmsNumberId("sms_number_id") .setEnabled(true) .setName("Inbound Name") .setForwardUrl("yourapp.com/hook") .setFilter({ comparer: "equal", value: "START" }); mailerSend.sms.inbound.create(smsInbound) .then((response) => console.log(response.body)) .catch((error) => console.log(error.body)); ``` [More examples](https://github.com/mailersend/mailersend-nodejs) ```python from mailersend import MailerSendClient, SmsInboundsBuilder from mailersend.models.sms_inbounds import FilterComparer ms = MailerSendClient() request = (SmsInboundsBuilder() .sms_number_id("sms-number-id") .name("Support Route") .forward_url("https://api.example.com/sms/support") .filter(FilterComparer.STARTS_WITH, "SUPPORT") .enabled(True) .build_create_request()) response = ms.sms_inbounds.create_sms_inbound(request) ``` [More examples](https://github.com/mailersend/mailersend-python) ```go require "mailersend-ruby" # Intialize the SMS Inbounds class ms_sms_inbounds = Mailersend::SMSInbounds.new # Add parameters ms_sms_inbounds.settings = { 'forward_url' => 'https://your-forward-url', 'name' => 'name', 'events' => ['sms.sent', 'sms.delivered'], 'sms_number_id' => 'your-sms-number-id' } puts ms_sms_inbounds.add_sms_inbound_route ``` [More examples](https://github.com/mailersend/mailersend-go) ```java import com.mailersend.sdk.MailerSend; import com.mailersend.sdk.exceptions.MailerSendException; import com.mailersend.sdk.sms.inboundroutes.SmsInboundRoute; public void addSmsInboundRoute() { MailerSend ms = new MailerSend(); ms.setToken("mailersend token"); try { SmsInboundRoute route = ms.sms().inboundRoutes().builder() .smsNumberId("sms number id") .name("Test inbound route") .enabled(false) .forwardUrl("https://example.com") .filter("equal", "START") .addSmsInboundRoute(); System.out.println(route.id); } catch (MailerSendException e) { e.printStackTrace(); } } ``` [More examples](https://github.com/mailersend/mailersend-java) ```ruby require "mailersend-ruby" # Intialize the SMS Inbounds class ms_sms_inbounds = Mailersend::SMSInbounds.new # Add parameters ms_sms_inbounds.settings = { 'forward_url' => 'https://your-forward-url', 'name' => 'name', 'events' => ['sms.sent', 'sms.delivered'], 'sms_number_id' => 'your-sms-number-id' } puts ms_sms_inbounds.add_sms_inbound_route ``` [More examples](https://github.com/mailersend/mailersend-ruby) ### Request Parameters \[!toc] [#request-parameters-toc-2] *JSON parameters are provided in dot notation* | JSON Parameter | Type | Required | Limitations | Details | | ----------------- | --------- | -------- | ----------------------------------------------------------------------------------------------------------------------------------------------- | ------- | | `sms_number_id` | `string` | Yes | | | | `name` | `string` | Yes | `Max` 191 characters. | | | `forward_url` | `string` | Yes | | | | `filter` | `object` | No | | | | `filter.comparer` | `string` | Yes\* | Must be one of the comparers: `equal`, `not-equal`, `contains`, `not-contains`, `starts-with`, `ends-with`, `not-starts-with`, `not-ends-with`. | | | `filter.value` | `string` | Yes\* | Min: `1`, `Max` 255 characters. | | | `enabled` | `boolean` | No | | | ###### \* Required when `filter` object is provided. [#-required-when-filter-object-is-provided] ### Responses [#responses-2] | Response Key | Type | Details | | ------------ | ------ | --------------------------- | | data | object | SMS Inbound object created. | #### Valid [#valid-2] ```http Response Code: 201 CREATED Response Headers: content-type: application/json ``` ```json { "data": { "id": "7z3m5jgrogdpyo6n", "name": "Inbound", "filter": { "value": "START", "comparer": "equal" }, "forward_url": "https://yourapp.com/hook", "enabled": true, "secret": "jYhafGtTiZgw0qWxlkUA7cbqTG3Zfh2j", "created_at": "2022-01-01T12:00:00.000000Z" } } ``` #### Invalid [#invalid] ```http Response Code: 422 Unprocessable Entity ``` *See - [Validation errors](/../../general#validation-errors)* ## Update an inbound route [#update-an-inbound-route] If you want to update the information of an existing inbound route, use this `PUT` request: ```http PUT https://api.mailersend.com/v1/sms-inbounds/{sms_inbound_id} ``` ### Request body \[!toc] [#request-body-toc-1] ```json { "sms_number_id": "7z3m5jgrogdpyo6n", "name": "Inbound", "forward_url": "https://yourapp.com/hook", "filter": { "comparer": "equal", "value": "START" }, "enabled": true } ``` ```php use MailerSend\MailerSend; use MailerSend\Helpers\Builder\SmsInbound; use MailerSend\Helpers\Builder\SmsInboundFilter; $mailersend = new MailerSend(['api_key' => 'key']); $smsInboundParams = (new SmsInbound()) ->setSmsNumberId('sms_number_id') ->setName('Name') ->setForwardUrl('https://mailersend.com/inbound_webhook') ->setFilter(new SmsInboundFilter($comparer = 'starts-with', $value = 'Stop')) ->setEnabled(true); $smsRecipients = $mailersend->smsInbound->update('sms_inbound_id', $smsInboundParams); ``` [More examples](https://github.com/mailersend/mailersend-php) ```javascript import 'dotenv/config'; import { MailerSend, SmsInbound } from "mailersend"; const mailerSend = new MailerSend({ apiKey: process.env.API_KEY, }); const smsInbound = new SmsInbound() .setSmsNumberId("sms_number_id") .setEnabled(true) .setName("Inbound Name Update") .setForwardUrl("yourapp.com/hook") .setFilter({ comparer: "equal", value: "START" }); mailerSend.sms.inbound.update("sms_inbound_id", {...smsInbound}) .then((response) => console.log(response.body)) .catch((error) => console.log(error.body)); ``` [More examples](https://github.com/mailersend/mailersend-nodejs) ```python from mailersend import MailerSendClient, SmsInboundsBuilder from mailersend.models.sms_inbounds import FilterComparer ms = MailerSendClient() request = (SmsInboundsBuilder() .sms_number_id("inbound-id") .name("Updated Support Route") .forward_url("https://api.example.com/sms/new-support") .filter(FilterComparer.CONTAINS, "HELP") .enabled(False) .build_update_request()) response = ms.sms_inbounds.update_sms_inbound(request) ``` [More examples](https://github.com/mailersend/mailersend-python) ```go require "mailersend-ruby" # Intialize the SMS Inbounds class ms_sms_inbounds = Mailersend::SMSInbounds.new # Add parameters ms_sms_inbounds.settings = { 'forward_url' => 'https://your-forward-url', 'name' => 'name', 'events' => ['sms.sent', 'sms.delivered'], 'sms_number_id' => 'your-sms-number-id' } puts ms_sms_inbounds.update_sms_inbound_route(sms_inbound_id: 'your-sms-inbound-id') ``` [More examples](https://github.com/mailersend/mailersend-go) ```java import com.mailersend.sdk.MailerSend; import com.mailersend.sdk.exceptions.MailerSendException; import com.mailersend.sdk.sms.inboundroutes.SmsInboundRoute; public void updateSmsInboundRoute() { MailerSend ms = new MailerSend(); ms.setToken("mailersend token"); try { SmsInboundRoute route = ms.sms().inboundRoutes().builder() .smsNumberId("sms number id") .name("Test inbound route updated") .enabled(false) .forwardUrl("https://example.com") .filter("equal", "START") .updateSmsInboundRoute("route id"); System.out.println(route.name); } catch (MailerSendException e) { e.printStackTrace(); } } ``` [More examples](https://github.com/mailersend/mailersend-java) ```ruby require "mailersend-ruby" # Intialize the SMS Inbounds class ms_sms_inbounds = Mailersend::SMSInbounds.new # Add parameters ms_sms_inbounds.settings = { 'forward_url' => 'https://your-forward-url', 'name' => 'name', 'events' => ['sms.sent', 'sms.delivered'], 'sms_number_id' => 'your-sms-number-id' } puts ms_sms_inbounds.update_sms_inbound_route(sms_inbound_id: 'your-sms-inbound-id') ``` [More examples](https://github.com/mailersend/mailersend-ruby) ### Request Parameters \[!toc] [#request-parameters-toc-3] | URL parameter | Type | Required | Limitations | Details | | ---------------- | -------- | -------- | ----------- | ------- | | `sms_inbound_id` | `string` | yes | | | *JSON parameters are provided in dot notation* | JSON Parameter | Type | Required | Limitations | Details | | ----------------- | --------- | -------- | ----------------------------------------------------------------------------------------------------------------------------------------------- | ------- | | `sms_number_id` | `string` | No | | | | `name` | `string` | No | `Max` 191 characters. | | | `forward_url` | `string` | No | | | | `filter` | `object` | No | | | | `filter.comparer` | `string` | Yes\* | Must be one of the comparers: `equal`, `not-equal`, `contains`, `not-contains`, `starts-with`, `ends-with`, `not-starts-with`, `not-ends-with`. | | | `filter.value` | `string` | Yes\* | Min: `1`, `Max` 255 characters. | | | `enabled` | `boolean` | No | | | ###### \* Required when `filter` object is provided. [#-required-when-filter-object-is-provided-1] ### Responses [#responses-3] | Response Key | Type | Details | | ------------ | ------ | --------------------------- | | data | object | SMS Inbound object created. | #### Valid [#valid-3] ```http Response Code: 200 OK Response Headers: content-type: application/json ``` ```json { "data": { "id": "7z3m5jgrogdpyo6n", "name": "Inbound", "filter": { "value": "START", "comparer": "equal" }, "forward_url": "https://yourapp.com/hook", "enabled": true, "secret": "jYhafGtTiZgw0qWxlkUA7cbqTG3Zfh2j", "created_at": "2022-01-01T12:00:00.000000Z" } } ``` #### Invalid [#invalid-1] ```http Response Code: 422 Unprocessable Entity ``` *See - [Validation errors](/../../general#validation-errors)* ## Delete an SMS inbound route [#delete-an-sms-inbound-route] If you want to delete an SMS inbound route, use this `DELETE` request: ```http DELETE https://api.mailersend.com/v1/sms-inbounds/{sms_inbound_id} ``` ### Request parameters \[!toc] [#request-parameters-toc-4] | URL parameter | Type | Required | Limitations | Details | | ---------------- | -------- | -------- | ----------- | ------- | | `sms_inbound_id` | `string` | yes | | | ```php use MailerSend\MailerSend; $mailersend = new MailerSend(['api_key' => 'key']); $smsRecipients = $mailersend->smsInbound->delete('sms_inbound_id'); ``` [More examples](https://github.com/mailersend/mailersend-php) ```javascript import 'dotenv/config'; import { MailerSend } from "mailersend"; const mailerSend = new MailerSend({ apiKey: process.env.API_KEY, }); mailerSend.sms.inbound.delete("sms_inbound_id") .then((response) => console.log(response.body)) .catch((error) => console.log(error.body)); ``` [More examples](https://github.com/mailersend/mailersend-nodejs) ```python from mailersend import MailerSendClient, SmsInboundsBuilder ms = MailerSendClient() request = (SmsInboundsBuilder() .sms_inbound_id("inbound-id") .build_delete_request()) response = ms.sms_inbounds.delete_sms_inbound(request) ``` [More examples](https://github.com/mailersend/mailersend-python) ```go package main import ( "context" "log" "time" "github.com/mailersend/mailersend-go" ) var APIKey = "Api Key Here" func main() { // Create an instance of the mailersend client ms := mailersend.NewMailersend(APIKey) ctx := context.Background() ctx, cancel := context.WithTimeout(ctx, 5*time.Second) defer cancel() _, err := ms.SmsInbound.Delete(ctx, "sms-inbound-id") if err != nil { log.Fatal(err) } } ``` [More examples](https://github.com/mailersend/mailersend-go) ```java import com.mailersend.sdk.MailerSend; import com.mailersend.sdk.exceptions.MailerSendException; import com.mailersend.sdk.sms.inboundroutes.SmsInboundRoute; public void deleteSmsInboundRoute() { MailerSend ms = new MailerSend(); ms.setToken("mailersend token"); try { boolean result = ms.sms().inboundRoutes().deleteSmsInboundRoute("route id"); System.out.println(result); } catch (MailerSendException e) { e.printStackTrace(); } } ``` [More examples](https://github.com/mailersend/mailersend-java) ```ruby require "mailersend-ruby" # Intialize the SMS Inbounds class ms_sms_inbounds = Mailersend::SMSInbounds.new # Add parameters ms_sms_inbounds.delete_sms_inbound_route(sms_inbound_id: 'your-sms-inbound-id') ``` [More examples](https://github.com/mailersend/mailersend-ruby) ### Responses [#responses-4] #### Valid [#valid-4] ```http Response Code: 200 OK ``` #### Error [#error-2] ```http Response Code: 404 Not Found ``` # Sending an SMS (/api/v1/sms) This endpoint allows you to start sending SMSs through MailerSend SMS API. ## Send an SMS [#send-an-sms] This endpoint allows you to send an asynchronous SMS. It returns the status of the SMS sent with a `X-SMS-Message-Id` that can be used to continuously query for the status using the SMS API. Send an SMS using this `POST` request: ```http POST https://api.mailersend.com/v1/sms ``` #### Request Body \[!toc] [#request-body-toc] ```json { "from": "+19191234567", "to": [ "+19191234567", "+19199876543" ], "text": "Hey {{name}}! This is just a friendly hello :D", "personalization": [ { "phone_number": "+19191234567", "data": { "name": "Dummy" } }, { "phone_number": "+19199876543", "data": { "name": "Not Dummy" } } ] } ``` ```php use MailerSend\MailerSend; use MailerSend\Helpers\Builder\SmsParams; $mailersend = new MailerSend(['api_key' => 'key']); $smsParams = (new SmsParams()) ->setFrom('+12065550101') ->setTo(['+12065550102']) ->addRecipient('+12065550103') ->setText('Text'); $sms = $mailersend->sms->send($smsParams); ``` [More examples](https://github.com/mailersend/mailersend-php) ```javascript "use strict"; require('dotenv').config() const MailerSend = require("../../src/MailerSend"); const SmsParams = require("../../src/SmsParams"); const mailersend = new MailerSend({ api_key: process.env.API_KEY, }); const recipients = [ "+18332647501" ]; const smsParams = new SmsParams() .setFrom("+18332647501") .setRecipients(recipients) .setText("This is the text content"); mailersend.sendSms(smsParams); ``` [More examples](https://github.com/mailersend/mailersend-nodejs) ```python from mailersend import MailerSendClient, SmsSendingBuilder ms = MailerSendClient() # Simple SMS request = (SmsSendingBuilder() .from_number("sms-number") .to(["+1234567890", "+1234567891"]) .text("Hello from MailerSend SMS!") .build()) response = ms.sms_sending.send(request) ``` [More examples](https://github.com/mailersend/mailersend-python) ```go package main import ( "context" "fmt" "time" "github.com/mailersend/mailersend-go" ) var APIKey = "Api Key Here" func main() { // Create an instance of the mailersend client ms := mailersend.NewMailersend(APIKey) ctx := context.Background() ctx, cancel := context.WithTimeout(ctx, 5*time.Second) defer cancel() message := ms.Sms.NewMessage() message.SetFrom("your-number") message.SetTo([]string{"client-number"}) message.SetText("This is the message content {{ var }}") personalization := []mailersend.SmsPersonalization{ { PhoneNumber: "client-number", Data: map[string]interface{}{ "var": "foo", }, }, } message.SetPersonalization(personalization) res, _ := ms.Sms.Send(context.TODO(), message) fmt.Printf(res.Header.Get("X-SMS-Message-Id")) } ``` [More examples](https://github.com/mailersend/mailersend-go) ```java import com.mailersend.sdk.MailerSend; import com.mailersend.sdk.exceptions.MailerSendException; public void sendSms() { MailerSend ms = new MailerSend(); ms.setToken("mailersend token"); try { String messageId = ms.sms().builder().from("from phone number") .addRecipient("to phone number") .text("test sms {{name}}") .addPersonalization("to phone number", "name", "name personalization") .send(); System.out.println(messageId); } catch (MailerSendException e) { e.printStackTrace(); } } ``` [More examples](https://github.com/mailersend/mailersend-java) ```ruby require "mailersend-ruby" # Intialize the SMS class ms_sms = Mailersend::SMS.new # Add parameters ms_sms.add_from('your-number') ms_sms.add_to('client-number') ms_sms.add_text('This is the message content') personalization = { phone_number: 'client-number', data: { test: 'Test Value' } } ms_sms.add_personalization(personalization) # Send the SMS ms_sms.send ``` [More examples](https://github.com/mailersend/mailersend-ruby) #### Request parameters \[!toc] [#request-parameters-toc] *JSON parameters are provided in dot notation* | JSON parameter | Type | Required | Limitations | Details | | -------------------------------- | ---------- | -------- | ----------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `from` | `string` | yes | | Number belonging to your account in E164 format | | `to` | `string[]` | yes | `min:1`,`max:50` | | | `to.*` | `string` | yes | `US`, `CA` | The phone number(s) the message should be sent to in E164 format | | `text` | `string` | yes | `Max lenght:2048` | The contents of the text message. Must be 2048 characters or less. Curly braces (`{` and `}`) are not allowed.
If the body of your message is more than 160 GSM-7 characters or 70 UCS-2 characters, MailerSend will split the message into a segmented SMS and add a special header ([User Data Header](https://en.wikipedia.org/wiki/User_Data_Header)). Please note you are billed by segment.
The User Data Header (UDH) takes up 6 bytes and instructs the receiving device how to reassemble the segments so that your whole message will be shown as one SMS on the receiving handset. The maximum number of characters per concatenated (long) message is slightly reduced due to the inclusion of concatenation headers (UDH).
You can see the difference between GSM-7 and UCS-2 and how they're segmented [here](https://chadselph.github.io/smssplit/). | | `personalization` | `object[]` | no | | Allows using personalization in `{{ var }}` syntax. Can be used in the `text` fields. Read more about [advanced personalization](/features#advanced-personalization). | | `personalization.*.phone_number` | `string` | yes | | Phone number that personalization will be applied to. | | `personalization.*.data` | `object[]` | yes | | Object with `key: value` pairs. Values will be added to your template using `{{ key }}` syntax. | ### Responses [#responses] #### Sending queued [#sending-queued] ```http Response Code: 202 Accepted Response Headers: Content-Type: text/plain; charset=utf-8 X-SMS-Message-Id: 5e42957d51f1d94a1070a733 Response Body: [EMPTY] ``` #### Sending paused [#sending-paused] ```http Response Code: 202 Accepted Response Headers: Content-Type: text/plain; charset=utf-8 X-SMS-Message-Id: 5e42957d51f1d94a1070a733 X-SMS-Send-Paused: true Response Body: [EMPTY] ``` #### Validation error [#validation-error] ```http Response Code: 422 Unprocessable Entity Response Headers: content-type: application/json ``` ```json { "message": "The given data was invalid.", "errors": { "from": [ "The from field contains an invalid number." ] } } ``` *See - [Validations errors](/../../general#validation-errors)* # Messages (/api/v1/sms/messages) SMS Messages are resources that are created from a single SMS API request. ## Get a list of SMS messages [#get-a-list-of-sms-messages] Get a list of SMS messages information with this `GET` request: ```http GET https://api.mailersend.com/v1/sms-messages ``` #### Request parameters \[!toc] [#request-parameters-toc] | Query parameter | Type | Required | Limitations | Details | | --------------- | ----- | -------- | --------------------- | ------------- | | `page` | `int` | no | | | | `limit` | `int` | no | Min: `10`, Max: `100` | Default: `25` | ```php use MailerSend\MailerSend; $mailersend = new MailerSend(['api_key' => 'key']); $smsMessages = $mailersend->smsMessage->getAll($page = 1, $limit = 10); ``` [More examples](https://github.com/mailersend/mailersend-php) ```javascript import 'dotenv/config'; import { MailerSend } from "mailersend"; const mailerSend = new MailerSend({ apiKey: process.env.API_KEY, }); mailerSend.sms.message.list({ limit: 10, page: 1 }) .then((response) => console.log(response.body)) .catch((error) => console.log(error.body)); ``` [More examples](https://github.com/mailersend/mailersend-nodejs) ```python from mailersend import MailerSendClient, SmsMessagesBuilder ms = MailerSendClient() request = (SmsMessagesBuilder() .page(1) .limit(25) .build_sms_messages_list()) response = ms.sms_messages.list_sms_messages(request) ``` [More examples](https://github.com/mailersend/mailersend-python) ```go package main import ( "context" "log" "time" "github.com/mailersend/mailersend-go" ) var APIKey = "Api Key Here" func main() { // Create an instance of the mailersend client ms := mailersend.NewMailersend(APIKey) ctx := context.Background() ctx, cancel := context.WithTimeout(ctx, 5*time.Second) defer cancel() options := &mailersend.ListSmsMessageOptions{ Limit: 10, } _, _, err := ms.SmsMessage.List(ctx, options) if err != nil { log.Fatal(err) } } ``` [More examples](https://github.com/mailersend/mailersend-go) ```java import com.mailersend.sdk.MailerSend; import com.mailersend.sdk.exceptions.MailerSendException; import com.mailsend.sdk.sms.messages.SmsMessageList; import com.mailsend.sdk.sms.messages.SmsMessage; public void getSmsMessages() { MailerSend ms = new MailerSend(); ms.setToken("mailersend token"); try { SmsMessageList list = ms.sms().messages().getMessages(); for (SmsMessage message : list.messages) { System.out.println(message.id); System.out.println(message.text); } } catch (MailerSendException e) { e.printStackTrace(); } } ``` [More examples](https://github.com/mailersend/mailersend-java) ```ruby require "mailersend-ruby" # Intialize the SMS Messages class ms_sms_messages = Mailersend::SMSMessages.new # Add parameters ms_sms_messages.list(page: 1, limit: 10) ``` [More examples](https://github.com/mailersend/mailersend-ruby) ### Responses [#responses] #### Valid [#valid] ```http Response Code: 200 OK Response Headers: content-type: application/json ``` ```json { "data": [ { "id": "6203a0cc00033b7d341d0f52", "from": "+19191234567", "to": [ "+19199876543" ], "text": "Hello world", "paused": false, "created_at": "2022-01-01T12:00:00.000000Z" }, ... ] } ``` #### Error [#error] ```http Response Code: 422 Unprocessable Entity ``` *See - [Validations errors](/../../general#validation-errors)* ## Get an SMS message [#get-an-sms-message] Get a single SMS message. ```http GET https://api.mailersend.com/v1/sms-messages/{sms_message_id} ``` #### Request parameters \[!toc] [#request-parameters-toc-1] | URL parameter | Type | Required | Limitations | Details | | ---------------- | -------- | -------- | ----------- | ------- | | `sms_message_id` | `string` | yes | | | ```php use MailerSend\MailerSend; $mailersend = new MailerSend(['api_key' => 'key']); $smsMessage = $mailersend->smsMessage->find('sms_message_id'); ``` [More examples](https://github.com/mailersend/mailersend-php) ```javascript import 'dotenv/config'; import { MailerSend } from "mailersend"; const mailerSend = new MailerSend({ apiKey: process.env.API_KEY, }); mailerSend.sms.message.single("sms_message_id") .then((response) => console.log(response.body)) .catch((error) => console.log(error.body)); ``` [More examples](https://github.com/mailersend/mailersend-nodejs) ```python from mailersend import MailerSendClient, SmsMessagesBuilder ms = MailerSendClient() request = (SmsMessagesBuilder() .sms_message_id("message-id") .build_sms_message_get()) response = ms.sms_messages.get_sms_message(request) ``` [More examples](https://github.com/mailersend/mailersend-python) ```go package main import ( "context" "log" "time" "github.com/mailersend/mailersend-go" ) var APIKey = "Api Key Here" func main() { // Create an instance of the mailersend client ms := mailersend.NewMailersend(APIKey) ctx := context.Background() ctx, cancel := context.WithTimeout(ctx, 5*time.Second) defer cancel() _, _, err := ms.SmsMessage.Get(ctx, "sms-message-id") if err != nil { log.Fatal(err) } } ``` [More examples](https://github.com/mailersend/mailersend-go) ```java import com.mailersend.sdk.MailerSend; import com.mailersend.sdk.exceptions.MailerSendException; import com.mailsend.sdk.sms.messages.SmsMessage; public void getSmsMessage() { MailerSend ms = new MailerSend(); ms.setToken("mailersend token"); try { SmsMessage message = ms.sms().messages().getMessage("message id"); System.out.println(message.id); System.out.println(message.text); } catch (MailerSendException e) { e.printStackTrace(); } } ``` [More examples](https://github.com/mailersend/mailersend-java) ```ruby require "mailersend-ruby" # Intialize the SMS Messages class ms_sms_messages = Mailersend::SMSMessages.new # Add parameters ms_sms_messages.get_single_route(sms_message_id: 'your-sms-message-id') ``` [More examples](https://github.com/mailersend/mailersend-ruby) ### Responses [#responses-1] #### Valid [#valid-1] | Response key | Type | Details | | ------------ | ---------- | ---------------------------------------------------------------- | | `data.sms.*` | `object[]` | Will include `sms` data, if it has been created in the database. | ```http Response Code: 200 OK Response Headers: content-type: application/json ``` ```json { "data": { "id": "01h909rj94ybjnvpke60w866n6", "from": "+18332552485", "to": [ "+16062149989" ], "text": "Hey Jane! Your verification code is 1234567890.", "paused": false, "created_at": "2023-08-29T09:24:58.000000Z", "sms": [ { "id": "01h909rjj42mjxcpkxv6asq1jn", "from": "+18332552485", "to": "+16062149989", "text": "Hey Jane! Your verification code is 1234567890.", "compiled_text": "Hey Jane! Your verification code is 1234567890.", "status": "sent", "segment_count": 1, "error_type": null, "error_description": null, "created_at": "2023-08-29T09:24:59.000000Z" } ], "sms_activity": [ { "from": "+18332552485", "to": "+16062149989", "created_at": "2023-08-29T09:24:59.000000Z", "status": "processed", "sms_message_id": "01h909rj94ybjnvpke60w866n6" }, { "from": "+18332552485", "to": "+16062149989", "created_at": "2023-08-29T09:24:59.000000Z", "status": "queued", "sms_message_id": "01h909rj94ybjnvpke60w866n6" }, { "from": "+18332552485", "to": "+16062149989", "created_at": "2023-08-29T09:24:59.000000Z", "status": "sent", "sms_message_id": "01h909rj94ybjnvpke60w866n6" } ] } } ``` #### Error [#error-1] ```http Response Code: 404 Not Found ``` # Phone numbers (/api/v1/sms/numbers) Get information about SMS phone numbers. ## Get a list of SMS phone numbers [#get-a-list-of-sms-phone-numbers] Get a list of SMS phone numbers information with this `GET` request: ```http GET https://api.mailersend.com/v1/sms-numbers ``` #### Request parameters \[!toc] [#request-parameters-toc] | Query parameter | Type | Required | Limitations | Details | | --------------- | ----- | -------- | --------------------- | ------------- | | `paused` | bool | no | | | | `page` | `int` | no | | | | `limit` | `int` | no | Min: `10`, Max: `100` | Default: `25` | ```php use MailerSend\MailerSend; $mailersend = new MailerSend(['api_key' => 'key']); $sms = $mailersend->smsNumber->getAll($page = 1, $limit = 10, $paused = true); ``` [More examples](https://github.com/mailersend/mailersend-php) ```javascript import 'dotenv/config'; import { MailerSend } from "mailersend"; const mailerSend = new MailerSend({ apiKey: process.env.API_KEY, }); mailerSend.sms.number.single("sms_number_id") .then((response) => console.log(response.body)) .catch((error) => console.log(error.body)); ``` [More examples](https://github.com/mailersend/mailersend-nodejs) ```python from mailersend import MailerSendClient, SmsNumbersBuilder ms = MailerSendClient() request = (SmsNumbersBuilder() .paused(False) .page(1) .limit(25) .build_list_request()) response = ms.sms_numbers.list(request) ``` [More examples](https://github.com/mailersend/mailersend-python) ```go package main import ( "context" "log" "time" "github.com/mailersend/mailersend-go" ) var APIKey = "Api Key Here" func main() { // Create an instance of the mailersend client ms := mailersend.NewMailersend(APIKey) ctx := context.Background() ctx, cancel := context.WithTimeout(ctx, 5*time.Second) defer cancel() options := &mailersend.SmsNumberOptions{} _, _, err := ms.SmsNumber.List(context.TODO(), options) if err != nil { log.Fatal(err) } } ``` [More examples](https://github.com/mailersend/mailersend-go) ```java import com.mailersend.sdk.MailerSend; import com.mailersend.sdk.exceptions.MailerSendException; import com.mailersend.sdk.sms.phonenumbers.PhoneNumber; import com.mailersend.sdk.sms.phonenumbers.PhoneNumberList; public void getSmsPhoneNumbers() { MailerSend ms = new MailerSend(); ms.setToken("mailersend token"); try { PhoneNumberList numbers = ms.sms().phoneNumbers().getPhoneNumbers(); for (PhoneNumber number : numbers.phoneNumbers) { System.out.println(number.id); } } catch (MailerSendException e) { e.printStackTrace(); } } ``` [More examples](https://github.com/mailersend/mailersend-java) ```ruby require "mailersend-ruby" # Intialize the SMS Recipient class ms_sms_number = Mailersend::SMSNumber.new # Add parameters ms_sms_number.list(page: 1, limit: 10) ``` [More examples](https://github.com/mailersend/mailersend-ruby) ### Responses [#responses] #### Valid [#valid] ```http Response Code: 200 OK Response Headers: content-type: application/json ``` ```json { "data": [ { "id": "7z3m5jgrogdpyo6n", "telephone_number": "+1234567890", "paused": false, "created_at": "2022-01-01T12:00:00.000000Z" }, ... ] } ``` #### Error [#error] ```http Response Code: 422 Unprocessable Entity ``` *See - [Validations errors](/../../general#validation-errors)* ## Get an SMS phone number [#get-an-sms-phone-number] Get information about a specific SMS phone number with this `GET` request: ```http GET https://api.mailersend.com/v1/sms-numbers/{sms_number_id} ``` #### Request parameters \[!toc] [#request-parameters-toc-1] | URL parameter | Type | Required | Limitations | Details | | --------------- | ------ | -------- | ----------- | ------- | | `sms_number_id` | string | yes | | | ```php use MailerSend\MailerSend; $mailersend = new MailerSend(['api_key' => 'key']); $sms = $mailersend->smsNumber->find('sms_number_id'); ``` [More examples](https://github.com/mailersend/mailersend-php) ```javascript import 'dotenv/config'; import { MailerSend } from "mailersend"; const mailerSend = new MailerSend({ apiKey: process.env.API_KEY, }); mailerSend.sms.number.single("sms_number_id") .then((response) => console.log(response.body)) .catch((error) => console.log(error.body)); ``` [More examples](https://github.com/mailersend/mailersend-nodejs) ```python from mailersend import MailerSendClient, SmsNumbersBuilder ms = MailerSendClient() request = (SmsNumbersBuilder() .sms_number_id("sms-number-id") .build_get_request()) response = ms.sms_numbers.get(request) ``` [More examples](https://github.com/mailersend/mailersend-python) ```go package main import ( "context" "log" "time" "github.com/mailersend/mailersend-go" ) var APIKey = "Api Key Here" func main() { // Create an instance of the mailersend client ms := mailersend.NewMailersend(APIKey) ctx := context.Background() ctx, cancel := context.WithTimeout(ctx, 5*time.Second) defer cancel() _, _, err := ms.SmsNumber.Get(context.TODO(), "number-id") if err != nil { log.Fatal(err) } } ``` [More examples](https://github.com/mailersend/mailersend-go) ```java import com.mailersend.sdk.MailerSend; import com.mailersend.sdk.exceptions.MailerSendException; import com.mailersend.sdk.sms.phonenumbers.PhoneNumber; public void getSmsPhoneNumber() { MailerSend ms = new MailerSend(); ms.setToken("mailersend token"); try { PhoneNumber number = ms.sms().phoneNumbers().getPhoneNumber("phone number id"); System.out.println(number.id); } catch (MailerSendException e) { e.printStackTrace(); } } ``` [More examples](https://github.com/mailersend/mailersend-java) ```ruby require "mailersend-ruby" # Intialize the SMS Recipient class ms_sms_number = Mailersend::SMSNumber.new # Add parameters ms_sms_number.get(sms_number_id: 'your-sms-number-id') ``` [More examples](https://github.com/mailersend/mailersend-ruby) ### Responses [#responses-1] #### Valid [#valid-1] ```http Response Code: 200 OK Response Headers: content-type: application/json ``` ```json { "data": { "id": "7z3m5jgrogdpyo6n", "telephone_number": "+1234567890", "paused": false, "created_at": "2022-01-01T12:00:00.000000Z" } } ``` #### Error [#error-1] ```http Response Code: 404 Not Found ``` ## Update a single SMS phone number [#update-a-single-sms-phone-number] Update a specific SMS phone number with this `PUT` request: ```http PUT https://api.mailersend.com/v1/sms-numbers/{sms_number_id} ``` #### Request parameters \[!toc] [#request-parameters-toc-2] | URL parameter | Type | Required | Limitations | Details | | --------------- | ------ | -------- | ----------- | ------- | | `sms_number_id` | string | yes | | | | Query parameter | Type | Required | Limitations | Details | | --------------- | ------ | -------- | ----------- | ------- | | `paused` | `bool` | no | | | ```php use MailerSend\MailerSend; $mailersend = new MailerSend(['api_key' => 'key']); $sms = $mailersend->smsNumber->update('sms_number_id', $paused = true); ``` [More examples](https://github.com/mailersend/mailersend-php) ```javascript import 'dotenv/config'; import { MailerSend } from "mailersend"; const mailerSend = new MailerSend({ apiKey: process.env.API_KEY, }); mailerSend.sms.number.update("sms_number_id", true) .then((response) => console.log(response.body)) .catch((error) => console.log(error.body)); ``` [More examples](https://github.com/mailersend/mailersend-nodejs) ```python from mailersend import MailerSendClient, SmsNumbersBuilder ms = MailerSendClient() request = (SmsNumbersBuilder() .sms_number_id("sms-number-id") .paused(True) .build_update_request()) response = ms.sms_numbers.update(request) ``` [More examples](https://github.com/mailersend/mailersend-python) ```go package main import ( "context" "log" "time" "github.com/mailersend/mailersend-go" ) var APIKey = "Api Key Here" func main() { // Create an instance of the mailersend client ms := mailersend.NewMailersend(APIKey) ctx := context.Background() ctx, cancel := context.WithTimeout(ctx, 5*time.Second) defer cancel() options := &mailersend.SmsNumberSettingOptions{ Id: "number-id", Paused: mailersend.Bool(false), } _, _, err := ms.SmsNumber.Update(context.TODO(), options) if err != nil { log.Fatal(err) } } ``` [More examples](https://github.com/mailersend/mailersend-go) ```java import com.mailersend.sdk.MailerSend; import com.mailersend.sdk.exceptions.MailerSendException; import com.mailersend.sdk.sms.phonenumbers.PhoneNumber; public void updateSmsPhoneNumber() { MailerSend ms = new MailerSend(); ms.setToken("mailersend token"); try { boolean pausePhoneNumber = false; PhoneNumber number = ms.sms().phoneNumbers().updatePhoneNumber("phone number id", pausePhoneNumber); } catch (MailerSendException e) { e.printStackTrace(); } } ``` [More examples](https://github.com/mailersend/mailersend-java) ```ruby require "mailersend-ruby" # Intialize the SMS Recipient class ms_sms_number = Mailersend::SMSNumber.new # Add parameters ms_sms_number.update(sms_number_id: 'your-sms-number-id', paused: false) ``` [More examples](https://github.com/mailersend/mailersend-ruby) ### Responses [#responses-2] #### Valid [#valid-2] ```http Response Code: 200 OK Response Headers: content-type: application/json ``` ```json { "data": { "id": "7z3m5jgrogdpyo6n", "telephone_number": "+1234567890", "paused": true, "created_at": "2022-01-01T12:00:00.000000Z" } } ``` #### Error [#error-2] ```http Response Code: 422 Unprocessable Entity ``` *See - [Validations errors](/../../general#validation-errors)* ## Delete an SMS phone number [#delete-an-sms-phone-number] Delete an SMS phone number with this `DELETE` request: ```http DELETE https://api.mailersend.com/v1/sms-numbers/{sms_number_id} ``` #### Request parameters \[!toc] [#request-parameters-toc-3] | URL parameter | Type | Required | Limitations | Details | | --------------- | ------ | -------- | ----------- | ------- | | `sms_number_id` | string | yes | | | ```php use MailerSend\MailerSend; $mailersend = new MailerSend(['api_key' => 'key']); $sms = $mailersend->smsNumber->delete('sms_number_id'); ``` [More examples](https://github.com/mailersend/mailersend-php) ```javascript import 'dotenv/config'; import { MailerSend } from "mailersend"; const mailerSend = new MailerSend({ apiKey: process.env.API_KEY, }); mailerSend.sms.number.delete("sms_number_id") .then((response) => console.log(response.body)) .catch((error) => console.log(error.body)); ``` [More examples](https://github.com/mailersend/mailersend-nodejs) ```python from mailersend import MailerSendClient, SmsNumbersBuilder ms = MailerSendClient() request = (SmsNumbersBuilder() .sms_number_id("sms-number-id") .build_delete_request()) response = ms.sms_numbers.delete(request) ``` [More examples](https://github.com/mailersend/mailersend-python) ```go package main import ( "context" "log" "time" "github.com/mailersend/mailersend-go" ) var APIKey = "Api Key Here" func main() { // Create an instance of the mailersend client ms := mailersend.NewMailersend(APIKey) ctx := context.Background() ctx, cancel := context.WithTimeout(ctx, 5*time.Second) defer cancel() numberID := "number-id" _, err := ms.SmsNumber.Delete(ctx, numberID) if err != nil { log.Fatal(err) } } ``` [More examples](https://github.com/mailersend/mailersend-go) ```java import com.mailersend.sdk.MailerSend; import com.mailersend.sdk.exceptions.MailerSendException; public void deleteSmsPhoneNumber() { MailerSend ms = new MailerSend(); ms.setToken("mailersend token"); try { boolean result = ms.sms().phoneNumbers().deletePhoneNumber("phone number id"); System.out.println(result); } catch (MailerSendException e) { e.printStackTrace(); } } ``` [More examples](https://github.com/mailersend/mailersend-java) ```ruby require "mailersend-ruby" # Intialize the SMS Recipient class ms_sms_number = Mailersend::SMSNumber.new # Add parameters ms_sms_number.delete(sms_number_id: 'your-sms-number-id') ``` [More examples](https://github.com/mailersend/mailersend-ruby) ### Responses [#responses-3] #### Valid [#valid-3] ```http Response Code: 204 OK Response Body: [EMPTY] ``` #### Error [#error-3] ```http Response Code: 404 Not Found ``` # Recipients (/api/v1/sms/recipients) Get information about SMS recipients. ## Get a list of SMS recipients [#get-a-list-of-sms-recipients] Get a list of SMS recipients information with this `GET` request: ```http GET https://api.mailersend.com/v1/sms-recipients ``` #### Request parameters \[!toc] [#request-parameters-toc] | Query parameter | Type | Required | Limitations | Details | | --------------- | -------- | -------- | --------------------- | ------------- | | `status` | `string` | no | `active`, `opt_out` | | | `sms_number_id` | `string` | no | | | | `page` | `int` | no | | | | `limit` | `int` | no | Min: `10`, Max: `100` | Default: `25` | ```php use MailerSend\MailerSend; use MailerSend\Helpers\Builder\SmsRecipientParams; $mailersend = new MailerSend(['api_key' => 'key']); $smsRecipientParams = (new SmsRecipientParams()) ->setSmsNumberId('sms_number_id') ->setStatus('opt_out') ->setPage(3) ->setLimit(15); $smsRecipients = $mailersend->smsRecipient->getAll($smsRecipientParams); ``` [More examples](https://github.com/mailersend/mailersend-php) ```javascript import 'dotenv/config'; import { MailerSend } from "mailersend"; const mailerSend = new MailerSend({ apiKey: process.env.API_KEY, }); mailerSend.sms.recipient.list({ sms_number_id: "sms_number_id", status: "active", limit: 10, page: 1, }) .then((response) => console.log(response.body)) .catch((error) => console.log(error.body)); ``` [More examples](https://github.com/mailersend/mailersend-nodejs) ```python from mailersend import MailerSendClient, SmsRecipientsBuilder from mailersend.models.sms_recipients import SmsRecipientStatus ms = MailerSendClient() request = (SmsRecipientsBuilder() .sms_number_id("sms-number-id") .status(SmsRecipientStatus.ACTIVE) .page(1) .limit(25) .build_list_request()) response = ms.sms_recipients.list_sms_recipients(request) ``` [More examples](https://github.com/mailersend/mailersend-python) ```go package main import ( "context" "log" "time" "github.com/mailersend/mailersend-go" ) var APIKey = "Api Key Here" func main() { // Create an instance of the mailersend client ms := mailersend.NewMailersend(APIKey) ctx := context.Background() ctx, cancel := context.WithTimeout(ctx, 5*time.Second) defer cancel() options := &mailersend.SmsRecipientOptions{SmsNumberId: "sms-number-id"} _, _, err := ms.SmsRecipient.List(context.TODO(), options) if err != nil { log.Fatal(err) } } ``` [More examples](https://github.com/mailersend/mailersend-go) ```java import com.mailersend.sdk.MailerSend; import com.mailersend.sdk.exceptions.MailerSendException; import com.mailersend.sdk.sms.recipients.SmsRecipient; import com.mailersend.sdk.sms.recipients.SmsRecipientList; public void getSmsRecipients() { MailerSend ms = new MailerSend(); ms.setToken("mailersend token"); try { SmsRecipientList list = ms.sms().recipients().getRecipients(); for (SmsRecipient recipient : list.recipients) { System.out.println(recipient.id); } } catch (MailerSendException e) { e.printStackTrace(); } } ``` [More examples](https://github.com/mailersend/mailersend-java) ```ruby require "mailersend-ruby" # Intialize the SMS Recipient class ms_sms_recipient = Mailersend::SMSRecipient.new # Add parameters ms_sms_recipient.list(page: 1, limit: 10) ``` [More examples](https://github.com/mailersend/mailersend-ruby) ### Responses [#responses] #### Valid [#valid] ```http Response Code: 200 OK Response Headers: content-type: application/json ``` ```json { "data": [ { "id": "62347d2be979fd275c0afd34", "number": "+1234567890", "status": "active", "created_at": "2022-01-01T12:00:0003.000000Z" }, ... ] } ``` #### Error [#error] ```http Response Code: 422 Unprocessable Entity ``` *See - [Validations errors](/../../general#validation-errors)* ## Get an SMS recipient [#get-an-sms-recipient] Get information about a specific SMS recipient with this `GET` request: ```http GET https://api.mailersend.com/v1/sms-recipients/{sms_recipient_id} ``` #### Request parameters \[!toc] [#request-parameters-toc-1] | URL parameter | Type | Required | Limitations | Details | | ------------------ | ------ | -------- | ----------- | ------- | | `sms_recipient_id` | string | yes | | | ```php use MailerSend\MailerSend; $mailersend = new MailerSend(['api_key' => 'key']); $smsRecipients = $mailersend->smsRecipient->find('sms_recipient_id'); ``` [More examples](https://github.com/mailersend/mailersend-php) ```javascript import 'dotenv/config'; import { MailerSend } from "mailersend"; const mailerSend = new MailerSend({ apiKey: process.env.API_KEY, }); mailerSend.sms.recipient.single("sms_recipient_id") .then((response) => console.log(response.body)) .catch((error) => console.log(error.body)); ``` [More examples](https://github.com/mailersend/mailersend-nodejs) ```python from mailersend import MailerSendClient, SmsRecipientsBuilder ms = MailerSendClient() request = (SmsRecipientsBuilder() .sms_recipient_id("recipient-id") .build_get_request()) response = ms.sms_recipients.get_sms_recipient(request) ``` [More examples](https://github.com/mailersend/mailersend-python) ```go package main import ( "context" "log" "time" "github.com/mailersend/mailersend-go" ) var APIKey = "Api Key Here" func main() { // Create an instance of the mailersend client ms := mailersend.NewMailersend(APIKey) ctx := context.Background() ctx, cancel := context.WithTimeout(ctx, 5*time.Second) defer cancel() _, _, err := ms.SmsRecipient.Get(context.TODO(), "sms-recipient-id") if err != nil { log.Fatal(err) } } ``` [More examples](https://github.com/mailersend/mailersend-go) ```java import com.mailersend.sdk.MailerSend; import com.mailersend.sdk.exceptions.MailerSendException; import com.mailersend.sdk.sms.recipients.SmsRecipient; public void getSmsRecipient() { MailerSend ms = new MailerSend(); ms.setToken("mailersend token"); try { SmsRecipient recipient = ms.sms().recipients().getRecipient("recipient id"); System.out.println(recipient.id); } catch (MailerSendException e) { e.printStackTrace(); } } ``` [More examples](https://github.com/mailersend/mailersend-java) ```ruby require "mailersend-ruby" # Intialize the SMS Recipient class ms_sms_recipient = Mailersend::SMSRecipient.new # Add parameters ms_sms_recipient.get(sms_recipient_id: 'your-sms-recipient-id') ``` [More examples](https://github.com/mailersend/mailersend-ruby) ### Responses [#responses-1] #### Valid [#valid-1] ```http Response Code: 200 OK Response Headers: content-type: application/json ``` ```json { "data": { "id": "62347d2be979fd275c0afd34", "number": "+1234567890", "status": "active", "created_at": "2022-01-01T12:00:00.000000Z", "sms": [ { "id": "62347d2be979fd275c0afd33", "from": "+1234567890", "to": "+1234567890", "text": "Lorem Ipsum is simply dummy text", "status": "delivered", "segment_count": 1, "error_type": null, "error_description": null, "created_at": "2022-01-01T12:00:00.000000Z" } ] } } ``` #### Error [#error-1] ```http Response Code: 404 Not Found ``` ## Update a single SMS recipient [#update-a-single-sms-recipient] Update a specific SMS recipient with this `PUT` request: ```http PUT https://api.mailersend.com/v1/sms-recipients/{sms_recipient_id} ``` #### Request parameters \[!toc] [#request-parameters-toc-2] | URL parameter | Type | Required | Limitations | Details | | ------------------ | ------ | -------- | ----------- | ------- | | `sms_recipient_id` | string | yes | | | | Query parameter | Type | Required | Limitations | Details | | --------------- | -------- | -------- | ------------------- | ------- | | `status` | `string` | yes | `active`, `opt_out` | | ```php use MailerSend\MailerSend; $mailersend = new MailerSend(['api_key' => 'key']); $smsRecipients = $mailersend->smsRecipient->update('sms_recipient_id', $status = 'opt_out'); ``` [More examples](https://github.com/mailersend/mailersend-php) ```javascript import 'dotenv/config'; import { MailerSend } from "mailersend"; const mailerSend = new MailerSend({ apiKey: process.env.API_KEY, }); mailerSend.sms.recipient.list({ sms_number_id: "sms_number_id", status: "active", limit: 10, page: 1, }) .then((response) => console.log(response.body)) .catch((error) => console.log(error.body)); ``` [More examples](https://github.com/mailersend/mailersend-nodejs) ```python from mailersend import MailerSendClient, SmsRecipientsBuilder from mailersend.models.sms_recipients import SmsRecipientStatus ms = MailerSendClient() request = (SmsRecipientsBuilder() .sms_recipient_id("recipient-id") .build_update_request(SmsRecipientStatus.OPT_OUT)) response = ms.sms_recipients.update_sms_recipient(request) ``` [More examples](https://github.com/mailersend/mailersend-python) ```go package main import ( "context" "log" "time" "github.com/mailersend/mailersend-go" ) var APIKey = "Api Key Here" func main() { // Create an instance of the mailersend client ms := mailersend.NewMailersend(APIKey) ctx := context.Background() ctx, cancel := context.WithTimeout(ctx, 5*time.Second) defer cancel() options := &mailersend.SmsRecipientSettingOptions{ Id: "sms-recipient-id", Status: "opt_out", } _, _, err := ms.SmsRecipient.Update(context.TODO(), options) if err != nil { log.Fatal(err) } } ``` [More examples](https://github.com/mailersend/mailersend-go) ```java import com.mailersend.sdk.MailerSend; import com.mailersend.sdk.exceptions.MailerSendException; import com.mailersend.sdk.sms.recipients.SmsRecipient; public void updateSmsRecipient() { MailerSend ms = new MailerSend(); ms.setToken("mailersend token"); try { String status = "opt_out"; SmsRecipient recipient = ms.sms().recipients().updateRecipient("recipient id", status); System.out.println(recipient.status); } catch (MailerSendException e) { e.printStackTrace(); } } ``` [More examples](https://github.com/mailersend/mailersend-java) ```ruby require "mailersend-ruby" # Intialize the SMS Recipient class ms_sms_recipient = Mailersend::SMSRecipient.new # Add parameters ms_sms_recipient.update(sms_recipient_id: 'your-sms-recipient-id', status: 'opt_out') ``` [More examples](https://github.com/mailersend/mailersend-ruby) ### Responses [#responses-2] #### Valid [#valid-2] ```http Response Code: 200 OK Response Headers: content-type: application/json ``` ```json { "data": { "id": "62347d2be979fd275c0afd34", "number": "+1234567890", "status": "opt_out", "created_at": "2022-01-01T12:00:0003.000000Z" } } ``` #### Error [#error-2] ```http Response Code: 422 Unprocessable Entity ``` *See - [Validations errors](/../../general#validation-errors)* # Webhooks (/api/v1/sms/webhooks) SMS Webhooks allow you to subscribe to real-time notifications about various SMS events that occur in MailerSend. You can create a SMS webhook directly from your MailerSend account and listen for events so your integration can automatically trigger reactions. ## SMS Webhooks overview [#sms-webhooks-overview] ### Setup [#setup] Currently, you can create a SMS webhook using the API endpoints listed below or directly from your account. [Read more about webhooks](https://www.mailersend.com/help/webhooks). ### URL validation [#url-validation] When creating or updating a webhook, MailerSend will send a test request to the provided URL to verify that it is reachable. The endpoint must return a `2xx` response for the webhook to be saved successfully. The test request uses the following payload: ```json { "type": "webhook.test", "message": "This is a ping test message", "created_at": "2026-03-27T07:24:20.577080Z" } ``` This test request is signed with a fixed test secret: `test_Am3L1GuOIc4blLUuHqAPxxwkZaJyEk8G`. Use it to verify the signature of incoming test requests. ### Available events [#available-events] These are all the events you can listen to and send a notification for. | Event | Description | | --------------- | ------------------------------------------------------------------------------------------------------------------- | | `sms.sent` | Fired when your SMS is sent from our sending servers. We are now waiting for a response from the receiving servers. | | `sms.delivered` | Fired when your SMS is successfully delivered with no errors. | | `sms.failed` | Fired when your SMS failed to deliver. | ### Payload example [#payload-example] Our responses contain fat payloads, including the information about the event-related object, so there is no need to make an additional API request. An example of `sms.sent` event: ``` { "type": "sms.sent", "sms_number_id": "7z3m5jgrogdpyo6n", "created_at": "2022-01-01T12:00:00.000000Z", "sms_webhook_id": "7z3m5jgrogdpyo6n", "url": "https://www.mailersend.com/webhook", "data": { "from": "+12345678901", "to": "+98765432109", "created_at": "2022-01-01T12:00:00.000000Z", "status": "sent", "sms_message_id": "6244233a7e194137e70e3bd2", "sms": { "id": "6244233a7e194137e70e3bd2", "from": "+12345678901", "to": "+98765432109", "text": "Lorem Ipsum is simply dummy text", "status": "sent", "segment_count": 1, "error_type": null, "error_description": null, "created_at": "2022-01-01T12:00:00.000000Z", "recipient": { "id": "6244233a7e194137e70e3bd2", "number": "+98765432109", "status": "active", "created_at": "2022-01-01T12:00:00.000000Z" } } } } ``` ### Security [#security] Webhook requests made by MailerSend include a `Signature` header. It contains a string generated by hashing the data sent to your webhook endpoint with an individual Signing Secret. A signing secret is a random string that is generated when you create a webhook. **Verifying a signature:** ```php // $signature - a header sent by MailerSend, please refer to your framework // or PHP manual on how to read the Signature header // $requestContent - please refer to your framework or PHP manual on how to read the request content $computedSignature = hash_hmac('sha256', $requestContent, $signingSecret); return hash_equals($signature, $computedSignature); ``` If your endpoint is unreachable or returns a non-2xx response, MailerSend automatically retries with exponential backoff for up to about 3 days. While your webhook is failing we'll send escalating email notifications. If the endpoint stays down too long, the webhook is automatically paused. You can re-enable it from your dashboard at any time. ### Retrying failed webhooks [#retrying-failed-webhooks] When your webhook receives a response other than a `2xx` code from your endpoint URL, or if the endpoint doesn’t respond within 3 seconds, it will show up as a failed attempt in the log section of your webhook. If it receives a `2xx`, then it will show as a success. If a webhook call fails, MailerSend automatically retries with exponential backoff for up to about 3 days. Some failures are considered unrecoverable and aren't retried. Examples include `4xx` client errors (other than `429`) and DNS resolution failures. In these cases only a single attempt is logged, so verify your endpoint URL is reachable before relying on retries. ### Useful tools [#useful-tools] [Webhook.site](https://webhook.site/) or [Pipedream.com](https://pipedream.com/) are useful tools for testing webhooks quickly, seeing how it works, and inspecting what's being sent—without any coding on your side. ## Get a list of SMS webhooks [#get-a-list-of-sms-webhooks] If you want to retrieve information about SMS webhooks, use this `GET` request: ```http GET https://api.mailersend.com/v1/sms-webhooks ``` #### Request parameters \[!toc] [#request-parameters-toc] | Parameter | Type | Required | Limitations | Details | | --------------- | -------- | -------- | --------------------- | ------------- | | `sms_number_id` | `string` | yes | | | | `limit` | `int` | no | Min: `10`, Max: `100` | Default: `25` | | `page` | `int` | no | Min: `1` | | ```php use MailerSend\MailerSend; $mailersend = new MailerSend(['api_key' => 'key']); $smsRecipients = $mailersend->smsWebhook->get('sms_number_id'); ``` [More examples](https://github.com/mailersend/mailersend-php) ```javascript import 'dotenv/config'; import { MailerSend } from "mailersend"; const mailerSend = new MailerSend({ apiKey: process.env.API_KEY, }); mailerSend.sms.webhook.list("sms_number_id") .then((response) => console.log(response.body)) .catch((error) => console.log(error.body)); ``` [More examples](https://github.com/mailersend/mailersend-nodejs) ```python from mailersend import MailerSendClient, SmsWebhooksBuilder ms = MailerSendClient() request = (SmsWebhooksBuilder() .sms_number_id("sms-number-id") .build_list_request()) response = ms.sms_webhooks.list_sms_webhooks(request) ``` [More examples](https://github.com/mailersend/mailersend-python) ```go package main import ( "context" "log" "time" "github.com/mailersend/mailersend-go" ) var APIKey = "Api Key Here" func main() { // Create an instance of the mailersend client ms := mailersend.NewMailersend(APIKey) ctx := context.Background() ctx, cancel := context.WithTimeout(ctx, 5*time.Second) defer cancel() options := &mailersend.ListSmsWebhookOptions{ SmsNumberId: "sms-number-id", } _, _, err := ms.SmsWebhook.List(ctx, options) if err != nil { log.Fatal(err) } } ``` [More examples](https://github.com/mailersend/mailersend-go) ```java import com.mailersend.sdk.MailerSend; import com.mailersend.sdk.exceptions.MailerSendException; import com.mailersend.sms.webhooks.SmsWebhook; import com.mailersend.sms.webhooks.SmsWebhookList; public void getSmsWebhooks() { MailerSend ms = new MailerSend(); ms.setToken("mailersend token"); try { SmsWebhookList list = ms.sms().webhooks().getWebhooks("phone number id"); for (SmsWebhook webhook : list.webhooks) { System.out.println(webhook.id); } } catch (MailerSendException e) { e.printStackTrace(); } } ``` [More examples](https://github.com/mailersend/mailersend-java) ```ruby require "mailersend-ruby" # Intialize the SMS Webhooks class ms_sms_webhooks = Mailersend::SMSWebhooks.new # Add parameters ms_sms_webhooks.list(sms_number_id: 'your-sms-number-id') ``` [More examples](https://github.com/mailersend/mailersend-ruby) ## Get a single SMS webhook [#get-a-single-sms-webhook] To retrieve information about a single SMS webhook, use this `GET` request: ```http GET https://api.mailersend.com/v1/sms-webhooks/{sms_webhook_id} ``` #### Request parameters \[!toc] [#request-parameters-toc-1] | URL Parameter | Type | Required | Limitations | Details | | ---------------- | -------- | -------- | ----------- | ------- | | `sms_webhook_id` | `string` | yes | | | ```php use MailerSend\MailerSend; $mailersend = new MailerSend(['api_key' => 'key']); $smsRecipients = $mailersend->smsWebhook->find('sms_webhook_id'); ``` [More examples](https://github.com/mailersend/mailersend-php) ```javascript import 'dotenv/config'; import { MailerSend } from "mailersend"; const mailerSend = new MailerSend({ apiKey: process.env.API_KEY, }); mailerSend.sms.webhook.single("sms_webhook_id") .then((response) => console.log(response.body)) .catch((error) => console.log(error.body)); ``` [More examples](https://github.com/mailersend/mailersend-nodejs) ```python from mailersend import MailerSendClient, SmsWebhooksBuilder ms = MailerSendClient() request = (SmsWebhooksBuilder() .sms_webhook_id("webhook-id") .build_get_request()) response = ms.sms_webhooks.get_sms_webhook(request) ``` [More examples](https://github.com/mailersend/mailersend-python) ```go package main import ( "context" "log" "time" "github.com/mailersend/mailersend-go" ) var APIKey = "Api Key Here" func main() { // Create an instance of the mailersend client ms := mailersend.NewMailersend(APIKey) ctx := context.Background() ctx, cancel := context.WithTimeout(ctx, 5*time.Second) defer cancel() _, _, err := ms.SmsWebhook.Get(ctx, "sms-webhook-id") if err != nil { log.Fatal(err) } } ``` [More examples](https://github.com/mailersend/mailersend-go) ```java import com.mailersend.sdk.MailerSend; import com.mailersend.sdk.exceptions.MailerSendException; import com.mailersend.sms.webhooks.SmsWebhook; public void getSmsWebhook() { MailerSend ms = new MailerSend(); ms.setToken("mailersend token"); try { SmsWebhook webhook = ms.sms().webhooks().getWebhook("webhook id"); System.out.println(webhook.id); } catch (MailerSendException e) { e.printStackTrace(); } } ``` [More examples](https://github.com/mailersend/mailersend-java) ```ruby require "mailersend-ruby" # Intialize the SMS Webhooks class ms_sms_webhooks = Mailersend::SMSWebhooks.new # Add parameters ms_sms_webhooks.get_sms_webhook_route(sms_webhook_id: 'your-sms-webhook-id') ``` [More examples](https://github.com/mailersend/mailersend-ruby) ## Create an SMS webhook [#create-an-sms-webhook] Create a SMS webhook using this `POST` request: ```http POST https://api.mailersend.com/v1/sms-webhooks/ ``` #### Request parameters \[!toc] [#request-parameters-toc-2] *JSON parameters are provided in dot notation* | JSON Parameter | Type | Required | Limitations | Details | | --------------- | --------- | -------- | ------------------ | ------------------------------ | | `url` | `url` | yes | Max: `191`, unique | | | `name` | `string` | yes | Max: `191` | | | `events` | `array` | yes | | | | `enabled` | `boolean` | optional | | | | `sms_number_id` | `string` | yes | | Existing hashed SMS number ID. | ```php use MailerSend\MailerSend; use MailerSend\Helpers\Builder\SmsWebhookParams; $mailersend = new MailerSend(['api_key' => 'key']); $smsWebhookParams = (new SmsWebhookParams()) ->setSmsNumberId('sms_number_id') ->setName('Name') ->setUrl('https://mailersend.com/sms_webhook') ->setEvents(['sms.sent', 'sms.delivered', 'sms.failed']) ->setEnabled(false); $smsRecipients = $mailersend->smsWebhook->create($smsWebhookParams); ``` [More examples](https://github.com/mailersend/mailersend-php) ```javascript import 'dotenv/config'; import { MailerSend, SmsWebhook, SmsWebhookEventType } from "mailersend"; const mailerSend = new MailerSend({ apiKey: process.env.API_KEY, }); const smsWebhook = new SmsWebhook() .setName("Sms Webhook") .setUrl("https:://yourapp.com/hook") .setSmsNumberId("sms_number_id") .setEnabled(true) .setEvents([SmsWebhookEventType.SENT, SmsWebhookEventType.DELIVERED]) mailerSend.sms.webhook.create(smsWebhook) .then((response) => console.log(response.body)) .catch((error) => console.log(error.body)); ``` [More examples](https://github.com/mailersend/mailersend-nodejs) ```python from mailersend import MailerSendClient, SmsWebhooksBuilder from mailersend.models.sms_webhooks import SmsWebhookEvent ms = MailerSendClient() request = (SmsWebhooksBuilder() .from_number("sms-number-id") .url("https://webhook.example.com/sms") .name("SMS Webhook") .add_event(SmsWebhookEvent.SMS_SENT) .add_event(SmsWebhookEvent.SMS_DELIVERED) .add_event(SmsWebhookEvent.SMS_FAILED) .enabled(True) .build_create_request()) response = ms.sms_webhooks.create_sms_webhook(request) ``` [More examples](https://github.com/mailersend/mailersend-python) ```go package main import ( "context" "log" "time" "github.com/mailersend/mailersend-go" ) var APIKey = "Api Key Here" func main() { // Create an instance of the mailersend client ms := mailersend.NewMailersend(APIKey) ctx := context.Background() ctx, cancel := context.WithTimeout(ctx, 5*time.Second) defer cancel() events := []string{"sms.sent"} options := &mailersend.CreateSmsWebhookOptions{ SmsNumberId: "sms-number-id", Name: "Webhook", Events: events, URL: "https://test.com", Enabled: mailersend.Bool(false), } _, _, err := ms.SmsWebhook.Create(ctx, options) if err != nil { log.Fatal(err) } } ``` [More examples](https://github.com/mailersend/mailersend-go) ```java import com.mailersend.sdk.MailerSend; import com.mailersend.sdk.exceptions.MailerSendException; import com.mailersend.sms.webhooks.SmsWebhook; public void createSmsWebhook() { MailerSend ms = new MailerSend(); ms.setToken("mailersend token"); try { SmsWebhook webhook = ms.sms().webhooks().builder() .addEvent("sms.sent") .name("sms webhook") .url("https://example.com") .createWebhook("sms phone number id"); System.out.print(webhook.id); } catch (MailerSendException e) { e.printStackTrace(); } } ``` [More examples](https://github.com/mailersend/mailersend-java) ```ruby require "mailersend-ruby" # Intialize the SMS Webhooks class ms_sms_webhooks = Mailersend::SMSWebhooks.new # Add parameters ms_sms_webhooks.settings = { 'sms_number_id' => 'your-sms-number-id', 'name' => 'your-name', 'url' => 'https://your-url.com', 'events' => ['sms.sent', 'sms.delivered'] } puts ms_sms_webhooks.add_sms_webhook_route ``` [More examples](https://github.com/mailersend/mailersend-ruby) ## Update a single SMS webhook [#update-a-single-sms-webhook] Update a SMS webhook using this `PUT` request: ```http PUT https://api.mailersend.com/v1/sms-webhooks/{sms_webhook_id} ``` ### Request Parameters \[!toc] [#request-parameters-toc-3] | URL Parameter | Type | Required | Limitations | Details | | ---------------- | -------- | -------- | ----------- | ------- | | `sms_webhook_id` | `string` | yes | | | *JSON parameters are provided in dot notation* | JSON Parameter | Type | Required | Limitations | Details | | -------------- | --------- | -------- | ----------- | ------- | | `url` | `url` | optional | Max: `191` | | | `name` | `string` | optional | Max: `191` | | | `events` | `array` | optional | | | | `enabled` | `boolean` | optional | | | ```php use MailerSend\MailerSend; use MailerSend\Helpers\Builder\SmsWebhookParams; $mailersend = new MailerSend(['api_key' => 'key']); $smsWebhookParams = (new SmsWebhookParams()) ->setSmsNumberId('sms_number_id') ->setName('Name') ->setUrl('https://mailersend.com/sms_webhook') ->setEvents(['sms.sent', 'sms.delivered', 'sms.failed']) ->setEnabled(false); $smsRecipients = $mailersend->smsWebhook->update('sms_webhook_id', $smsWebhookParams); ``` [More examples](https://github.com/mailersend/mailersend-php) ```javascript import 'dotenv/config'; import { MailerSend } from "mailersend"; const mailerSend = new MailerSend({ apiKey: process.env.API_KEY, }); mailerSend.sms.webhook.update("sms_webhook_id", { name: "Webhook", url: "https:://yourapp.com/hook", enabled: ["sms.sent", "sms.delivered", "sms.failed"], enabled: true }) .then((response) => console.log(response.body)) .catch((error) => console.log(error.body)); ``` [More examples](https://github.com/mailersend/mailersend-nodejs) ```python from mailersend import MailerSendClient, SmsWebhooksBuilder from mailersend.models.sms_webhooks import SmsWebhookEvent ms = MailerSendClient() request = (SmsWebhooksBuilder() .sms_webhook_id("webhook-id") .name("Updated SMS Webhook") .url("https://new-webhook.example.com/sms") .events([SmsWebhookEvent.SMS_DELIVERED, SmsWebhookEvent.SMS_FAILED]) .enabled(False) .build_update_request()) response = ms.sms_webhooks.update_sms_webhook(request) ``` [More examples](https://github.com/mailersend/mailersend-python) ```go package main import ( "context" "log" "time" "github.com/mailersend/mailersend-go" ) var APIKey = "Api Key Here" func main() { // Create an instance of the mailersend client ms := mailersend.NewMailersend(APIKey) ctx := context.Background() ctx, cancel := context.WithTimeout(ctx, 5*time.Second) defer cancel() events := []string{"sms.sent"} options := &mailersend.UpdateSmsWebhookOptions{ Id: "sms-webhook-id", Name: "Webhook", Events: events, Enabled: mailersend.Bool(true), URL: "https://test.com", } _, _, err := ms.SmsWebhook.Update(ctx, options) if err != nil { log.Fatal(err) } } ``` [More examples](https://github.com/mailersend/mailersend-go) ```java import com.mailersend.sdk.MailerSend; import com.mailersend.sdk.exceptions.MailerSendException; import com.mailersend.sms.webhooks.SmsWebhook; public void updateSmsWebhook() { MailerSend ms = new MailerSend(); ms.setToken("mailersend token"); try { SmsWebhook webhook = ms.sms().webhooks().builder() .name("sms updated webhook") .updateWebhook("webhook id"); System.out.print(webhook.name); } catch (MailerSendException e) { e.printStackTrace(); } } ``` [More examples](https://github.com/mailersend/mailersend-java) ```ruby require "mailersend-ruby" # Intialize the SMS Webhooks class ms_sms_webhooks = Mailersend::SMSWebhooks.new # Add parameters ms_sms_webhooks.settings = { 'sms_number_id' => 'your-sms-number-id', 'name' => 'your-name', 'url' => 'https://your-url.com', 'events' => ['sms.sent', 'sms.delivered'] } puts ms_sms_webhooks.update_sms_webhook_route(sms_webhook_id: 'your-sms-webhook-id') ``` [More examples](https://github.com/mailersend/mailersend-ruby) ## Delete an SMS webhook [#delete-an-sms-webhook] Delete a SMS webhook using this `DELETE` request: ```http DELETE https://api.mailersend.com/v1/sms-webhooks/{sms_webhook_id} ``` ### Request Parameters \[!toc] [#request-parameters-toc-4] | URL Parameter | Type | Required | Limitations | Details | | ---------------- | -------- | -------- | ----------- | ------- | | `sms_webhook_id` | `string` | yes | | | ```php use MailerSend\MailerSend; $mailersend = new MailerSend(['api_key' => 'key']); $mailersend->smsWebhook->delete('sms_webhook_id'); ``` [More examples](https://github.com/mailersend/mailersend-php) ```javascript import 'dotenv/config'; import { MailerSend } from "mailersend"; const mailerSend = new MailerSend({ apiKey: process.env.API_KEY, }); mailerSend.sms.webhook.delete("sms_webhook_id") .then((response) => console.log(response.body)) .catch((error) => console.log(error.body)); ``` [More examples](https://github.com/mailersend/mailersend-nodejs) ```python from mailersend import MailerSendClient, SmsWebhooksBuilder ms = MailerSendClient() request = (SmsWebhooksBuilder() .sms_webhook_id("webhook-id") .build_delete_request()) response = ms.sms_webhooks.delete_sms_webhook(request) ``` [More examples](https://github.com/mailersend/mailersend-python) ```go package main import ( "context" "log" "time" "github.com/mailersend/mailersend-go" ) var APIKey = "Api Key Here" func main() { // Create an instance of the mailersend client ms := mailersend.NewMailersend(APIKey) ctx := context.Background() ctx, cancel := context.WithTimeout(ctx, 5*time.Second) defer cancel() _, err := ms.SmsWebhook.Delete(ctx, "sms-webhook-id") if err != nil { log.Fatal(err) } } ``` [More examples](https://github.com/mailersend/mailersend-go) ```java import com.mailersend.sdk.MailerSend; import com.mailersend.sdk.exceptions.MailerSendException; public void deleteSmsWebhook() { MailerSend ms = new MailerSend(); ms.setToken("mailersend token"); try { boolean result = ms.sms().webhooks().deleteWebhook("webhook id"); System.out.print(result); } catch (MailerSendException e) { e.printStackTrace(); } } ``` [More examples](https://github.com/mailersend/mailersend-java) ```ruby require "mailersend-ruby" # Intialize the SMS Webhooks class ms_sms_webhooks = Mailersend::SMSWebhooks.new # Add parameters ms_sms_webhooks.delete_sms_webhook_route(sms_webhook_id: 'your-sms-webhook-id') ``` [More examples](https://github.com/mailersend/mailersend-ruby) # Email Verification (/api/v1/verification/email) This endpoint allows you to verify emails through the MailerSend Email API. ## Verify an email [#verify-an-email] If you want to verify a single email, use this `POST` request: ```http POST https://api.mailersend.com/v1/email-verification/verify ``` #### Request parameters \[!toc] [#request-parameters-toc] | JSON parameter | Type | Required | Limitations | Details | | -------------- | -------- | -------- | ----------- | ------- | | `email` | `string` | yes | Max: `320` | | ```php use MailerSend\MailerSend; $mailersend = new MailerSend(['api_key' => 'key']); $mailersend->emailVerification->verifyEmail('test@example.com'); ``` [More examples](https://github.com/mailersend/mailersend-php) ```javascript import 'dotenv/config'; import { MailerSend } from "mailersend"; const mailerSend = new MailerSend({ apiKey: process.env.API_KEY, }); mailerSend.emailVerification.verifyEmail("test@example.com") .then((response) => console.log(response.body)) .catch((error) => console.log(error.body)); ``` [More examples](https://github.com/mailersend/mailersend-nodejs) ```go package main import ( "context" "os" "log" "time" "github.com/mailersend/mailersend-go" ) func main() { // Create an instance of the mailersend client ms := mailersend.NewMailersend(os.Getenv("MAILERSEND_API_KEY")) ctx := context.Background() ctx, cancel := context.WithTimeout(ctx, 5*time.Second) defer cancel() options := &mailersend.SingleEmailVerificationOptions{ Email: "john@doe.com" } _, _, err := ms.EmailVerification.VerifySingle(ctx, options) if err != nil { log.Fatal(err) } } ``` [More examples](https://github.com/mailersend/mailersend-go) ```ruby require "mailersend-ruby" ms_email_verification = Mailersend::EmailVerification.new ms_email_verification.verify_an_email(email: 'test@example.com') ``` [More examples](https://github.com/mailersend/mailersend-ruby) ### Responses [#responses] #### Valid [#valid] ```json { "status": "valid" } ``` #### Not enough credits error [#not-enough-credits-error] ```http Response Code: 402 Payment Required Response Headers: content-type: application/json ``` ```json { "message": "Not enough credits. Credits required: 1" } ``` ### Verification results [#verification-results] The possible outcome of an email validation can be grouped in 3 categories: **Valid**, **Risky** and **Do Not Send**. #### Valid [#valid-1] | Result | Description | | ------- | ---------------------- | | `valid` | Email is safe to send. | #### Risky [#risky] | Result | Description | | -------------- | --------------------------------------------------------------------------------------------------------------------------- | | `catch_all` | Recipient's mail server will accept emails to this address, but we cannot guarantee this email address belongs to a person. | | `mailbox_full` | Recipient’s inbox is full and may not be able to receive new emails. | | `role_based` | Email is role-based and may not be associated with a single, specific person but a group of people. | | `unknown` | We are unable to determine if the email is valid or not valid. | | `failed` | We could not perform the check due to timeouts. Verify the email by importing a list. | #### Do Not Send [#do-not-send] | Result | Description | | ------------------- | -------------------------------------------------------------------------------------------- | | `syntax_error` | The email address is not valid. | | `typo` | The email address has a typo. Correct the email address and retest. | | `mailbox_not_found` | Recipient’s inbox does not exist. | | `disposable` | The email address is a temporary inbox and should be removed from your lists. | | `mailbox_blocked` | The email address’ mailbox is blocked by its service provider due to poor sending practices. | *See - [Validation errors](/../../general#validation-errors)* ## Verify an email (Async) [#verify-an-email-async] Check a single email and receive the result asynchronously to avoid delays and timeouts, use this `POST` request: ```http POST https://api.mailersend.com/v1/email-verification/verify-async ``` #### Request parameters \[!toc] [#request-parameters-toc-1] | JSON parameter | Type | Required | Limitations | Details | | -------------- | -------- | -------- | ----------- | ------- | | `email` | `string` | yes | Max: `320` | | ```php use MailerSend\MailerSend; $mailersend = new MailerSend(['api_key' => 'key']); $mailersend->emailVerification->verifyAsync('test@example.com'); ``` [More examples](https://github.com/mailersend/mailersend-php) ```javascript import 'dotenv/config'; import { MailerSend } from "mailersend"; const mailerSend = new MailerSend({ apiKey: process.env.API_KEY, }); mailerSend.emailVerification.verifyEmailAsync("test@example.com") .then((response) => console.log(response.body)) .catch((error) => console.log(error.body)); ``` [More examples](https://github.com/mailersend/mailersend-nodejs) ### Responses [#responses-1] #### Valid [#valid-2] ```json { "id": "67c83bf24a5d02568029ee10", "address": "test@email.com", "status": "queued", "result": null, "error": null } ``` #### Not enough credits error [#not-enough-credits-error-1] ```http Response Code: 402 Payment Required Response Headers: content-type: application/json ``` ```json { "message": "Not enough credits. Credits required: 1" } ``` *See - [Validation errors](/../../general#validation-errors)* ## Get async email verification status [#get-async-email-verification-status] If you want to retrieve information about an async email verification status, use this `GET` request or [Receive via webhook](/api/v1/account/webhooks#available-events): ```http GET https://api.mailersend.com/v1/email-verification/verify-async/{email_verification_id} ``` #### Request parameters \[!toc] [#request-parameters-toc-2] | URL parameter | Type | Required | Limitations | Details | | ----------------------- | -------- | -------- | ----------- | ------- | | `email_verification_id` | `string` | yes | | | ### Check verification status [#check-verification-status] You can use this endpoint to check the verification status, with the following possible status: | Status | Description | | ----------- | -------------------------------------------------------- | | `queued` | The verification process is ongoing. | | `completed` | The verification process has finished successfully. | | `failed` | The verification process has run into an internal error. | ```php use MailerSend\MailerSend; $mailersend = new MailerSend(['api_key' => 'key']); $mailersend->emailVerification->getVerifyAsyncResult('email_verification_id'); ``` [More examples](https://github.com/mailersend/mailersend-php) ```javascript import 'dotenv/config'; import { MailerSend } from "mailersend"; const mailerSend = new MailerSend({ apiKey: process.env.API_KEY, }); mailerSend.emailVerification.getVerifyEmailAsyncStatus("email_verification_id") .then((response) => console.log(response.body)) .catch((error) => console.log(error.body)); ``` [More examples](https://github.com/mailersend/mailersend-nodejs) ### Responses [#responses-2] #### Valid [#valid-3] ```json { "id": "67c8863ce2fbd4fc8a7611cc", "address": "test@email.com", "status": "completed", "result": "unknown", "error": null } ``` ### Response fields [#response-fields] | Field | Type | Details | | --------- | -------------- | ---------------------------------------------------------------------- | | `id` | `string` | The unique identifier of the async verification. | | `address` | `string` | The email address that was verified. | | `status` | `string` | The current verification status (`queued`, `completed`, or `failed`). | | `result` | `string\|null` | The verification result once completed. `null` while still processing. | | `error` | `string\|null` | Error message when `status` is `failed`. `null` otherwise. | ## Get all lists [#get-all-lists] Get all email verifications lists with this `GET` request: ```http GET https://api.mailersend.com/v1/email-verification ``` #### Request parameters \[!toc] [#request-parameters-toc-3] | Query parameter | Type | Required | Limitations | Details | | --------------- | ----- | -------- | --------------------- | ------------- | | `page` | `int` | no | Min: `1` | | | `limit` | `int` | no | Min: `10`, Max: `100` | Default: `25` | ```php use MailerSend\MailerSend; $mailersend = new MailerSend(['api_key' => 'key']); $mailersend->emailVerification->getAll($page = 1, $limit = 10); ``` [More examples](https://github.com/mailersend/mailersend-php) ```javascript import 'dotenv/config'; import { MailerSend } from "mailersend"; const mailerSend = new MailerSend({ apiKey: process.env.API_KEY, }); mailerSend.emailVerification.list({ limit: 10, page: 1 }) .then((response) => console.log(response.body)) .catch((error) => console.log(error.body)); ``` [More examples](https://github.com/mailersend/mailersend-nodejs) ```python from mailersend import MailerSendClient, EmailVerificationBuilder ms = MailerSendClient() request = EmailVerificationBuilder().build_list_request() response = ms.email_verification.list_verification_lists(request) for verification_list in response.data: print(f"List: {verification_list.name}, Status: {verification_list.status}") ``` [More examples](https://github.com/mailersend/mailersend-python) ```go package main import ( "context" "log" "time" "github.com/mailersend/mailersend-go" ) var APIKey = "Api Key Here" func main() { // Create an instance of the mailersend client ms := mailersend.NewMailersend(APIKey) ctx := context.Background() ctx, cancel := context.WithTimeout(ctx, 5*time.Second) defer cancel() options := &mailersend.ListEmailVerificationOptions{ Page: 1, Limit: 25, } _, _, err := ms.EmailVerification.List(ctx, options) if err != nil { log.Fatal(err) } } ``` [More examples](https://github.com/mailersend/mailersend-go) ```java import com.mailersend.sdk.MailerSend; import com.mailersend.sdk.exceptions.MailerSendException; import com.mailsend.sdk.emailverification.EmailVerificationList; import com.mailsend.sdk.emailverification.EmailVerificationLists; public void getLists() { MailerSend ms = new MailerSend(); ms.setToken("mailersend token"); try { EmailVerificationLists lists = ms.emailVerification().getLists(); for (EmailVerificationList list : lists.lists) { System.out.println(list.id); System.out.println(list.name); } } catch (MailerSendException e) { e.printStackTrace(); } } ``` [More examples](https://github.com/mailersend/mailersend-java) ```ruby require "mailersend-ruby" ms_email_verification = Mailersend::EmailVerification.new ms_email_verification.list(page: 1, limit: 10) ``` [More examples](https://github.com/mailersend/mailersend-ruby) ### Responses [#responses-3] #### Valid [#valid-4] ```json { "data": [ { "id": "n3k6d1jr1eq50x4v", "name": "Example List", "total": 0, "verification_started": null, "verification_ended": null, "created_at": "2022-07-19T15:11:18.000000Z", "updated_at": "2022-07-19T15:11:18.000000Z", "status": { "name": "uploading", "count": 0 }, "source": "api", "statistics": { "valid": 0, "catch_all": 0, "mailbox_full": 0, "role_based": 0, "unknown": 0, "syntax_error": 0, "typo": 0, "mailbox_not_found": 0, "disposable": 0, "mailbox_blocked": 0, "failed": 0 } } ], "links": { "first": "http:\/\/localhost:8080\/api\/v1\/email-verification?page=1", "last": null, "prev": null, "next": null }, "meta": { "current_page": 1, "from": 1, "path": "http:\/\/localhost:8080\/api\/v1\/email-verification", "per_page": 25, "to": 1 } } ``` ## Get a single list [#get-a-single-list] If you want to retrieve information about a single email verification list, use this `GET` request: ```http GET https://api.mailersend.com/v1/email-verification/{email_verification_id} ``` #### Request parameters \[!toc] [#request-parameters-toc-4] | URL parameter | Type | Required | Limitations | Details | | ----------------------- | -------- | -------- | ----------- | ------- | | `email_verification_id` | `string` | yes | | | | Query parameter | Type | Required | Limitations | Details | | --------------- | --------- | -------- | -------------------- | ----------------------------------------------------------------------------- | | `detailed` | `boolean` | no | | When true, response includes an `emails` object with paginated email results. | | `page` | `integer` | no | Min: `1` | Only relevant when `detailed=true`. | | `limit` | `integer` | no | Min: `1`, Max: `100` | Only relevant when `detailed=true`. | ### Check verification status [#check-verification-status-1] You can use this endpoint to check the verification status, with the following possible status: | Status | Description | | ----------- | -------------------------------------------------------- | | `uploading` | The email addresses are being uploaded to our system. | | `created` | The list has been created and is ready to be verified. | | `verifying` | The verification process is ongoing. | | `verified` | The verification process has finished successfully. | | `failed` | The verification process has run into an internal error. | | `canceled` | The verification process was canceled. | | `paused` | The verification process is paused. | You can also check how many emails have been verified by consulting the `count` property of the status object. Example of status in the payload: ```json "status": { "name": "verifying", "count": 5 } ``` ```php use MailerSend\MailerSend; $mailersend = new MailerSend(['api_key' => 'key']); $mailersend->emailVerification->find('email_verification_id'); ``` [More examples](https://github.com/mailersend/mailersend-php) ```javascript import 'dotenv/config'; import { MailerSend } from "mailersend"; const mailerSend = new MailerSend({ apiKey: process.env.API_KEY, }); mailerSend.emailVerification.single("email_verification_id") .then((response) => console.log(response.body)) .catch((error) => console.log(error.body)); ``` [More examples](https://github.com/mailersend/mailersend-nodejs) ```python from mailersend import MailerSendClient, EmailVerificationBuilder ms = MailerSendClient() request = (EmailVerificationBuilder() .verification_list_id("list-id") .build_get_request()) response = ms.email_verification.get_verification_list(request) print(f"List name: {response.name}") ``` [More examples](https://github.com/mailersend/mailersend-python) ```go package main import ( "context" "log" "time" "github.com/mailersend/mailersend-go" ) var APIKey = "Api Key Here" func main() { // Create an instance of the mailersend client ms := mailersend.NewMailersend(APIKey) ctx := context.Background() ctx, cancel := context.WithTimeout(ctx, 5*time.Second) defer cancel() _, _, err := ms.EmailVerification.Get(ctx, "email-verification-id") if err != nil { log.Fatal(err) } } ``` [More examples](https://github.com/mailersend/mailersend-go) ```java import com.mailersend.sdk.MailerSend; import com.mailersend.sdk.exceptions.MailerSendException; import com.mailsend.sdk.emailverification.EmailVerificationList; public void getList() { MailerSend ms = new MailerSend(); ms.setToken("mailersend token"); try { EmailVerificationList list = ms.emailVerification().getList("list id"); System.out.println(list.name); } catch (MailerSendException e) { e.printStackTrace(); } } ``` [More examples](https://github.com/mailersend/mailersend-java) ```ruby require "mailersend-ruby" ms_email_verification = Mailersend::EmailVerification.new ms_email_verification.get_single_list(email_verification_id: 'your-email-verification-id') ``` [More examples](https://github.com/mailersend/mailersend-ruby) ### Responses [#responses-4] #### Valid [#valid-5] ```json { "data": { "id": "n3k6d1jr1eq50x4v", "name": "Example List", "total": 0, "verification_started": null, "verification_ended": null, "created_at": "2022-07-19T15:11:18.000000Z", "updated_at": "2022-07-19T15:11:18.000000Z", "status": { "name": "uploading", "count": 0 }, "source": "api", "statistics": { "valid": 0, "catch_all": 0, "mailbox_full": 0, "role_based": 0, "unknown": 0, "syntax_error": 0, "typo": 0, "mailbox_not_found": 0, "disposable": 0, "mailbox_blocked": 0, "failed": 0 } } } ``` #### Valid with detailed=true [#valid-with-detailedtrue] ```json { "data": { "id": "n3k6d1jr1eq50x4v", "name": "Example List", "total": 2, "verification_started": "2022-07-19T15:24:19.000000Z", "verification_ended": "2022-07-19T15:30:00.000000Z", "created_at": "2022-07-19T15:11:18.000000Z", "updated_at": "2022-07-19T15:30:00.000000Z", "status": { "name": "verified", "count": 2 }, "source": "api", "statistics": { "valid": 1, "catch_all": 0, "mailbox_full": 0, "role_based": 0, "unknown": 0, "syntax_error": 0, "typo": 1, "mailbox_not_found": 0, "disposable": 0, "mailbox_blocked": 0, "failed": 0 }, "emails": { "data": [ { "address": "example1@mail.com", "result": "typo" }, { "address": "example2@gmail.com", "result": "valid" } ], "pagination": { "current_page": 1, "per_page": 25, "total": 2, "last_page": 1, "from": 1, "to": 2 }, "links": { "first": "https://api.mailersend.com/v1/email-verification/n3k6d1jr1eq50x4v?detailed=true&page=1", "last": "https://api.mailersend.com/v1/email-verification/n3k6d1jr1eq50x4v?detailed=true&page=1", "prev": null, "next": null } } } } ``` #### Error [#error] ```http Response Code: 422 Unprocessable Entity ``` *See - [Validation errors](/../../general#validation-errors)* ## Create a list [#create-a-list] If you want to add a new email verification list, use this `POST` request: ```http POST https://api.mailersend.com/v1/email-verification ``` ### Request body \[!toc] [#request-body-toc] ```json { "name": "Example List", "emails": [ "example1@mail.com", "example2@mail.com" ] } ``` ```php use MailerSend\MailerSend; use MailerSend\Helpers\Builder\EmailVerificationParams; $mailersend = new MailerSend(['api_key' => 'key']); $emailVerificationParams = (new EmailVerificationParams('file.csv')) ->setEmailAddresses(['test@mail.com']); $mailersend->emailVerification->create($emailVerificationParams); // Optionally start verification immediately or attach to an existing list $emailVerificationParams = (new EmailVerificationParams('file.csv')) ->setEmailAddresses(['test@mail.com']) ->setListId('existing_list_id') ->setVerify(true); $mailersend->emailVerification->create($emailVerificationParams); ``` [More examples](https://github.com/mailersend/mailersend-php) ```javascript import 'dotenv/config'; import { EmailVerification, MailerSend } from "mailersend"; const mailerSend = new MailerSend({ apiKey: process.env.API_KEY, }); const emailVerification = new EmailVerification() .setName("List example") .setEmails([ "info@mailersend.com", "test@mailersend.com" ]); mailerSend.emailVerification.create(emailVerification) .then((response) => console.log(response.body)) .catch((error) => console.log(error.body)); ``` [More examples](https://github.com/mailersend/mailersend-nodejs) ```python from mailersend import MailerSendClient, EmailVerificationBuilder ms = MailerSendClient() request = (EmailVerificationBuilder() .name("My Verification List") .emails(["test1@example.com", "test2@example.com"]) .build_create_request()) response = ms.email_verification.create_verification_list(request) print(f"Created list with ID: {response.id}") ``` [More examples](https://github.com/mailersend/mailersend-python) ```go package main import ( "context" "log" "time" "github.com/mailersend/mailersend-go" ) var APIKey = "Api Key Here" func main() { // Create an instance of the mailersend client ms := mailersend.NewMailersend(APIKey) ctx := context.Background() ctx, cancel := context.WithTimeout(ctx, 5*time.Second) defer cancel() options := &mailersend.CreateEmailVerificationOptions{ Name: "Email Verification List ", Emails: []string{"your@client.com", "your@client.eu"}, } _, _, err := ms.EmailVerification.Create(ctx, options) if err != nil { log.Fatal(err) } } ``` [More examples](https://github.com/mailersend/mailersend-go) ```java import com.mailersend.sdk.MailerSend; import com.mailersend.sdk.exceptions.MailerSendException; import com.mailsend.sdk.emailverification.EmailVerificationList; public void createList() { MailerSend ms = new MailerSend(); ms.setToken("mailersend token"); try { EmailVerificationList list = ms.emailVerification().builder() .name("Test email verification") .addEmail("info@example.com") .addEmail("info1@example.com") .addEmail("info2@example.com") .create(); System.out.println(list.id); } catch (MailerSendException e) { e.printStackTrace(); } } ``` [More examples](https://github.com/mailersend/mailersend-java) ```ruby require "mailersend-ruby" ms_email_verification = Mailersend::EmailVerification.new ms_email_verification.create_a_list(name: "name-your-list", emails: ["example@email.com"]) ``` [More examples](https://github.com/mailersend/mailersend-ruby) ### Request Parameters \[!toc] [#request-parameters-toc-5] *JSON parameters are provided in dot notation* | JSON Parameter | Type | Required | Limitations | Details | | -------------- | --------- | -------------------------- | ---------------------- | -------------------------------------------------------- | | `name` | `string` | required\_without:list\_id | Max: `191` | | | `list_id` | `string` | no | | ID of an existing verification list to append emails to. | | `emails` | `array` | yes | Min: `1`, Max: `10000` | | | `emails.*` | `string` | yes | Max: `320` | | | `verify` | `boolean` | no | | If true, immediately starts verification after upload. | ### Responses [#responses-5] | Response Key | Type | Details | | ------------ | ------ | --------------------------------- | | data | object | EmailVerification object created. | #### Valid [#valid-6] ```http Response Code: 201 CREATED Response Headers: content-type: application/json ``` ```json { "data": { "id": "n3k6d1jr1eq50x4v", "name": "Example List", "total": 0, "verification_started": null, "verification_ended": null, "created_at": "2022-07-19T15:11:18.000000Z", "updated_at": "2022-07-19T15:11:18.000000Z", "status": { "name": "uploading", "count": 0 }, "source": "api", "statistics": { "valid": 0, "catch_all": 0, "mailbox_full": 0, "role_based": 0, "unknown": 0, "syntax_error": 0, "typo": 0, "mailbox_not_found": 0, "disposable": 0, "mailbox_blocked": 0, "failed": 0 } } } ``` #### Invalid [#invalid] ```http Response Code: 422 Unprocessable Entity ``` *See - [Validation errors](/../../general#validation-errors)* ## Verify a list [#verify-a-list] If you want to verify an email verification list, use this `GET` request: ```http GET https://api.mailersend.com/v1/email-verification/{email_verification_id}/verify ``` #### Request parameters \[!toc] [#request-parameters-toc-6] | URL parameter | Type | Required | Limitations | Details | | ----------------------- | -------- | -------- | ----------- | ------- | | `email_verification_id` | `string` | yes | | | > **Note:** Sending this request while an email list is already being verified (status is `verifying`) will not queue another verification. Also, sending this request when the email list is verified (status is `verified`) will trigger a new verification. ```php use MailerSend\MailerSend; $mailersend = new MailerSend(['api_key' => 'key']); $mailersend->emailVerification->verify('email_verification_id'); ``` [More examples](https://github.com/mailersend/mailersend-php) ```javascript import 'dotenv/config'; import { MailerSend } from "mailersend"; const mailerSend = new MailerSend({ apiKey: process.env.API_KEY, }); mailerSend.emailVerification.verifyList("email_verification_id") .then((response) => console.log(response.body)) .catch((error) => console.log(error.body)); ``` [More examples](https://github.com/mailersend/mailersend-nodejs) ```python from mailersend import MailerSendClient, EmailVerificationBuilder ms = MailerSendClient() request = (EmailVerificationBuilder() .verification_list_id("list-id") .build_verify_request()) response = ms.email_verification.verify_list(request) print(f"Verification started: {response.message}") ``` [More examples](https://github.com/mailersend/mailersend-python) ```go package main import ( "context" "log" "time" "github.com/mailersend/mailersend-go" ) var APIKey = "Api Key Here" func main() { // Create an instance of the mailersend client ms := mailersend.NewMailersend(APIKey) ctx := context.Background() ctx, cancel := context.WithTimeout(ctx, 5*time.Second) defer cancel() _, _, err := ms.EmailVerification.Verify(ctx, "email-verification-id") if err != nil { log.Fatal(err) } } ``` [More examples](https://github.com/mailersend/mailersend-go) ```java import com.mailersend.sdk.MailerSend; import com.mailersend.sdk.exceptions.MailerSendException; import com.mailsend.sdk.emailverification.EmailVerificationList; public void verifyList() { MailerSend ms = new MailerSend(); ms.setToken("mailersend token"); try { EmailVerificationList list = ms.emailVerification().verifyList("list id"); System.out.println(list.status.name); } catch (MailerSendException e) { e.printStackTrace(); } } ``` [More examples](https://github.com/mailersend/mailersend-java) ```ruby require "mailersend-ruby" ms_email_verification = Mailersend::EmailVerification.new ms_email_verification.verify_a_list(email_verification_id: 'your-email-verification-id') ``` [More examples](https://github.com/mailersend/mailersend-ruby) ### Responses [#responses-6] #### Valid [#valid-7] ```json { "data": { "id": "n3k6d1jr1eq50x4v", "name": "Example List", "total": 2, "verification_started": "2022-07-19T15:24:19.000000Z", "verification_ended": null, "created_at": "2022-07-19T15:11:18.000000Z", "updated_at": "2022-07-19T15:24:19.000000Z", "status": { "name": "verifying", "count": 0 }, "source": "api", "statistics": { "valid": 0, "catch_all": 0, "mailbox_full": 0, "role_based": 0, "unknown": 0, "syntax_error": 0, "typo": 0, "mailbox_not_found": 0, "disposable": 0, "mailbox_blocked": 0, "failed": 0 } } } ``` #### Still uploading error [#still-uploading-error] ```http Response Code: 403 Forbidden Response Headers: content-type: application/json ``` ```json { "message": "The email addresses are still being uploaded, wait for the upload to finish to continue." } ``` #### Not enough credits error [#not-enough-credits-error-2] ```http Response Code: 403 Forbidden Response Headers: content-type: application/json ``` ```json { "message": "You do not have enough credits to perform this operation." } ``` *See - [Validation errors](/../../general#validation-errors)* ## Get list results [#get-list-results] If you want to get the result for each individual email of an email verification list, use this `GET` request: ```http GET https://api.mailersend.com/v1/email-verification/{email_verification_id}/results ``` #### Request parameters \[!toc] [#request-parameters-toc-7] | URL parameter | Type | Required | Limitations | Details | | ----------------------- | -------- | -------- | ----------- | ------- | | `email_verification_id` | `string` | yes | | | | Query parameter | Type | Required | Limitations | Details | | | --------------- | -------- | -------- | ----------------------------------------------------------------- | ------------- | - | | `page` | `int` | no | Min: `1` | | | | `limit` | `int` | no | Min: `10`, Max: `500` | Default: `25` | | | `results` | `array` | no | | | | | `results.*` | `string` | yes | Must be one of the [verification results](#verification-results). | | | ```php use MailerSend\MailerSend; use MailerSend\Helpers\Builder\EmailVerificationParams; $mailersend = new MailerSend(['api_key' => 'key']); $mailersend->emailVerification->getResults( $emailVerificationId = 'email_verification_id', $page = 1, $limit = 10, $results = [ EmailVerificationParams::TYPO, EmailVerificationParams::CATCH_ALL, ], ); ``` [More examples](https://github.com/mailersend/mailersend-php) ```javascript import 'dotenv/config'; import { EmailVerificationResultType, MailerSend } from "mailersend"; const mailerSend = new MailerSend({ apiKey: process.env.API_KEY, }); mailerSend.emailVerification.getListResult("email_verification_id",{ limit: 10, page: 1, results: [EmailVerificationResultType.CATCH_ALL, EmailVerificationResultType.DISPOSABLE] }) .then((response) => console.log(response.body)) .catch((error) => console.log(error.body)); ``` [More examples](https://github.com/mailersend/mailersend-nodejs) ```python from mailersend import MailerSendClient, EmailVerificationBuilder ms = MailerSendClient() request = (EmailVerificationBuilder() .verification_list_id("list-id") .build_results_request()) response = ms.email_verification.get_verification_results(request) for result in response.data: print(f"Email: {result.email}, Status: {result.status}") ``` [More examples](https://github.com/mailersend/mailersend-python) ```go package main import ( "context" "log" "time" "github.com/mailersend/mailersend-go" ) var APIKey = "Api Key Here" func main() { // Create an instance of the mailersend client ms := mailersend.NewMailersend(APIKey) ctx := context.Background() ctx, cancel := context.WithTimeout(ctx, 5*time.Second) defer cancel() options := &mailersend.GetEmailVerificationOptions{ EmailVerificationId: "email-verification-id", Page: 1, Limit: 25, } _, _, err := ms.EmailVerification.GetResults(ctx, options) if err != nil { log.Fatal(err) } } ``` [More examples](https://github.com/mailersend/mailersend-go) ```java import com.mailersend.sdk.MailerSend; import com.mailersend.sdk.exceptions.MailerSendException; import com.mailsend.sdk.emailverification.ListVerificationResults; import com.mailsend.sdk.emailverification.VerificationResult; public void verifyList() { MailerSend ms = new MailerSend(); ms.setToken("mailersend token"); try { ListVerificationResults results = ms.emailVerification().verificationResults("list id"); for (VerificationResult result : results.results) { System.out.println(result.address); System.out.println(result.result); } } catch (MailerSendException e) { e.printStackTrace(); } } ``` [More examples](https://github.com/mailersend/mailersend-java) ```ruby require "mailersend-ruby" ms_email_verification = Mailersend::EmailVerification.new ms_email_verification.get_list_results(email_verification_id: 'your-email-verification-id') ``` [More examples](https://github.com/mailersend/mailersend-ruby) ### Responses [#responses-7] #### Valid [#valid-8] ```json { "data": [ { "address": "example1@mail.com", "result": "typo" }, { "address": "example2@gmail.com", "result": "mailbox_not_found" } ], "links": { "first": "http:\/\/localhost:8080\/api\/v1\/email-verification\/n3k6d1jr1eq50x4v\/results?1=1", "last": null, "prev": null, "next": null }, "meta": { "current_page": 1, "from": 1, "path": "http:\/\/localhost:8080\/api\/v1\/email-verification\/n3k6d1jr1eq50x4v\/results", "per_page": 25, "to": 2 } } ``` #### Error [#error-1] ```http Response Code: 422 Unprocessable Entity ``` *See - [Validation errors](/../../general#validation-errors)* ## Verification results [#verification-results-1] The possible outcome of an email validation can be grouped in 3 categories: **Valid**, **Risky** and **Do Not Send**. ### Valid [#valid-9] | Result | Description | | ------- | ---------------------- | | `valid` | Email is safe to send. | ### Risky [#risky-1] | Result | Description | | -------------- | --------------------------------------------------------------------------------------------------------------------------- | | `catch_all` | Recipient’s mail server will accept emails to this address, but we cannot guarantee this email address belongs to a person. | | `mailbox_full` | Recipient’s inbox is full and may not be able to receive new emails. | | `role_based` | Email is role-based and may not be associated with a single, specific person but a group of people. | | `unknown` | We are unable to determine if the email is valid or not valid. | | `failed` | We could not perform the check due to timeouts. Verify the email by importing a list. | ### Do Not Send [#do-not-send-1] | Result | Description | | ------------------- | -------------------------------------------------------------------------------------------- | | `syntax_error` | The email address is not valid. | | `typo` | The email address has a typo. Correct the email address and retest. | | `mailbox_not_found` | Recipient’s inbox does not exist. | | `disposable` | The email address is a temporary inbox and should be removed from your lists. | | `mailbox_blocked` | The email address’ mailbox is blocked by its service provider due to poor sending practices. | # Activity (/api/v1/email/activity) Get information about your domain activity, including your sent emails and whether they were received by the recipient. You can also see whether they opened or clicked on any of the email content. ## Get a list of activities [#get-a-list-of-activities] With this endpoint, you can retrieve every single data point of the activity that happened for a specific domain. Obtain a list of activities with the following `GET` request: ```http GET https://api.mailersend.com/v1/activity/{domain_id} ``` #### Request parameters \[!toc] [#request-parameters-toc] | URL parameter | Type | Required | Limitations | Details | | ------------- | -------- | -------- | ----------- | ------- | | `domain_id` | `string` | yes | | | | Query parameter | Type | Required | Limitations | Details | | --------------- | ------------- | -------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------ | | `page` | `int` | no | Min: `1`, Max: `1000` | To reach older activity beyond the last page, narrow `date_from` and `date_to` | | `limit` | `int` | no | Min: `10`, Max: `100` | Default: `25` | | `date_from` | `int\|string` | yes | Timestamp is assumed to be `UTC`. Must be lower than `date_to`. | Unix timestamp: `1443651141` or datetime: `2015-10-01 00:00:00` | | `date_to` | `int\|string` | yes | Timestamp is assumed to be `UTC`. Must be higher than `date_from`. The allowed timeframe depends on your plan's data retention limit (1–30 days). | Unix timestamp: `1443651141` or datetime: `2015-10-01 23:59:59` | | `event[]` | `string[]` | no | Possible types: `queued`,`sent`,`delivered`,`soft_bounced`,
`hard_bounced`,`deferred`, `opened`,`opened_unique`,`clicked`,`clicked_unique`,
`unsubscribed`,`spam_complaints`,`survey_opened`, `survey_submitted`, `suppressed` | `deferred` and `suppressed` are available on the Starter plan and above. | ```php use MailerSend\MailerSend; use MailerSend\Helpers\Builder\ActivityParams; $mailersend = new MailerSend(['api_key' => 'key']); $activityParams = (new ActivityParams()) ->setPage(3) ->setLimit(15) ->setDateFrom(1623073576) ->setDateTo(1623074976) ->setEvent(['sent', 'delivered']); $mailersend->activity->getAll('domainId', $activityParams); ``` [More examples](https://github.com/mailersend/mailersend-php) ```javascript import 'dotenv/config'; import { MailerSend, ActivityEventType } from "mailersend"; const mailerSend = new MailerSend({ apiKey: process.env.API_KEY, }); const queryParams = { limit: 10, // Min: 10, Max: 100, Default: 25 page: 2, date_from: 1443651141, // Unix timestamp date_to: 1443651141, // Unix timestamp event: [ActivityEventType.SENT, ActivityEventType.SOFT_BOUNCED] } mailerSend.email.activity.domain("domain_id", queryParams) .then((response) => console.log(response.body)) .catch((error) => console.log(error)); ``` [More examples](https://github.com/mailersend/mailersend-nodejs) ```python from mailersend import MailerSendClient, ActivityBuilder from datetime import datetime, timedelta ms = MailerSendClient() # Get activities from last 7 days (maximum allowed timeframe) date_from = int((datetime.now() - timedelta(days=7)).timestamp()) date_to = int(datetime.now().timestamp()) request = (ActivityBuilder() .domain_id("domain-id") .date_from(date_from) .date_to(date_to) .page(1) .limit(25) .build_list_request()) response = ms.activities.get(request) ``` [More examples](https://github.com/mailersend/mailersend-python) ```go package main import ( "context" "log" "time" "github.com/mailersend/mailersend-go" ) var APIKey = "Api Key Here" func main() { // Create an instance of the mailersend client ms := mailersend.NewMailersend(APIKey) ctx := context.Background() ctx, cancel := context.WithTimeout(ctx, 5*time.Second) defer cancel() from := time.Now().Add(-24 * time.Hour).Unix() to := time.Now().Unix() domainID := "domain-id" options := &mailersend.ActivityOptions{ DomainID: domainID, DateFrom: from, DateTo: to, } _, _, err := ms.Activity.List(ctx, options) if err != nil { log.Fatal(err) } } ``` [More examples](https://github.com/mailersend/mailersend-go) ```java import com.mailersend.sdk.ActivitiesList; import com.mailersend.sdk.MailerSend; import com.mailersend.sdk.MailerSendResponse; import com.mailersend.sdk.exceptions.MailerSendException; public void getActivities() { MailerSend ms = new MailerSend(); ms.setToken("Your API token"); try { ActivitiesList activities = ms.activities().getActivities("domain id"); for (Activity activity : activities.activities) { System.out.println(activity.id); System.out.println(activity.createdAt.toString()); System.out.println(activity.email.from); System.out.println(activity.email.subject); System.out.println(activitiy.email.recipient.email); } } catch (MailerSendException e) { e.printStackTrace(); } } ``` [More examples](https://github.com/mailersend/mailersend-java) ```ruby require "mailersend-ruby" ms_activity = Mailersend::Activity.new ms_activity.get(domain_id: "xxx2241ll", page: 3, limit: 5, date_from: 1620643567, date_to: 1623321967) ``` [More examples](https://github.com/mailersend/mailersend-ruby) ### Responses [#responses] The `deferred` and `suppressed` activity types are available on the Starter plan and above. On lower plans, filtering by these types in `event[]` returns a validation error and no such activities are included in the response. When an activity has the type `suppressed`, the response object includes an additional `suppression_reason` field explaining why the recipient was suppressed. The field is only present for `suppressed` activities. Possible values: | Value | Description | | ----------------- | -------------- | | `on_hold` | On hold | | `hard_bounced` | Hard bounced | | `unsubscribed` | Unsubscribed | | `spam_complained` | Spam complaint | | `blocklisted` | Blocklisted | #### Valid [#valid] ```http Response Code: 200 OK Response Headers: content-type: application/json ``` ```json { "data" : [ { "id": "5ee0b166b251345e407c9207", "created_at": "2020-06-04 12:00:00", "updated_at": "2020-06-04 12:00:00", "type": "clicked", "email": { "id": "5ee0b166b251345e407c9201", "from": "colleen.wiza@example.net", "subject": "Magni aperiam sunt nam omnis.", "text": "Lorem ipsum dolor sit amet, consectetuer adipiscin", "html": " Analytics data is stored for up to 6 months. ## Activity data by date [#activity-data-by-date] {/* #### Limitations - Stats are cached for **60s** _TBD_. - Rate limited to **60** requests per hour TBD. */} Retrieve data grouped by date, based on activity, with this `GET` request: ```http GET https://api.mailersend.com/v1/analytics/date ``` #### Request parameters \[!toc] [#request-parameters-toc] | Query parameter | Type | Required | Limitations | Details | | ---------------- | ---------- | -------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------- | | `domain_id` | `string` | no | | | | `recipient_id[]` | `string` | no | Max number of recipients: *50* *TBD* | *Not yet implemented* | | `date_from` | `int` | yes | Timestamp is assumed to be `UTC`. Must be lower than `date_to`. | Format: `1443651141` | | `date_to` | `int` | yes | Timestamp is assumed to be `UTC`. Must be higher than `date_from`. | Format: `1443661141` | | `group_by` | `string` | no | Possible options: `days`, `weeks`, `months`, `years` | Default: `days` | | `tags[]` | `string[]` | no | | | | `event[]` | `string[]` | no | Possible types: `queued`,`sent`,`delivered`,`soft_bounced`,
`hard_bounced`,`deferred`,`opened`,`clicked`,`unsubscribed`,
`spam_complaints`,`survey_opened`, `survey_submitted`,`opened_unique`,`clicked_unique` | | ```php use MailerSend\MailerSend; use MailerSend\Helpers\Builder\ActivityAnalyticsParams; use MailerSend\Common\Constants; $mailersend = new MailerSend(['api_key' => 'key']); $activityAnalyticsParams = (new ActivityAnalyticsParams(100, 101)) ->setDomainId('domain_id') ->setGroupBy(Constants::GROUP_BY_DAYS) ->setTags(['tag']) ->setEvent(['sent', 'delivered']); $mailersend->analytics->activityDataByDate($activityAnalyticsParams); ``` [More examples](https://github.com/mailersend/mailersend-php) ```javascript import 'dotenv/config'; import { ActivityEventType, MailerSend } from "mailersend"; const mailerSend = new MailerSend({ apiKey: process.env.API_KEY, }); mailerSend.email.analytics.byDate({ date_from: 1443651141, date_to: 2443651141, event: [ActivityEventType.CLICKED, ActivityEventType.OPENED], }).then(response => { console.log(response.body); }).catch(error => { console.log(error.body); }); ``` [More examples](https://github.com/mailersend/mailersend-nodejs) ```python from mailersend import MailerSendClient, AnalyticsBuilder from datetime import datetime, timedelta ms = MailerSendClient() date_from = int((datetime.now() - timedelta(days=30)).timestamp()) date_to = int(datetime.now().timestamp()) request = (AnalyticsBuilder() .date_from(date_from) .date_to(date_to) .events("sent", "delivered", "opened") .domain_id("domain-id") .group_by("days") .build()) response = ms.analytics.get_activity_by_date(request) for stat in response.data: print(f"Date: {stat.date}, Sent: {stat.sent}, Delivered: {stat.delivered}") ``` [More examples](https://github.com/mailersend/mailersend-python) ```go package main import ( "context" "log" "time" "github.com/mailersend/mailersend-go" ) var APIKey = "Api Key Here" func main() { // Create an instance of the mailersend client ms := mailersend.NewMailersend(APIKey) ctx := context.Background() ctx, cancel := context.WithTimeout(ctx, 5*time.Second) defer cancel() from := time.Now().Add(-24 * time.Hour).Unix() to := time.Now().Unix() domainID := "domain-id" events := []string{"sent", "queued", "delivered"} options := &mailersend.AnalyticsOptions{ DomainID: domainID, DateFrom: from, DateTo: to, Event: events, } _, _, err := ms.Analytics.GetActivityByDate(ctx, options) if err != nil { log.Fatal(err) } } ``` [More examples](https://github.com/mailersend/mailersend-go) ```java import java.util.Date; import com.mailersend.sdk.MailerSend; import com.mailersend.sdk.analytics.AnalyticsByDate; import com.mailersend.sdk.analytics.AnalyticsByDateList; import com.mailersend.sdk.analytics.AnalyticsList; import com.mailersend.sdk.analytics.AnalyticsStatistic; import com.mailersend.sdk.exceptions.MailerSendException; import com.mailersend.sdk.util.EventTypes; public void getAnalyticsByDate() { MailerSend ms = new MailerSend(); ms.setToken(TestHelper.validToken); try { Date dateFrom = new Date(); // set your from date normally AnalyticsByDateList list = ms.analytics() .dateFrom(dateFrom) .dateTo(new Date()) .domainId(TestHelper.domainId) .getByDate(new String[] {EventTypes.DELIVERED, EventTypes.OPENED, EventTypes.CLICKED}); System.out.println("\n\nAnalytics by date for domain:"); for (AnalyticsByDate dayStat : list.statistics) { System.out.println(dayStat.statDate.toString()); System.out.println(dayStat.delivered); System.out.println(dayStat.opened); System.out.println(dayStat.clicked); } } catch (MailerSendException e) { e.printStackTrace(); } } ``` [More examples](https://github.com/mailersend/mailersend-java) ```ruby require "mailersend-ruby" ms_analytics = Mailersend::Analytics.new ms_analytics.date(date_from: 1620643567, date_to: 1623321967, events: %w[sent queued]) ``` [More examples](https://github.com/mailersend/mailersend-ruby) ### Responses [#responses] | Response key | Type | Details | | ---------------------- | ----------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `data.stats.*.date` | `timestamp` | The `date` will be at the start of the `group_by` unit (so start of day/week/month/year). Every date in the date range will be present, even if there are no events for that day. | | `data.stats.*.[event]` | `int` | Every queried `event[]` will be present in the response with a default value - `0` | #### Valid [#valid] ```http Response Code: 200 OK Response Headers: content-type: application/json ``` ```json { "data": { "date_from": "1591228800", "date_to": "1591401599", "group_by": "days", "stats": [ { "date": "1591228800", "queued": 0, "sent": 0, "delivered": 0, "opened": 0, "clicked": 0, "soft_bounced": 0, "hard_bounced": 0, "unsubscribed": 0, "spam_complaints": 0, "opened_unique": 0, "clicked_unique": 0, "survey_opened":0, "survey_submitted":0 }, { "date": "1591315200", "queued": 0, "sent": 0, "delivered": 0, "opened": 0, "clicked": 0, "soft_bounced": 0, "hard_bounced": 0, "unsubscribed": 0, "spam_complaints": 0, "opened_unique": 0, "clicked_unique": 0, "survey_opened":0, "survey_submitted":0 } ] } } ``` #### Error [#error] ```http Response Code: 422 Unprocessable Entity ``` *See - [Validation errors](/../../general#validation-errors)* ## Opens by country [#opens-by-country] {/* #### Limitations - Stats are cached for **60s** _TBD_. - Rate limited to **60** requests per hour TBD. */} Retrieve data grouped by country, based on activity, with this `GET` request: ```http GET https://api.mailersend.com/v1/analytics/country ``` #### Request parameters \[!toc] [#request-parameters-toc-1] | Query parameter | Type | Required | Limitations | Details | | ---------------- | ---------- | -------- | ------------------------------------------------------------------ | --------------------- | | `domain_id` | `string` | no | | | | `recipient_id[]` | `string` | no | Max number of recipients: *50* *TBD* | *Not yet implemented* | | `date_from` | `int` | yes | Timestamp is assumed to be `UTC`. Must be lower than `date_to`. | Format: `1443651141` | | `date_to` | `int` | yes | Timestamp is assumed to be `UTC`. Must be higher than `date_from`. | Format: `1443661141` | | `tags[]` | `string[]` | no | | | ```php use MailerSend\MailerSend; use MailerSend\Helpers\Builder\OpensAnalyticsParams; $mailersend = new MailerSend(['api_key' => 'key']); $opensAnalyticsParams = (new OpensAnalyticsParams(100, 101)) ->setDomainId('domain_id') ->setTags(['tag']); $mailersend->analytics->opensByCountry($opensAnalyticsParams); ``` [More examples](https://github.com/mailersend/mailersend-php) ```javascript import 'dotenv/config'; import { MailerSend } from "mailersend"; const mailerSend = new MailerSend({ apiKey: process.env.API_KEY, }); mailerSend.email.analytics.byCountry({ date_from: 1443651141, date_to: 2443651141, }).then(response => { console.log(response.body); }).catch(error => { console.log(error.body); }); ``` [More examples](https://github.com/mailersend/mailersend-nodejs) ```python from mailersend import MailerSendClient, AnalyticsBuilder from datetime import datetime, timedelta ms = MailerSendClient() date_from = int((datetime.now() - timedelta(days=30)).timestamp()) date_to = int(datetime.now().timestamp()) request = (AnalyticsBuilder() .date_from(date_from) .date_to(date_to) .domain_id("domain-id") .build()) response = ms.analytics.get_opens_by_country(request) ``` [More examples](https://github.com/mailersend/mailersend-python) ```go package main import ( "context" "log" "time" "github.com/mailersend/mailersend-go" ) var APIKey = "Api Key Here" func main() { // Create an instance of the mailersend client ms := mailersend.NewMailersend(APIKey) ctx := context.Background() ctx, cancel := context.WithTimeout(ctx, 5*time.Second) defer cancel() from := time.Now().Add(-24 * time.Hour).Unix() to := time.Now().Unix() domainID := "domain-id" options := &mailersend.AnalyticsOptions{ DomainID: domainID, DateFrom: from, DateTo: to, } _, _, err := ms.Analytics.GetOpensByCountry(ctx, options) if err != nil { log.Fatal(err) } } ``` [More examples](https://github.com/mailersend/mailersend-go) ```java import java.util.Date; import com.mailersend.sdk.MailerSend; import com.mailersend.sdk.analytics.AnalyticsList; import com.mailersend.sdk.analytics.AnalyticsStatistic; import com.mailersend.sdk.exceptions.MailerSendException; public void getOpensByCountry() { MailerSend ms = new MailerSend(); ms.setToken(TestHelper.validToken); try { Date dateFrom = new Date(); // set your from date normally AnalyticsList list = ms.analytics() .dateFrom(dateFrom) .dateTo(new Date()) .domainId(TestHelper.domainId) .getOpensByCountry(); System.out.println("\n\nOpens by country:"); for (AnalyticsStatistic stat : list.statistics) { System.out.println(stat.name + " - " + stat.count); } } catch (MailerSendException e) { e.printStackTrace(); } } ``` [More examples](https://github.com/mailersend/mailersend-java) ```ruby require "mailersend-ruby" ms_analytics = Mailersend::Analytics.new ms_analytics.country(date_from: 1620643567, date_to: 1623321967) ``` [More examples](https://github.com/mailersend/mailersend-ruby) ### Responses [#responses-1] | Response key | Type | Details | | -------------------- | -------- | ----------------------------------------------------------------------------------------------------------- | | `data.stats.*.name` | `string` | [2 Letter code of the country.](https://www.iban.com/country-codes) Will not be present if there's no data. | | `data.stats.*.count` | `int` | | #### Valid [#valid-1] ```http Response Code: 200 OK Response Headers: content-type: application/json ``` ```json { "data": { "date_from": 1591228800, "date_to": 1591401599, "stats": [ { "name": "LT", "count": 2 } ] } } ``` #### Error [#error-1] ```http Response Code: 422 Unprocessable Entity ``` *See - [Validation errors](/../../general#validation-errors)* ## Opens by user-agent name [#opens-by-user-agent-name] {/* #### Limitations - Stats are cached for **60s** _TBD_. - Rate limited to **60** requests per hour TBD. */} Retrieve data grouped by user-agent name (browser and operating system), based on activity, with this `GET` request: ```http GET https://api.mailersend.com/v1/analytics/ua-name ``` #### Request parameters \[!toc] [#request-parameters-toc-2] | Query parameter | Type | Required | Limitations | Details | | ---------------- | ---------- | -------- | ------------------------------------------------------------------ | --------------------- | | `domain_id` | `string` | no | | | | `recipient_id[]` | `string` | no | Max number of recipients: *50* *TBD* | *Not yet implemented* | | `date_from` | `int` | yes | Timestamp is assumed to be `UTC`. Must be lower than `date_to`. | Format: `1443651141` | | `date_to` | `int` | yes | Timestamp is assumed to be `UTC`. Must be higher than `date_from`. | Format: `1443661141` | | `tags[]` | `string[]` | no | | | ```php use MailerSend\MailerSend; use MailerSend\Helpers\Builder\OpensAnalyticsParams; $mailersend = new MailerSend(['api_key' => 'key']); $opensAnalyticsParams = (new OpensAnalyticsParams(100, 101)) ->setDomainId('domain_id') ->setTags(['tag']); $mailersend->analytics->opensByUserAgentName($opensAnalyticsParams); ``` [More examples](https://github.com/mailersend/mailersend-php) ```javascript import 'dotenv/config'; import { MailerSend } from "mailersend"; const mailerSend = new MailerSend({ apiKey: process.env.API_KEY, }); mailerSend.email.analytics.byUserAgent({ date_from: 1443651141, date_to: 2443651141, }).then(response => { console.log(response.body); }).catch(error => { console.log(error.body); }); ``` [More examples](https://github.com/mailersend/mailersend-nodejs) ```python from mailersend import MailerSendClient, AnalyticsBuilder from datetime import datetime, timedelta ms = MailerSendClient() date_from = int((datetime.now() - timedelta(days=30)).timestamp()) date_to = int(datetime.now().timestamp()) request = (AnalyticsBuilder() .date_from(date_from) .date_to(date_to) .domain_id("domain-id") .build()) response = ms.analytics.get_opens_by_user_agent(request) ``` [More examples](https://github.com/mailersend/mailersend-python) ```go package main import ( "context" "log" "time" "github.com/mailersend/mailersend-go" ) var APIKey = "Api Key Here" func main() { // Create an instance of the mailersend client ms := mailersend.NewMailersend(APIKey) ctx := context.Background() ctx, cancel := context.WithTimeout(ctx, 5*time.Second) defer cancel() from := time.Now().Add(-24 * time.Hour).Unix() to := time.Now().Unix() domainID := "domain-id" options := &mailersend.AnalyticsOptions{ DomainID: domainID, DateFrom: from, DateTo: to, } _, _, err := ms.Analytics.GetOpensByUserAgent(ctx, options) if err != nil { log.Fatal(err) } } ``` [More examples](https://github.com/mailersend/mailersend-go) ```java import java.util.Date; import com.mailersend.sdk.MailerSend; import com.mailersend.sdk.analytics.AnalyticsList; import com.mailersend.sdk.analytics.AnalyticsStatistic; import com.mailersend.sdk.exceptions.MailerSendException; public void getOpensByUserAgentName() { MailerSend ms = new MailerSend(); ms.setToken(TestHelper.validToken); try { Date dateFrom = new Date(); // set your from date normally AnalyticsList list = ms.analytics() .dateFrom(dateFrom) .dateTo(new Date()) .getOpensByUserAgent(); System.out.println("\n\nOpens by user agent:"); for (AnalyticsStatistic stat : list.statistics) { System.out.println(stat.name + " - " + stat.count); } } catch (MailerSendException e) { e.printStackTrace(); } } ``` [More examples](https://github.com/mailersend/mailersend-java) ```ruby from mailersend import analytics api_key = "API key here" mailer = analytics.NewAnalytics(api_key) date_from = 1623073576 date_to = 1623074976 # optional arguments domain_id = "domain-id" mailer.get_opens_by_user_agent(date_from, date_to, domain_id) ``` [More examples](https://github.com/mailersend/mailersend-ruby) ### Responses [#responses-2] | Response key | Type | Details | | -------------------- | -------- | -------------------------------------------------------- | | `data.stats.*.name` | `string` | User Agent Name. Will not be present if there's no data. | | `data.stats.*.count` | `int` | | #### Valid [#valid-2] ```http Response Code: 200 OK Response Headers: content-type: application/json ``` ```json { "data": { "date_from": 1591228800, "date_to": 1591401599, "stats": [ { "name": "Chrome", "count": 2 } ] } } ``` #### Error [#error-2] ```http Response Code: 422 Unprocessable Entity ``` *See - [Validation errors](/../../general#validation-errors)* ## Opens by reading environment [#opens-by-reading-environment] {/* #### Limitations - Stats are cached for **60s** _TBD_. - Rate limited to **60** requests per hour TBD. */} Retrieve data grouped by the reading environment (webmail, mobile, desktop), based on activity, with this `GET` request: ```http GET https://api.mailersend.com/v1/analytics/ua-type ``` #### Request parameters \[!toc] [#request-parameters-toc-3] | Query parameter | Type | Required | Limitations | Details | | ---------------- | ---------- | -------- | ------------------------------------------------------------------ | --------------------- | | `domain_id` | `string` | no | | | | `recipient_id[]` | `string` | no | Max number of recipients: *50* *TBD* | *Not yet implemented* | | `date_from` | `int` | yes | Timestamp is assumed to be `UTC`. Must be lower than `date_to`. | Format: `1443651141` | | `date_to` | `int` | yes | Timestamp is assumed to be `UTC`. Must be higher than `date_from`. | Format: `1443661141` | | `tags[]` | `string[]` | no | | | ```php use MailerSend\MailerSend; use MailerSend\Helpers\Builder\OpensAnalyticsParams; $mailersend = new MailerSend(['api_key' => 'key']); $opensAnalyticsParams = (new OpensAnalyticsParams(100, 101)) ->setDomainId('domain_id') ->setTags(['tag']); $mailersend->analytics->opensByReadingEnvironment($opensAnalyticsParams); ``` [More examples](https://github.com/mailersend/mailersend-php) ```javascript import 'dotenv/config'; import { MailerSend } from "mailersend"; const mailerSend = new MailerSend({ apiKey: process.env.API_KEY, }); mailerSend.email.analytics.byReadingEnvironment({ date_from: 1443651141, date_to: 2443651141, }).then(response => { console.log(response.body); }).catch(error => { console.log(error.body); }); ``` [More examples](https://github.com/mailersend/mailersend-nodejs) ```python from mailersend import MailerSendClient, AnalyticsBuilder from datetime import datetime, timedelta ms = MailerSendClient() date_from = int((datetime.now() - timedelta(days=30)).timestamp()) date_to = int(datetime.now().timestamp()) request = (AnalyticsBuilder() .date_from(date_from) .date_to(date_to) .domain_id("domain-id") .build()) response = ms.analytics.get_opens_by_reading_environment(request) ``` [More examples](https://github.com/mailersend/mailersend-python) ```go package main import ( "context" "log" "time" "github.com/mailersend/mailersend-go" ) var APIKey = "Api Key Here" func main() { // Create an instance of the mailersend client ms := mailersend.NewMailersend(APIKey) ctx := context.Background() ctx, cancel := context.WithTimeout(ctx, 5*time.Second) defer cancel() from := time.Now().Add(-24 * time.Hour).Unix() to := time.Now().Unix() domainID := "domain-id" options := &mailersend.AnalyticsOptions{ DomainID: domainID, DateFrom: from, DateTo: to, } _, _, err := ms.Analytics.GetOpensByReadingEnvironment(ctx, options) if err != nil { log.Fatal(err) } } ``` [More examples](https://github.com/mailersend/mailersend-go) ```java import java.util.Date; import com.mailersend.sdk.MailerSend; import com.mailersend.sdk.analytics.AnalyticsList; import com.mailersend.sdk.analytics.AnalyticsStatistic; import com.mailersend.sdk.exceptions.MailerSendException; public void getOpensByUserAgentType() { MailerSend ms = new MailerSend(); ms.setToken(TestHelper.validToken); try { Date dateFrom = new Date(); // set your from date normally AnalyticsList list = ms.analytics() .dateFrom(dateFrom) .dateTo(new Date()) .getOpensByUserAgenType(); System.out.println("\n\nOpens by user agent type:"); for (AnalyticsStatistic stat : list.statistics) { System.out.println(stat.name + " - " + stat.count); } } catch (MailerSendException e) { e.printStackTrace(); } } ``` [More examples](https://github.com/mailersend/mailersend-java) ```ruby require "mailersend-ruby" ms_analytics = Mailersend::Analytics.new ms_analytics.ua_type(date_from: 1620643567, date_to: 1623321967) ``` [More examples](https://github.com/mailersend/mailersend-ruby) ### Responses [#responses-3] | Response key | Type | Details | | -------------------- | -------- | ----------------------------------------------------------------------------- | | `data.stats.*.name` | `string` | One of `webmail`, `mobile`,`desktop`. Will not be present if there's no data. | | `data.stats.*.count` | `int` | | #### Valid [#valid-3] ```http Response Code: 200 OK Response Headers: content-type: application/json ``` ```json { "data": { "date_from": 1591228800, "date_to": 1591401599, "stats": [ { "name": "webmail", "count": 2 }, { "name": "mobile", "count": 2 }, { "name": "desktop", "count": 2 } ] } } ``` #### Error [#error-3] ```http Response Code: 422 Unprocessable Entity ``` *See - [Validation errors](/../../general#validation-errors)* # Domains (/api/v1/email/domains) Get information about your domain names, their account verification statuses, activity statistics, and history. ## Get a list of domains [#get-a-list-of-domains] If you want to retrieve information about multiple domains, use this `GET` request: ```http GET https://api.mailersend.com/v1/domains ``` #### Request parameters \[!toc] [#request-parameters-toc] | Query parameter | Type | Required | Limitations | Details | | --------------- | ------ | -------- | --------------------- | ------------- | | `page` | `int` | no | | | | `limit` | `int` | no | Min: `10`, Max: `100` | Default: `25` | | `verified` | `bool` | no | | | ```php use MailerSend\MailerSend; $mailersend = new MailerSend(['api_key' => 'key']); $mailersend->domain->getAll($page = 1, $limit = 10, $verified = true); ``` [More examples](https://github.com/mailersend/mailersend-php) ```javascript import 'dotenv/config'; import { MailerSend } from "mailersend"; const mailerSend = new MailerSend({ apiKey: process.env.API_KEY, }); mailerSend.email.domain.list() .then((response) => console.log(response.body)) .catch((error) => console.log(error.body)); ``` [More examples](https://github.com/mailersend/mailersend-nodejs) ```python from mailersend import MailerSendClient, DomainsBuilder ms = MailerSendClient() request = (DomainsBuilder() .page(1) .limit(25) .build_list_request()) response = ms.domains.list_domains(request) ``` [More examples](https://github.com/mailersend/mailersend-python) ```go package main import ( "context" "log" "time" "github.com/mailersend/mailersend-go" ) var APIKey = "Api Key Here" func main() { // Create an instance of the mailersend client ms := mailersend.NewMailersend(APIKey) ctx := context.Background() ctx, cancel := context.WithTimeout(ctx, 5*time.Second) defer cancel() options := &mailersend.ListDomainOptions{ Page: 1, Limit: 25, } _, _, err := ms.Domain.List(ctx, options) if err != nil { log.Fatal(err) } } ``` [More examples](https://github.com/mailersend/mailersend-go) ```java import com.mailersend.sdk.MailerSend; import com.mailersend.sdk.domains.Domain; import com.mailersend.sdk.domains.DomainsList; import com.mailersend.sdk.exceptions.MailerSendException; public void DomainsList() { MailerSend ms = new MailerSend(); ms.setToken("token"); try { DomainsList list = ms.domains().getDomains(); for (Domain domain : list.domains) { System.out.println(domain.id); System.out.println(domain.name); } } catch (MailerSendException e) { e.printStackTrace(); } } ``` [More examples](https://github.com/mailersend/mailersend-java) ```ruby require "mailersend-ruby" ms_domains = Mailersend::Domains.new ms_domains.list ``` [More examples](https://github.com/mailersend/mailersend-ruby) ### Responses [#responses] #### Valid [#valid] ```http Response Code: 200 OK Response Headers: content-type: application/json ``` ```json { "data" : [ { "id": "1jreeo", "name": "example.org", "dkim": true, "spf": true, "tracking": false, "is_verified": true, "is_cname_verified": false, "is_dns_active": true, "is_cname_active": false, "is_tracking_allowed": false, "has_not_queued_messages": false, "not_queued_messages_count": 0, "domain_settings": { "send_paused": false, "track_clicks": true, "track_opens": true, "track_unsubscribe": true, "track_unsubscribe_html": "

Click here to unsubscribe<\/a><\/p>", "track_unsubscribe_plain": "Click here to unsubscribe: {{unsubscribe}}", "track_content": true, "custom_tracking_enabled": false, "custom_tracking_subdomain": "email", "precedence_bulk": false, "ignore_duplicated_recipients": false }, "created_at": "2020-06-10 10:09:48", "updated_at": "2020-06-10 10:09:48" } ], "links": { "first": "http:\/\/www.mailersend.io\/api\/v1\/domains?page=1", "last": "http:\/\/www.mailersend.io\/api\/v1\/domains?page=1", "prev": null, "next": null }, "meta": { "current_page": 1, "from": 1, "last_page": 1, "path": "http:\/\/www.mailersend.io\/api\/v1\/domains", "per_page": 25, "to": 1, "total": 1 } } ``` #### Error [#error] ```http Response Code: 422 Unprocessable Entity ``` *See - [Validation errors](/../../general#validation-errors)* ## Get a single domain [#get-a-single-domain] If you want to retrieve information about a single domain name, use this `GET` request: ```http GET https://api.mailersend.com/v1/domains/{domain_id} ``` #### Request parameters \[!toc] [#request-parameters-toc-1] | URL parameter | Type | Required | Limitations | Details | | ------------- | -------- | -------- | ----------- | ------- | | `domain_id` | `string` | yes | | | ```php use MailerSend\MailerSend; $mailersend = new MailerSend(['api_key' => 'key']); $mailersend->domain->find('domain_id'); ``` [More examples](https://github.com/mailersend/mailersend-php) ```javascript import 'dotenv/config'; import { MailerSend } from "mailersend"; const mailerSend = new MailerSend({ apiKey: process.env.API_KEY, }); mailerSend.email.domain.single("domain_id") .then((response) => console.log(response.body)) .catch((error) => console.log(error.body)); ``` [More examples](https://github.com/mailersend/mailersend-nodejs) ```python from mailersend import MailerSendClient, DomainsBuilder ms = MailerSendClient() request = (DomainsBuilder() .domain_id("domain-id") .build_get_request()) response = ms.domains.get_domain(request) print(f"Domain: {response.name}") ``` [More examples](https://github.com/mailersend/mailersend-python) ```go package main import ( "context" "log" "time" "github.com/mailersend/mailersend-go" ) var APIKey = "Api Key Here" func main() { // Create an instance of the mailersend client ms := mailersend.NewMailersend(APIKey) ctx := context.Background() ctx, cancel := context.WithTimeout(ctx, 5*time.Second) defer cancel() domainID := "domain-id" _, _, err := ms.Domain.Get(ctx, domainID) if err != nil { log.Fatal(err) } } ``` [More examples](https://github.com/mailersend/mailersend-go) ```java import com.mailersend.sdk.MailerSend; import com.mailersend.sdk.domains.Domain; import com.mailersend.sdk.exceptions.MailerSendException; public void SingleDomain() { MailerSend ms = new MailerSend(); ms.setToken("api token"); try { Domain domain = ms.domains().getDomain("domain id"); System.out.println(domain.id); System.out.println(domain.name); } catch (MailerSendException e) { e.printStackTrace(); } } ``` [More examples](https://github.com/mailersend/mailersend-java) ```ruby require "mailersend-ruby" ms_domains = Mailersend::Domains.new ms_domains.single(domain_id: "idofdomain12412") ``` [More examples](https://github.com/mailersend/mailersend-ruby) ### Responses [#responses-1] #### Valid [#valid-1] ```http Response Code: 200 OK Response Headers: content-type: application/json ``` ```json { "data": { "id": "yjm4ej", "name": "example.org", "dkim": true, "spf": true, "mx": false, "tracking": false, "is_verified": true, "is_cname_verified": false, "is_dns_active": true, "is_cname_active": false, "is_tracking_allowed": false, "has_not_queued_messages": false, "not_queued_messages_count": 0, "domain_settings": { "send_paused": false, "track_clicks": true, "track_opens": true, "track_unsubscribe": true, "track_unsubscribe_html": "

Click here to unsubscribe<\/a><\/p>", "track_unsubscribe_plain": "Click here to unsubscribe: {{unsubscribe}}", "track_content": true, "custom_tracking_enabled": false, "custom_tracking_subdomain": "email", "precedence_bulk": false, "ignore_duplicated_recipients": false }, "created_at": "2020-06-10 10:09:50", "updated_at": "2020-06-10 10:09:50" } } ``` #### Error [#error-1] ```http Response Code: 404 Not Found ``` ## Add a domain [#add-a-domain] If you want to add a new domain, use this `POST` request: ```http POST https://api.mailersend.com/v1/domains ``` ### Request body \[!toc] [#request-body-toc] ```json { "name": "example.com", "return_path_subdomain": "rpsubdomain", "custom_tracking_subdomain": "ctsubdomain", "inbound_routing_subdomain": "irsubdomain" } ``` ```php use MailerSend\MailerSend; use MailerSend\Helpers\Builder\DomainParams; $mailersend = new MailerSend(['api_key' => 'key']); $domainParams = (new DomainParams('domainName')) ->setReturnPathSubdomain('returnPath') ->setCustomTrackingSubdomain('customTracking') ->setInboundRoutingSubdomain('inboundRouting'); $mailersend->domain->create($domainParams); ``` [More examples](https://github.com/mailersend/mailersend-php) ```javascript import 'dotenv/config'; import { MailerSend, Domain } from "mailersend"; const mailerSend = new MailerSend({ apiKey: process.env.API_KEY, }); const domain = new Domain({ name: "example.com", returnPathSubdomain: "rpsubdomain", customTrackingSubdomain: "ctsubdomain", inboundRoutingSubdomain: "irsubdomain", }) mailerSend.email.domain.create(domain) .then((response) => console.log(response.body)) .catch((error) => console.log(error.body)); ``` [More examples](https://github.com/mailersend/mailersend-nodejs) ```python from mailersend import MailerSendClient, DomainsBuilder ms = MailerSendClient() request = (DomainsBuilder() .domain_name("mydomain.com") .return_path_subdomain("rp") .custom_tracking_subdomain("ct") .inbound_routing_subdomain("ir") .build_create_request()) response = ms.domains.create_domain(request) print(f"Created domain with ID: {response.id}") ``` [More examples](https://github.com/mailersend/mailersend-python) ```go package main import ( "context" "log" "time" "github.com/mailersend/mailersend-go" ) var APIKey = "Api Key Here" func main() { // Create an instance of the mailersend client ms := mailersend.NewMailersend(APIKey) ctx := context.Background() ctx, cancel := context.WithTimeout(ctx, 5*time.Second) defer cancel() options := &mailersend.CreateDomainOptions{ Name: "domain.test", } _, _, err := ms.Domain.Create(ctx, options) if err != nil { log.Fatal(err) } } ``` [More examples](https://github.com/mailersend/mailersend-go) ```java import com.mailersend.sdk.MailerSend; import com.mailersend.sdk.domains.Domain; import com.mailersend.sdk.exceptions.MailerSendException; public void AddDomain() { MailerSend ms = new MailerSend(); ms.setToken("api token"); try { Domain domain = ms.domains().addDomainBuilder().addDomain("domain to add"); System.out.println(domain.id); System.out.println(domain.name); } catch (MailerSendException e) { e.printStackTrace(); } } ``` [More examples](https://github.com/mailersend/mailersend-java) ### Request Parameters \[!toc] [#request-parameters-toc-2] *JSON parameters are provided in dot notation* | JSON Parameter | Type | Required | Limitations | Details | | --------------------------- | -------- | -------- | ---------------------------------------------------------------------- | ------- | | `name` | `string` | yes | Must be unique and lowercase. Domain must be available and resolvable. | | | `return_path_subdomain` | `string` | no | Must be alphanumeric. | | | `custom_tracking_subdomain` | `string` | no | Must be alphanumeric. | | | `inbound_routing_subdomain` | `string` | no | Must be alphanumeric. | | ### Responses [#responses-2] | Response Key | Type | Details | | ------------ | ------ | ---------------------- | | data | object | Domain object created. | #### Valid [#valid-2] ```http Response Code: 201 CREATED Response Headers: content-type: application/json ``` ```json { "data": { "id": "dle1krod2jvn8gwm", "name": "testname.com", "dkim": null, "spf": null, "mx": null, "tracking": null, "is_verified": false, "is_dns_active": false, "domain_settings": { "send_paused": false, "track_clicks": true, "track_opens": true, "track_unsubscribe": false, "track_unsubscribe_html": "

Click here to unsubscribe<\/a><\/p>", "track_unsubscribe_html_enabled": false, "track_unsubscribe_plain": "Click here to unsubscribe: {{unsubscribe}}", "track_unsubscribe_plain_enabled": false, "track_content": false, "custom_tracking_enabled": false, "custom_tracking_subdomain": "email", "return_path_subdomain": "mta", "inbound_routing_enabled": false, "inbound_routing_subdomain": "inbound", "precedence_bulk": false, "ignore_duplicated_recipients": false }, "can": { "manage": true }, "totals": [] } } ``` #### Invalid [#invalid] ```http Response Code: 422 Unprocessable Entity ``` *See - [Validation errors](/../../general#validation-errors)* ## Delete a domain [#delete-a-domain] If you want to delete a domain name, use this `DELETE` request: ```http DELETE https://api.mailersend.com/v1/domains/{domain_id} ``` #### Request parameters \[!toc] [#request-parameters-toc-3] | URL parameter | Type | Required | Limitations | Details | | ------------- | -------- | -------- | ----------- | ------- | | `domain_id` | `string` | yes | | | ```php use MailerSend\MailerSend; $mailersend = new MailerSend(['api_key' => 'key']); $mailersend->domain->delete('domain_id'); ``` [More examples](https://github.com/mailersend/mailersend-php) ```javascript import 'dotenv/config'; import { MailerSend } from "mailersend"; const mailerSend = new MailerSend({ apiKey: process.env.API_KEY, }); mailerSend.email.domain.delete("domain_id") .then((response) => console.log(response.body)) .catch((error) => console.log(error.body)); ``` [More examples](https://github.com/mailersend/mailersend-nodejs) ```python from mailersend import MailerSendClient, DomainsBuilder ms = MailerSendClient() request = (DomainsBuilder() .domain_id("domain-id") .build_delete_request()) response = ms.domains.delete_domain(request) ``` [More examples](https://github.com/mailersend/mailersend-python) ```go package main import ( "context" "log" "time" "github.com/mailersend/mailersend-go" ) var APIKey = "Api Key Here" func main() { // Create an instance of the mailersend client ms := mailersend.NewMailersend(APIKey) ctx := context.Background() ctx, cancel := context.WithTimeout(ctx, 5*time.Second) defer cancel() domainID := "domain-id" _, err := ms.Domain.Delete(ctx, domainID) if err != nil { log.Fatal(err) } } ``` [More examples](https://github.com/mailersend/mailersend-go) ```java import com.mailersend.sdk.MailerSend; import com.mailersend.sdk.exceptions.MailerSendException; public void DeleteDomain() { MailerSend ms = new MailerSend(); ms.setToken("api token"); try { boolean domainDeleted = ms.domains().deleteDomain("domain id"); System.out.println("Domain deleted: ".contains(String.valueOf(domainDeleted))); } catch (MailerSendException e) { e.printStackTrace(); } } ``` [More examples](https://github.com/mailersend/mailersend-java) ```ruby require "mailersend-ruby" ms_domains = Mailersend::Domains.new ms_domains.delete(domain_id: "idofdomain12412") ``` [More examples](https://github.com/mailersend/mailersend-ruby) ### Responses [#responses-3] #### Valid [#valid-3] ```http Response Code: 204 OK ``` #### Error [#error-2] ```http Response Code: 404 Not Found ``` ## Get recipients for a domain [#get-recipients-for-a-domain] {/* #### Limitations - Rate limited to **60** requests per hour _TBD_. */} If you want to retrieve information (creation date, update date, deletion date) about the recipients for a domain name, use this `GET` request: ```http GET https://api.mailersend.com/v1/domains/{domain_id}/recipients ``` #### Request parameters \[!toc] [#request-parameters-toc-4] | URL parameter | Type | Required | Limitations | Details | | ------------- | ------ | -------- | ----------- | ------- | | `domain_id` | string | yes | | | | Query parameter | Type | Required | Limitations | Details | | --------------- | ----- | -------- | --------------------- | ------------- | | `page` | `int` | no | | | | `limit` | `int` | no | Min: `10`, Max: `100` | Default: `25` | ```php use MailerSend\MailerSend; $mailersend = new MailerSend(['api_key' => 'key']); $mailersend->domain->recipients($domainId = 'domain_id', $page = 1, $limit = 10); ``` [More examples](https://github.com/mailersend/mailersend-php) ```javascript import 'dotenv/config'; import { MailerSend } from "mailersend"; const mailerSend = new MailerSend({ apiKey: process.env.API_KEY, }); mailerSend.email.domain.recipients("domain_id", { page: 1, limit: 10 }) .then((response) => console.log(response.body)) .catch((error) => console.log(error.body)); ``` [More examples](https://github.com/mailersend/mailersend-nodejs) ```python from mailersend import MailerSendClient, DomainsBuilder ms = MailerSendClient() request = (DomainsBuilder() .domain_id("domain-id") .page(1) .limit(25) .build_recipients_request()) response = ms.domains.get_domain_recipients(request) ``` [More examples](https://github.com/mailersend/mailersend-python) ```go package main import ( "context" "log" "time" "github.com/mailersend/mailersend-go" ) var APIKey = "Api Key Here" func main() { // Create an instance of the mailersend client ms := mailersend.NewMailersend(APIKey) ctx := context.Background() ctx, cancel := context.WithTimeout(ctx, 5*time.Second) defer cancel() domainID := "domain-id" options := &mailersend.GetRecipientsOptions{ DomainID: domainID, Page: 1, Limit: 25, } _, _, err := ms.Domain.GetRecipients(ctx, options) if err != nil { log.Fatal(err) } } ``` [More examples](https://github.com/mailersend/mailersend-go) ```java import com.mailersend.sdk.MailerSend; import com.mailersend.sdk.domains.DomainRecipientsList; import com.mailersend.sdk.exceptions.MailerSendException; import com.mailersend.sdk.util.ApiRecipient; public void ReceipientsPerDomain() { MailerSend ms = new MailerSend(); ms.setToken("api token"); try { DomainRecipientsList list = ms.domains().getDomainRecipients("domaion id"); for (ApiRecipient recipient : list.recipients) { System.out.println(recipient.email); } } catch (MailerSendException e) { e.printStackTrace(); } } ``` [More examples](https://github.com/mailersend/mailersend-java) ```ruby require "mailersend-ruby" ms_domains = Mailersend::Domains.new ms_domains.recipients(domain_id: "idofdomain12412") ``` [More examples](https://github.com/mailersend/mailersend-ruby) ### Responses [#responses-4] #### Valid [#valid-4] ```http Response Code: 200 OK Response Headers: content-type: application/json ``` ```json { "data": [ { "id": "5ee0b174b251345e407c92dc", "email": "dsanford@example.net", "created_at": "2020-06-10 10:09:56", "updated_at": "2020-06-10 10:09:56", "deleted_at": "" }, { "id": "5ee0b174b251345e407c92dd", "email": "konopelski.nina@example.com", "created_at": "2020-06-10 10:09:56", "updated_at": "2020-06-10 10:09:56", "deleted_at": "" }, { "id": "5ee0b174b251345e407c92de", "email": "hester.howe@example.net", "created_at": "2020-06-10 10:09:56", "updated_at": "2020-06-10 10:09:56", "deleted_at": "" } ], "links": { "first": "https:\/\/www.mailersend.io\/api\/v1\/domains\/7qvdnq\/recipients?page=1", "last": "https:\/\/www.mailersend.io\/api\/v1\/domains\/7qvdnq?page=1", "prev": null, "next": null }, "meta": { "current_page": 1, "from": 1, "last_page": 1, "path": "http:\/\/www.mailersend.io\/api\/v1\/recipients", "per_page": 25, "to": 3, "total": 3 } } ``` #### Error [#error-3] ```http Response Code: 422 Unprocessable Entity ``` *See - [Validation errors](/../../general#validation-errors)* ## Update domain settings [#update-domain-settings] If you want to update the domain name settings, use this `PUT` request: ```http PUT https://api.mailersend.com/v1/domains/{domain_id}/settings ``` #### Request Body \[!toc] [#request-body-toc-1] ```json { "send_paused": true, "track_clicks": true, "track_opens": true, "track_unsubscribe": true, "track_unsubscribe_html": "

Click here to unsubscribe<\/a><\/p>", "track_unsubscribe_plain": "Click here to unsubscribe: {{unsubscribe}}", "track_content": true, "custom_tracking_enabled": true, "custom_tracking_subdomain": "email", "precedence_bulk": false, "ignore_duplicated_recipients": false } ``` ```php use MailerSend\MailerSend; use MailerSend\Helpers\Builder\DomainSettingsParams; $mailersend = new MailerSend(['api_key' => 'key']); $domainSettingsParam = (new DomainSettingsParams()) ->setSendPaused(true) ->setTrackClicks(true) ->setTrackOpens(false) ->setTrackUnsubscribe(false) ->setTrackUnsubscribeHtmlEnabled(true) ->setTrackUnsubscribePlainEnabled(true) ->setTrackContent(true) ->setTrackUnsubscribeHtml('Unsubscribe') ->setTrackUnsubscribePlain('Unsubscribe') ->setCustomTrackingEnabled(true) ->setCustomTrackingSubdomain('email') ->setPrecedenceBulk(false) ->setIgnoreDuplicatedRecipients(false); $mailersend->domain->domainSettings($domainId = 'domain_id', $domainSettingsParam); ``` [More examples](https://github.com/mailersend/mailersend-php) ```javascript import 'dotenv/config'; import { MailerSend } from "mailersend"; const mailerSend = new MailerSend({ apiKey: process.env.API_KEY, }); mailerSend.email.domain.updateSettings("domain_id", { send_paused: true, track_clicks: true, track_opens: true, track_unsubscribe: true, track_unsubscribe_html: " Unsubscribe now ", track_unsubscribe_html_enabled: true, track_unsubscribe_plain: "Unsubscribe now", track_unsubscribe_plain_enabled: true, track_content: true, custom_tracking_enabled: true, custom_tracking_subdomain: "subdomain", precedence_bulk: false, ignore_duplicated_recipients: false, }) .then((response) => console.log(response.body)) .catch((error) => console.log(error.body)); ``` [More examples](https://github.com/mailersend/mailersend-nodejs) ```python from mailersend import MailerSendClient, DomainsBuilder ms = MailerSendClient() request = (DomainsBuilder() .domain_id("domain-id") .send_paused(False) .track_clicks(True) .track_opens(True) .track_unsubscribe(True) .track_content(True) .custom_tracking_enabled(True) .custom_tracking_subdomain("email") .precedence_bulk(False) .build_update_settings_request()) response = ms.domains.update_domain_settings(request) ``` [More examples](https://github.com/mailersend/mailersend-python) ```go package main import ( "context" "log" "time" "github.com/mailersend/mailersend-go" ) var APIKey = "Api Key Here" func main() { // Create an instance of the mailersend client ms := mailersend.NewMailersend(APIKey) ctx := context.Background() ctx, cancel := context.WithTimeout(ctx, 5*time.Second) defer cancel() domainID := "domain-id" options := &mailersend.DomainSettingOptions{ DomainID: domainID, SendPaused: mailersend.Bool(false), TrackClicks: mailersend.Bool(true), TrackOpens: mailersend.Bool(true), TrackUnsubscribe: mailersend.Bool(true), TrackUnsubscribeHTML: "Unsubscribe", TrackUnsubscribePlain: "Unsubscribe", TrackContent: mailersend.Bool(true), CustomTrackingEnabled: mailersend.Bool(true), CustomTrackingSubdomain: "email", PrecedenceBulk: mailersend.Bool(false), IgnoreDuplicatedRecipients: mailersend.Bool(false), } _, _, err := ms.Domain.Update(ctx, options) if err != nil { log.Fatal(err) } } ``` [More examples](https://github.com/mailersend/mailersend-go) ```java import com.mailersend.sdk.MailerSend; import com.mailersend.sdk.domains.Domain; import com.mailersend.sdk.exceptions.MailerSendException; public void UpdateDomainSettings() { MailerSend ms = new MailerSend(); ms.setToken("api token"); try { Domain domain = ms.domains().updateDomainSettingsBuilder() .customnTrackingEnabled(true) .sendPaused(false) .precedenceBulk(false) .ignoreDuplicatedRecipients(false) .updateDomain("domain id"); System.out.println(domain.domainSettings.customTrackingEnabled); System.out.println(domain.domainSettings.sendPaused); } catch (MailerSendException e) { e.printStackTrace(); } } ``` [More examples](https://github.com/mailersend/mailersend-java) ```ruby require "mailersend-ruby" ms_domains = Mailersend::Domains.new ms_domains.settings( domain_id: "idofdomain12412", send_paused: false, track_clicks: true, track_opens: true, track_unsubscribe: false, track_unsubscribe_html: "Unsubscribe", track_unsubscribe_plain: "Unsubscribe", track_content: true, custom_tracking_enabled: true, custom_tracking_subdomain: "email", precedence_bulk: false ) ``` [More examples](https://github.com/mailersend/mailersend-ruby) #### Request parameters \[!toc] [#request-parameters-toc-5] | URL parameter | Type | Required | Limitations | Details | | ------------- | ------ | -------- | ----------- | ------- | | `domain_id` | string | yes | | | *JSON parameters are provided in dot notation* | JSON Body Parameter | Type | Required | Limitations | Details | | --------------------------------- | -------- | -------- | ----------- | ------- | | `send_paused` | `bool` | No | | | | `track_clicks` | `bool` | no | | | | `track_opens` | `bool` | no | | | | `track_unsubscribe` | `bool` | no | | | | `track_content` | `bool` | no | | | | `track_unsubscribe_html` | `string` | no | | | | `track_unsubscribe_html_enabled` | `bool` | no | | | | `track_unsubscribe_plain` | `string` | no | | | | `track_unsubscribe_plain_enabled` | `bool` | no | | | | `custom_tracking_enabled` | `bool` | no | | | | `custom_tracking_subdomain` | `string` | no | | | | `precedence_bulk` | `bool` | no | | | | `ignore_duplicated_recipients` | `bool` | no | | | ### Responses [#responses-5] #### Valid [#valid-5] ```http Response Code: 200 OK ``` ```json { "data": { "id": "dq3wdj", "name": "example.org", "dkim": true, "spf": true, "tracking": false, "is_verified": true, "is_cname_verified": true, "is_dns_active": true, "is_cname_active": true, "is_tracking_allowed": true, "has_not_queued_messages": false, "not_queued_messages_count": 0, "domain_settings": { "send_paused": true, "track_clicks": true, "track_opens": true, "track_unsubscribe": true, "track_unsubscribe_html": "

Click here to unsubscribe<\/a><\/p>", "track_unsubscribe_plain": "Click here to unsubscribe: {{unsubscribe}}", "track_content": true, "custom_tracking_enabled": true, "custom_tracking_subdomain": "email", "precedence_bulk": false, "ignore_duplicated_recipients": false }, "created_at": "2020-06-10 10:09:52", "updated_at": "2020-06-10 10:09:52" } } ``` #### Error [#error-4] ```http Response Code: 422 Unprocessable Entity ``` *See - [Validation errors](/../../general#validation-errors)* ## Get DNS Records [#get-dns-records] If you want to retrieve the domain's DNS records, use this `GET` request: ```http GET https://api.mailersend.com/v1/domains/{domain_id}/dns-records ``` ### Request Parameters \[!toc] [#request-parameters-toc-6] | URL Parameter | Type | Required | Limitations | Details | | ------------- | -------- | -------- | ----------- | ------- | | `domain_id` | `string` | yes | | | ```php use MailerSend\MailerSend; $mailersend = new MailerSend(['api_key' => 'key']); $mailersend->domain->getDnsRecords('domain_id'); ``` [More examples](https://github.com/mailersend/mailersend-php) ```javascript import 'dotenv/config'; import { MailerSend } from "mailersend"; const mailerSend = new MailerSend({ apiKey: process.env.API_KEY, }); mailerSend.email.domain.dns("domain_id") .then((response) => console.log(response.body)) .catch((error) => console.log(error.body)); ``` [More examples](https://github.com/mailersend/mailersend-nodejs) ```python from mailersend import MailerSendClient, DomainsBuilder ms = MailerSendClient() request = (DomainsBuilder() .domain_id("domain-id") .build_dns_records_request()) response = ms.domains.get_domain_dns_records(request) ``` [More examples](https://github.com/mailersend/mailersend-python) ```go package main import ( "context" "log" "time" "github.com/mailersend/mailersend-go" ) var APIKey = "Api Key Here" func main() { // Create an instance of the mailersend client ms := mailersend.NewMailersend(APIKey) ctx := context.Background() ctx, cancel := context.WithTimeout(ctx, 5*time.Second) defer cancel() domainID := "domain-id" _, _, err := ms.Domain.GetDNS(ctx, domainID) if err != nil { log.Fatal(err) } } ``` [More examples](https://github.com/mailersend/mailersend-go) ```java import com.mailersend.sdk.MailerSend; import com.mailersend.sdk.domains.Domain; import com.mailersend.sdk.domains.DomainDnsAttribute; import com.mailersend.sdk.domains.DomainDnsRecords; import com.mailersend.sdk.exceptions.MailerSendException; public void DomainDnsRecords() { MailerSend ms = new MailerSend(); ms.setToken("api token"); try { DomainDnsRecords records = ms.domains().getDomainDnsRecords("domain id"); printDomainDnsAttribute(records.spf); printDomainDnsAttribute(records.dkim); printDomainDnsAttribute(records.customTracking); printDomainDnsAttribute(records.returnPath); printDomainDnsAttribute(records.inboundRouting); } catch (MailerSendException e) { e.printStackTrace(); } } private void printDomainDnsAttribute(DomainDnsAttribute attribute) { System.out.println(attribute.hostname); System.out.println(attribute.type); System.out.println(attribute.value); } ``` [More examples](https://github.com/mailersend/mailersend-java) ```ruby require "mailersend-ruby" ms_domains = Mailersend::Domains.new ms_domains.dns(domain_id: "idofdomain12412") ``` [More examples](https://github.com/mailersend/mailersend-ruby) ### Responses [#responses-6] #### Valid [#valid-6] ```http Response Code: 200 OK Response Headers: content-type: application/json ``` ```json { "data": { "id": "dle1krod2jvn8gwm", "spf": { "hostname": "testname.com", "type": "TXT", "value": "v=spf1 include:_spf.mailersend.net ip6:fd43:c0d1:c090::\/48 -all" }, "dkim": { "hostname": "mlsend._domainkey.testname.com", "type": "TXT", "value": "v=DKIM1;t=s;p=MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCv9y0EE38P8bpwNnvTRZvxnQkpe7hmv9clRGG8Vj+g3\/JTVh0Q\/4EOrgn29CO\/8ByRGzc9t\/IAQ0pevN0yXOKOLt8Gng67dzqp2hA1IKEBHPwRZjv30ROSjpknDcmnJSVK2KO3sI7lxzQo73fwuwm9WVbXUJpBJG8yQftwibkj+QIDAQAB" }, "return_path": { "hostname": "mta.testname.com", "type": "CNAME", "value": "mailersend.net" }, "custom_tracking": { "hostname": "email.testname.com", "type": "CNAME", "value": "links.mailersend.net" }, "inbound_routing": { "hostname": "inbound.testname.com", "type": "MX", "value": "inbound.mailersend.net", "priority": "10" } } } ``` #### Invalid [#invalid-1] ```http Response Code: 404 Not Found ``` ## Get verification status [#get-verification-status] If you want to retrieve the verification status for a domain, use this `GET` request: ```http GET https://api.mailersend.com/v1/domains/{domain_id}/verify ``` ### Request Parameters \[!toc] [#request-parameters-toc-7] | URL Parameter | Type | Required | Limitations | Details | | ------------- | -------- | -------- | ----------- | ------- | | `domain_id` | `string` | yes | | | ```php use MailerSend\MailerSend; $mailersend = new MailerSend(['api_key' => 'key']); $mailersend->domain->verify('domain_id'); ``` [More examples](https://github.com/mailersend/mailersend-php) ```javascript import 'dotenv/config'; import { MailerSend } from "mailersend"; const mailerSend = new MailerSend({ apiKey: process.env.API_KEY, }); mailerSend.email.domain.verify("domain_id") .then((response) => console.log(response.body)) .catch((error) => console.log(error.body)); ``` [More examples](https://github.com/mailersend/mailersend-nodejs) ```python from mailersend import MailerSendClient, DomainsBuilder ms = MailerSendClient() request = (DomainsBuilder() .domain_id("domain-id") .build_verification_request()) response = ms.domains.get_domain_verification_status(request) ``` [More examples](https://github.com/mailersend/mailersend-python) ```go package main import ( "context" "log" "time" "github.com/mailersend/mailersend-go" ) var APIKey = "Api Key Here" func main() { // Create an instance of the mailersend client ms := mailersend.NewMailersend(APIKey) ctx := context.Background() ctx, cancel := context.WithTimeout(ctx, 5*time.Second) defer cancel() domainID := "domain-id" _, _, err := ms.Domain.Verify(ctx, domainID) if err != nil { log.Fatal(err) } } ``` [More examples](https://github.com/mailersend/mailersend-go) ```java import com.mailersend.sdk.MailerSend; import com.mailersend.sdk.domains.DomainVerificationStatus; import com.mailersend.sdk.exceptions.MailerSendException; public void VerifyDomain() { MailerSend ms = new MailerSend(); ms.setToken("api token"); try { DomainVerificationStatus status = ms.domains().verifyDomain("domain id"); System.out.println(status.message); } catch (MailerSendException e) { e.printStackTrace(); } } ``` [More examples](https://github.com/mailersend/mailersend-java) ```ruby require "mailersend-ruby" ms_domains = Mailersend::Domains.new ms_domains.verify(domain_id: "idofdomain12412") ``` [More examples](https://github.com/mailersend/mailersend-ruby) ### Responses [#responses-7] #### Valid [#valid-7] Domain verified: ```http Response Code: 200 OK Response Headers: content-type: application/json ``` ```json { "message": "The domain is verified.", "data": { "dkim": true, "spf": true, "mx": true, "tracking": false, "cname": true, "rp_cname": true } } ``` Domain not verified: ```http Response Code: 200 OK Response Headers: content-type: application/json ``` ```json { "message": "The domain was not verified, please check your DNS records and try again.", "data": { "dkim": false, "spf": false, "mx": false, "tracking": false, "cname": false, "rp_cname": false } } ``` #### Invalid [#invalid-2] ```http Response Code: 404 Not Found ``` # Email personalization (/api/v1/email/features) ## Personalization [#personalization] MailerSend's Personalization feature allows you to personalize email messages by generating dynamic content for each recipient when sending emails using the [Email](/email#send-an-email) endpoint. * Personalization only compiles the template if `personalization` data is passed via Email API * Personalization is available for `subject`, `html` and `text` fields * It is cached server-side, but the hash is calculated based on content so it will reset with every change A limited version of the [Twig](https://twig.symfony.com/) v3.x templating engine is used as a template language. ### Template language [#template-language] #### Example of personalization passed to Email API: [#example-of-personalization-passed-to-email-api] ```json { "personalization": [ { "email": "test@mailersend.com", "data": { "var": "value", "boolean": true, "object": { "key" : "object-value" }, "number": 2, "array": [ 1, 2, 3 ] } } ] } ``` ### Variables [#variables] Variables are used to print basic data. The variable should look like `{{var}}`. It starts with double curly brackets `{{`, followed by the variable name and is closed with double curly brackets `}}`. Variables are available in `subject`, `html` and `text` fields. #### General rules: [#general-rules] * Must be surrounded by double curly brackets `{{var}}` * May contain alphanumeric characters and underscores (\_) * Must not start with a number or underscore * Are case sensitive, meaning that `{{VAR}}` is different from `{{var}}` #### Examples of combinations: [#examples-of-combinations] | Syntax | Output | Details | | --------------------- | ------------ | ------------------------------------------------------------------ | | `{{var}}` | value | Display a simple variable (no array or object). | | `{{object.key}}` | object-value | Display the key value of an object. | | `{{number + number}}` | 4 | A simple calculation of two simple variables (no array or object). | ### Conditional statement [#conditional-statement] A conditional statement (i.e. if/elseif/else) appears inside `{%` `%}` block. A conditional block always starts with the `if` keyword followed by the statement that is being tested, and ends with the `endif` keyword. Conditional statements are only available in `html` and `text` fields. Additional [filters](https://twig.symfony.com/doc/3.x/templates.html#filters) are also available in: `escape`, `default`, `length`, `lower`, `upper` and `keys`. #### Example: \[!toc] [#example-toc] ```twig {% if boolean == true %} Available {% elseif number > 0 %} Only {{number}} left! {% else %} Sold-out! {% endif %} ``` #### Output: \[!toc] [#output-toc] ```html Available ``` ### Foreach [#foreach] A collection of data (an array) can be printed by looping through all the items in this collection. A loop should appear inside the `{%` `%}` block. A loop block always starts with the `for` keyword, and ends with the `endfor` keyword. Foreach is only available in `html` and `text` fields. Additional [filters](https://twig.symfony.com/doc/3.x/templates.html#filters) are also available in: `escape`, `length`, `lower`, `upper` and `keys`. #### Example: \[!toc] [#example-toc-1] ```twig {% if array|length > 0 %}

{% endif %} ``` #### Output: \[!toc] [#output-toc-1] ```html
  • 1
  • 2
  • 3
``` More details about iterating over keys, getting loop info, etc. [can be found here](https://twig.symfony.com/doc/3.x/tags/for.html). # Inbound routing (/api/v1/email/inbound) ## Get a list of inbound routes [#get-a-list-of-inbound-routes] If you want to retrieve information about multiple inbound routes, use this `GET` request: ```http GET https://api.mailersend.com/v1/inbound ``` #### Request parameters \[!toc] [#request-parameters-toc] | Query parameter | Type | Required | Limitations | Details | | --------------- | -------- | -------- | --------------------- | ------------- | | `domain_id` | `string` | no | | | | `page` | `int` | no | Min: `1` | | | `limit` | `int` | no | Min: `10`, Max: `100` | Default: `10` | ```php use MailerSend\MailerSend; $mailersend = new MailerSend(['api_key' => 'key']); $mailersend->inbound->getAll($domainId = 'domainId', $page = 1, $limit = 10); ``` [More examples](https://github.com/mailersend/mailersend-php) ```javascript import 'dotenv/config'; import { MailerSend } from "mailersend"; const mailerSend = new MailerSend({ apiKey: process.env.API_KEY, }); mailerSend.email.inbound.list() .then((response) => console.log(response.body)) .catch((error) => console.log(error.body)); ``` [More examples](https://github.com/mailersend/mailersend-nodejs) ```python from mailersend import MailerSendClient, InboundBuilder ms = MailerSendClient() request = (InboundBuilder() .domain_id("domain-id") .build_list_request()) response = ms.inbound.list(request) ``` [More examples](https://github.com/mailersend/mailersend-python) ```go package main import ( "context" "github.com/mailersend/mailersend-go" ) var APIKey = "Api Key Here" func main() { // Create an instance of the mailersend client ms := mailersend.NewMailersend(APIKey) ctx := context.TODO() domainID := "domain-id" listOptions := &mailersend.ListInboundOptions{ DomainID: domainID, } _, _, _ = ms.Inbound.List(ctx, listOptions) } ``` [More examples](https://github.com/mailersend/mailersend-go) ```java import com.mailersend.sdk.MailerSend; import com.mailersend.sdk.exceptions.MailerSendException; import com.mailersend.sdk.inboundroutes.InboundRoute; import com.mailersend.sdk.inboundroutes.InboundRoutesList; public void getInboundRoutes() { MailerSend ms = new MailerSend(); ms.setToken("Your API token"); try { InboundRoutesList routes = ms.inboundRoutes().getRoutes(); for (InboundRoute route : routes.routes) { System.out.println(route.id); } } catch (MailerSendException e) { e.printStackTrace(); } } ``` [More examples](https://github.com/mailersend/mailersend-java) ```ruby require "mailersend-ruby" ms_inbound_routes = Mailersend::InboundRouting.new ms_inbound_routes.get_inbound_routes ``` [More examples](https://github.com/mailersend/mailersend-ruby) ### Responses [#responses] #### Valid [#valid] ```http Response Code: 200 OK Response Headers: content-type: application/json ``` ```json { "data": [ { "id": "v57gn2j67qlr6z4d", "name": "Test name", "address": "imxbfppzn7cbhak9lef5@inbound.mailersend.net", "domain": "test.mailersend.com", "dns_checked_at": null, "enabled": true, "filters": [ { "type": "catch_recipient", "key": null, "comparer": "equal", "value": "test" }, { "type": "match_all", "key": null, "comparer": null, "value": null } ], "forwards": [ { "type": "webhook", "value": "https:\/\/yourapp.com\/hook", "secret": "jYhafQeTihgw0qWclkUA7cbqTG3Zfh2j" } ], "priority": 100, "mxValues": { "priority": 10, "target": "inbound.mailersend.net" } } ] } ``` #### Error [#error] ```http Response Code: 404 Not Found ``` ## Get a single inbound route [#get-a-single-inbound-route] If you want to retrieve a single inbound route, use this `GET` request: ```http GET https://api.mailersend.com/v1/inbound/{inbound_id} ``` #### Request parameters \[!toc] [#request-parameters-toc-1] | URL parameter | Type | Required | Limitations | Details | | ------------- | -------- | -------- | ----------- | ------- | | `inbound_id` | `string` | yes | | | ```php use MailerSend\MailerSend; $mailersend = new MailerSend(['api_key' => 'key']); $mailersend->inbound->find('inboundId'); ``` [More examples](https://github.com/mailersend/mailersend-php) ```javascript import 'dotenv/config'; import { MailerSend } from "mailersend"; const mailerSend = new MailerSend({ apiKey: process.env.API_KEY, }); mailerSend.email.inbound.single("inbound_id") .then((response) => console.log(response.body)) .catch((error) => console.log(error.body)); ``` [More examples](https://github.com/mailersend/mailersend-nodejs) ```python from mailersend import MailerSendClient, InboundBuilder ms = MailerSendClient() request = (InboundBuilder() .inbound_id("inbound-id") .build_get_request()) response = ms.inbound.get(request) ``` [More examples](https://github.com/mailersend/mailersend-python) ```go package main import ( "context" "github.com/mailersend/mailersend-go" ) var APIKey = "Api Key Here" func main() { // Create an instance of the mailersend client ms := mailersend.NewMailersend(APIKey) ctx := context.TODO() inboundID := "inbound-id" _, _, _ = ms.Inbound.Get(ctx, inboundID) } ``` [More examples](https://github.com/mailersend/mailersend-go) ```java import com.mailersend.sdk.MailerSend; import com.mailersend.sdk.exceptions.MailerSendException; import com.mailersend.sdk.inboundroutes.InboundRoute; public void getInboundRoute() { MailerSend ms = new MailerSend(); ms.setToken("Your API token"); try { InboundRoute route = ms.inboundRoutes().getRoute("inbound route id"); System.out.println(route.id); System.out.println(route.name); } catch (MailerSendException e) { e.printStackTrace(); } } ``` [More examples](https://github.com/mailersend/mailersend-java) ```ruby require "mailersend-ruby" ms_inbound_routes = Mailersend::InboundRouting.new ms_inbound_routes.get_single_route(inbound_id: 'idofroute12412') ``` [More examples](https://github.com/mailersend/mailersend-ruby) ### Responses [#responses-1] #### Valid [#valid-1] ```http Response Code: 200 OK Response Headers: content-type: application/json ``` ```json { "data": { "id": "v57gn2j67qlr6z4d", "name": "Test name", "address": "imxbbppzn7cbhak9lef5@inbound.mailersend.net", "domain": "test.mailersend.com", "dns_checked_at": null, "enabled": true, "filters": [ { "type": "catch_recipient", "key": null, "comparer": "equal", "value": "test" }, { "type": "match_all", "key": null, "comparer": null, "value": null } ], "forwards": [ { "id": "v57gn2j67qlr6z4d", "type": "webhook", "value": "https:\/\/yourapp.com\/hook", "secret": "jYhafQeTiZgw0qWxlkUA7cbqTG3Zfh2j" } ], "priority": 100, "mxValues": { "priority": 10, "target": "inbound.mailersend.net" } } } ``` #### Error [#error-1] ```http Response Code: 404 Not Found ``` ## Add an inbound route [#add-an-inbound-route] If you want to add a new inbound route to a domain, use this `POST` request: ```http POST https://api.mailersend.com/v1/inbound ``` ### Request body \[!toc] [#request-body-toc] ```json { "domain_id": "7nxe3yjmeq28vp0k", "name": "Test name", "domain_enabled": true, "inbound_domain": "test.mailersend.com", "inbound_priority": 100, "match_filter": { "type": "match_all" }, "catch_filter": { "type": "catch_recipient", "filters": [ { "comparer": "equal", "value": "test" } ] }, "forwards": [ { "type": "webhook", "value": "https://www.mailersend.com/hook" } ] } ``` ```php use MailerSend\MailerSend; use MailerSend\Helpers\Builder\Inbound; use \MailerSend\Helpers\Builder\CatchFilter; use \MailerSend\Helpers\Builder\MatchFilter; use \MailerSend\Helpers\Builder\Forward; use \MailerSend\Helpers\Builder\Filter; use \MailerSend\Common\Constants; $mailersend = new MailerSend(['api_key' => 'key']); $mailersend->inbound->create( (new Inbound('domainId', 'name', true)) ->setInboundDomain('inboundDomain') ->setCatchFilter( (new CatchFilter(Constants::TYPE_CATCH_RECIPIENT) ->addFilter(new Filter(Constants::COMPARER_EQUAL, 'test@mailersend.com')))) ->setMatchFilter( (new MatchFilter(Constants::TYPE_MATCH_SENDER)) ->addFilter(new Filter(Constants::COMPARER_EQUAL, 'sender@mailersend.com', 'sender'))) ->addForward(new Forward(Constants::TYPE_WEBHOOK, 'https://www.mailersend.com/hook')) ); ``` [More examples](https://github.com/mailersend/mailersend-php) ```javascript import 'dotenv/config'; import { MailerSend, Inbound, InboundFilterType } from "mailersend"; const mailerSend = new MailerSend({ apiKey: process.env.API_KEY, }); const inbound = new Inbound() .setDomainId('domain_id') .setName('inbound test') .setDomainEnabled(true) .setMatchFilter({ type: InboundFilterType.MATCH_ALL, }) .setForwards([ { type: "webhook", value: "https://www.yourdomain.com/hook" } ]); mailerSend.email.inbound.create(inbound) .then((response) => console.log(response.body)) .catch((error) => console.log(error.body)); ``` [More examples](https://github.com/mailersend/mailersend-nodejs) ```python from mailersend import MailerSendClient, InboundBuilder ms = MailerSendClient() request = (InboundBuilder() .domain_id("domain-id") .name("My Inbound Route") .domain_enabled(False) .inbound_priority(1) .catch_type("all") .match_type("all") .add_forward("email", "support@mycompany.com") .catch_recipient([{"comparer": "equal", "value": "support"}]) .add_match_filter("match_sender", [{"comparer": "equal", "value": "support"}]) .add_webhook_forward("https://mycompany.com/webhook") .build_create_request()) response = ms.inbound.create_inbound_route(request) ``` [More examples](https://github.com/mailersend/mailersend-python) ```go package main import ( "context" "github.com/mailersend/mailersend-go" ) var APIKey = "Api Key Here" func main() { // Create an instance of the mailersend client ms := mailersend.NewMailersend(APIKey) ctx := context.TODO() domainID := "domain-id" createOptions := &mailersend.CreateInboundOptions{ DomainID: domainID, Name: "Example Route", DomainEnabled: *mailersend.Bool(false), MatchFilter: &mailersend.MatchFilter{ Type: "match_all", }, CatchFilter: &mailersend.CatchFilter{}, Forwards: []mailersend.Forwards{ { Type: "webhook", Value: "https://example.com", }, }, } _, _, _ = ms.Inbound.Create(ctx, createOptions) } ``` [More examples](https://github.com/mailersend/mailersend-go) ```java import com.mailersend.sdk.MailerSend; import com.mailersend.sdk.exceptions.MailerSendException; import com.mailersend.sdk.inboundroutes.Forward; public void createInboundRoute() { MailerSend ms = new MailerSend(); ms.setToken("Your API token"); try { Forward forward = new Forward(); forward.type = "webhook"; forward.value = "https://example-domain.com"; ms.inboundRoutes().builder() .domainId("domain id") .name("Test inbound name") .domainEnabled(false) .matchFilter("match_all") .forwards(new Forward[] { forward }) .addRoute(); } catch (MailerSendException e) { e.printStackTrace(); } } ``` [More examples](https://github.com/mailersend/mailersend-java) ```ruby require "mailersend-ruby" ms_inbound_routes = Mailersend::InboundRouting.new ms_inbound_routes.settings = { 'domain_id' => 'yourdomainid', 'name' => 'inbound_name', 'domain_enabled' => false, 'match_filter' => { 'type' => 'match_all' }, 'forwards' => [{ 'type' => 'webhook', 'value' => 'https://example.com' }] } puts ms_inbound_routes.add_inbound_route ``` [More examples](https://github.com/mailersend/mailersend-ruby) ### Request Parameters \[!toc] [#request-parameters-toc-2] *JSON parameters are provided in dot notation* | JSON Parameter | Type | Required | Limitations | Details | | --------------------------------- | ---------- | ----------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------- | | `domain_id` | `string` | yes | | | | `name` | `string` | yes | `Max` 191 characters. | | | `domain_enabled` | `boolean` | yes | | | | `inbound_domain` | `string` | yes\*\* | `Max` 191 characters, unique, and must end with the current domain name. | | | `inbound_priority` | `integer` | yes\*\* | `Min` 0 and `Max` 100. Priority weight is ordered in a descending order, `0` has more importance than `100`. Must be unique per domain when `domain_enabled` is `true`. | | | `catch_filter` | `object[]` | yes\*\* | | | | `catch_filter.type` | `string` | yes | Must be one of the inbound's types: `catch_all`, `catch_recipient`. | | | `catch_filter.filters` | `object[]` | yes\*\*\* | `Max` 5. | | | `catch_filter.filters.*.comparer` | `string` | yes | Must be one of the comparers: `equal`, `not-equal`, `contains`, `not-contains`, `starts-with`, `ends-with`, `not-starts-with`, `not-ends-with`. | | | `catch_filter.filters.*.value` | `string` | yes | `Max` 191 characters. | | | `catch_type` | `string` | no | Must be one of the catch types: `all`, `one` when the `catch filter type` is set to `catch_recipient`. | | | `match_filter` | `object[]` | yes | | | | `match_filter.type` | `string` | yes | Must be one of the inbound's types: `match_all`, `match_sender`, `match_domain`, `match_header`. | | | `match_filter.filters` | `object[]` | yes\*\*\* | `Max` 5. | | | `match_filter.filters.*.comparer` | `string` | yes | Must be one of the comparers: `equal`, `not-equal`, `contains`, `not-contains`, `starts-with`, `ends-with`, `not-starts-with`, `not-ends-with`. | | | `match_filter.filters.*.value` | `string` | yes | `Max` 191 characters. | | | `match_filter.filters.*.key` | `string` | yes\*\*\*\* | `Max` 191 characters. | | | `match_type` | `string` | no | Must be one of the match types: `all`, `one` when the `match filter type` is set to `match_sender`, `match_domain`, or `match_header`. | | | `forwards` | `object[]` | yes | `Min` 1 and `max` 5. | | | `forwards.*.type` | `string` | yes | Must be either `email` or `webhook`. | | | `forwards.*.value` | `string` | yes | Must be distinct, `max` 191 characters. If its type is `webhook`, it must be a valid URL. If its type is `email`, it must be a valid email address. | | ###### \* Required if inbound domain is not enabled. [#-required-if-inbound-domain-is-not-enabled] ###### \*\* Required if inbound domain is enabled. [#-required-if-inbound-domain-is-enabled] ###### \*\*\* Required if inbound is enabled and filter type is not `match_all`. [#-required-if-inbound-is-enabled-and-filter-type-is-not-match_all] ###### \*\*\*\* Required if match type is `match_header`. [#-required-if-match-type-is-match_header] When `forwards.*.type` is set to `webhook`, MailerSend will send a test request to the provided URL to verify that it is reachable. The endpoint must return a `2xx` response for the route to be saved successfully. The test request uses the following payload: ```json { "type": "webhook.test", "message": "This is a ping test message", "created_at": "2026-03-27T07:24:20.577080Z" } ``` This test request is signed with a fixed test secret: `test_Am3L1GuOIc4blLUuHqAPxxwkZaJyEk8G`. Use it to verify the signature of incoming test requests. ### Responses [#responses-2] | Response Key | Type | Details | | ------------ | ------ | ----------------------- | | data | object | Inbound object created. | #### Valid [#valid-2] ```http Response Code: 201 CREATED Response Headers: content-type: application/json ``` ```json { "data": { "id": "v57gn2j67qlr6z4d", "name": "Test name", "address": "imxbfnpzn7cbhak9lef5@inbound.mailersend.net", "domain": "test.mailersend.com", "dns_checked_at": null, "enabled": true, "filters": [ { "type": "catch_recipient", "key": null, "comparer": "equal", "value": "test" }, { "type": "match_all", "key": null, "comparer": null, "value": null } ], "forwards": [ { "type": "webhook", "value": "https:\/\/yourapp.com\/hook", "secret": "jYhafQeTiZgw0qWclkUA7cbqTG3Zfh2j" } ], "priority": 100, "mxValues": { "priority": 10, "target": "inbound.mailersend.net" } } } ``` #### Invalid [#invalid] ```http Response Code: 422 Unprocessable Entity ``` *See - [Validation errors](/../../general#validation-errors)* ## Update an inbound route [#update-an-inbound-route] If you want to update the information of an existing inbound route, use this `PUT` request: ```http PUT https://api.mailersend.com/v1/inbound/{inbound_id} ``` ### Request body \[!toc] [#request-body-toc-1] ```json { "domain_id": "7nxe3yjmeq28vp0k", "name": "Test update", "domain_enabled": true, "inbound_domain": "test.mailersend.com", "inbound_priority": 100, "match_filter": { "type": "match_all" }, "catch_filter": { "type": "catch_recipient", "filters": [ { "comparer": "equal", "value": "test" } ] }, "forwards": [ { "type": "webhook", "value": "https://yourapp.com/hook" } ] } ``` ```php use MailerSend\MailerSend; use MailerSend\Helpers\Builder\Inbound; use \MailerSend\Helpers\Builder\CatchFilter; use \MailerSend\Helpers\Builder\MatchFilter; use \MailerSend\Helpers\Builder\Forward; use \MailerSend\Common\Constants; $mailersend = new MailerSend(['api_key' => 'key']); $mailersend->inbound->update( 'inboundId', (new Inbound('domainId', 'name', true)) ->setInboundDomain('inboundDomain') ->setCatchFilter( (new CatchFilter(Constants::TYPE_CATCH_ALL)) ) ->setMatchFilter(new MatchFilter(Constants::TYPE_MATCH_ALL)) ->addForward(new Forward(Constants::TYPE_WEBHOOK, 'https://www.mailersend.com/hook')) ); ``` [More examples](https://github.com/mailersend/mailersend-php) ```javascript import 'dotenv/config'; import { MailerSend, Inbound, InboundFilterType } from "mailersend"; const mailerSend = new MailerSend({ apiKey: process.env.API_KEY, }); const inbound = new Inbound() .setDomainId('domain_id') .setName('inbound test 2') .setDomainEnabled(false) .setMatchFilter({ type: InboundFilterType.MATCH_ALL, }) .setForwards([ { type: "webhook", value: "https://www.yourdomain.com/hook" } ]); mailerSend.email.inbound.update('inbound_id', inbound) .then((response) => console.log(response.body)) .catch((error) => console.log(error.body)); ``` [More examples](https://github.com/mailersend/mailersend-nodejs) ```python from mailersend import MailerSendClient, InboundBuilder ms = MailerSendClient() request = (InboundBuilder() .inbound_id("inbound-id") .name("Updated Route Name") .enabled(False) .build_update_request()) response = ms.inbound.update_inbound_route(request) ``` [More examples](https://github.com/mailersend/mailersend-python) ```go package main import ( "context" "github.com/mailersend/mailersend-go" ) var APIKey = "Api Key Here" func main() { // Create an instance of the mailersend client ms := mailersend.NewMailersend(APIKey) ctx := context.TODO() inboundID := "inbound-id" updateOptions := &mailersend.UpdateInboundOptions{ Name: "Example Route", DomainEnabled: *mailersend.Bool(true), InboundDomain: "inbound.example.com", MatchFilter: &mailersend.MatchFilter{ Type: "match_all", }, CatchFilter: &mailersend.CatchFilter{ Type: "catch_recipient", Filters: []mailersend.Filter{ { Comparer: "equal", Value: "email", }, { Comparer: "equal", Value: "emails", }, }, }, Forwards: []mailersend.Forwards{ { Type: "webhook", Value: "https://example.com", }, }, } _, _, _ = ms.Inbound.Update(ctx, inboundID, updateOptions) } ``` [More examples](https://github.com/mailersend/mailersend-go) ```java import com.mailersend.sdk.MailerSend; import com.mailersend.sdk.exceptions.MailerSendException; import com.mailersend.sdk.inboundroutes.Forward; import com.mailersend.sdk.inboundroutes.InboundRoute; public void updateInboundRoute() { MailerSend ms = new MailerSend(); ms.setToken("Your API token"); try { Forward forward = new Forward(); forward.type = "webhook"; forward.value = "https://example-domain.com"; InboundRoute route = ms.inboundRoutes().builder() .domainId("domain id") .name("Updated route name") .domainEnabled(false) .matchFilter("match_all") .forwards(new Forward[] { forward }) .updateRoute("inbound route id"); System.out.println(route.id); System.out.println(route.name); } catch (MailerSendException e) { e.printStackTrace(); } } ``` [More examples](https://github.com/mailersend/mailersend-java) ```ruby require "mailersend-ruby" ms_inbound_routes = Mailersend::InboundRouting.new ms_inbound_routes.settings = { 'domain_id' => 'yourdomainid', 'name' => 'inbound_updated', 'domain_enabled' => false, 'match_filter' => { 'type' => 'match_all' }, 'forwards' => [{ 'type' => 'webhook', 'value' => 'https://example.com' }] } puts ms_inbound_routes.update_inbound_route(inbound_id: 'idofroute12412') ``` [More examples](https://github.com/mailersend/mailersend-ruby) ### Request Parameters \[!toc] [#request-parameters-toc-3] | URL parameter | Type | Required | Limitations | Details | | ------------- | -------- | -------- | ----------- | ------- | | `inbound_id` | `string` | yes | | | *JSON parameters are provided in dot notation* | JSON Parameter | Type | Required | Limitations | Details | | --------------------------------- | ---------- | ----------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------- | | `name` | `string` | yes | `Max` 191 characters. | | | `domain_enabled` | `boolean` | yes | | | | `inbound_domain` | `string` | yes\*\* | `Max` 191 characters. Must end with the current domain name. | | | `inbound_priority` | `int` | yes\*\* | `Min` 0 `Max` 100. Priority weight is ordered in a descending order, `0` has more importance than `100`. Must be unique per domain when `domain_enabled` is `true`. | | | `catch_filter` | `object[]` | yes\*\* | | | | `catch_filter.type` | `string` | yes | Must be one of the inbound's types: `catch_all`, `catch_recipient`. | | | `catch_filter.filters` | `object[]` | yes\*\*\* | `Max` 5. | | | `catch_filter.filters.*.comparer` | `string` | yes | Must be one of the comparers: `equal`, `not-equal`, `contains`, `not-contains`, `starts-with`, `ends-with`, `not-starts-with`, `not-ends-with`. | | | `catch_filter.filters.*.value` | `string` | yes | `Max` 191 characters. | | | `catch_type` | `string` | no | Must be one of the catch types: `all`, `one` when the `catch filter type` is set to `catch_recipient`. | | | `match_filter` | `object[]` | yes | | | | `match_filter.type` | `string` | yes | Must be one of the inbound's types: `match_all`, `match_sender`, `match_domain`, `match_header`. | | | `match_filter.filters` | `object[]` | yes\*\*\* | `Max` 5. | | | `match_filter.filters.*.comparer` | `string` | yes | Must be one of the comparers: `equal`, `not-equal`, `contains`, `not-contains`, `starts-with`, `ends-with`, `not-starts-with`, `not-ends-with`. | | | `match_filter.filters.*.value` | `string` | yes | `Max` 191 characters. | | | `match_filter.filters.*.key` | `string` | yes\*\*\*\* | `Max` 191 characters. | | | `match_type` | `string` | no | Must be one of the match types: `all`, `one` when the `match filter type` is set to `match_sender`, `match_domain`, or `match_header`. | | | `forwards` | `object[]` | yes | `Min` 1 and `max` 5. | | | `forwards.*.type` | `string` | yes | Must be either `email` or `webhook`. | | | `forwards.*.value` | `string` | yes | Must be distinct, `max` 191 characters. If its type is `webhook`, it must be a valid URL. If its type is `email`, it must be a valid email address. | | ###### \* Required if inbound is not enabled. [#-required-if-inbound-is-not-enabled] ###### \*\* Required if inbound is enabled. [#-required-if-inbound-is-enabled] ###### \*\*\* Required if inbound is enabled and filter type is not `match_all`. [#-required-if-inbound-is-enabled-and-filter-type-is-not-match_all-1] ###### \*\*\*\* Required if match type is `match_header`. [#-required-if-match-type-is-match_header-1] When `forwards.*.type` is set to `webhook`, MailerSend will send a test request to the provided URL to verify that it is reachable. The endpoint must return a `2xx` response for the route to be saved successfully. The test request uses the following payload: ```json { "type": "webhook.test", "message": "This is a ping test message", "created_at": "2026-03-27T07:24:20.577080Z" } ``` This test request is signed with a fixed test secret: `test_Am3L1GuOIc4blLUuHqAPxxwkZaJyEk8G`. Use it to verify the signature of incoming test requests. ### Responses [#responses-3] | Response Key | Type | Details | | ------------ | ------ | ----------------------- | | data | object | Inbound object created. | #### Valid [#valid-3] ```http Response Code: 200 OK Response Headers: content-type: application/json ``` ```json { "data": { "id": "v57gn2j67qlr6z4d", "name": "Test update", "address": "qi5onrgpw4ujkiqg0p9b@inbound.mailersend.net", "domain": "test.mailersend.com", "dns_checked_at": null, "enabled": true, "filters": [ { "type": "catch_recipient", "key": null, "comparer": "equal", "value": "test" }, { "type": "match_all", "key": null, "comparer": null, "value": null } ], "forwards": [ { "type": "webhook", "value": "https:\/\/yourapp.com\/hook", "secret": "jYhafQeTiZgw0qWclkUA7cnqTG3Zfh2j" } ], "mxValues": { "priority": 10, "target": "inbound.mailersend.net" } } } ``` #### Invalid [#invalid-1] ```http Response Code: 422 Unprocessable Entity ``` *See - [Validation errors](/../../general#validation-errors)* ## Delete an inbound route [#delete-an-inbound-route] If you want to delete an inbound route, use this `DELETE` request: ```http DELETE https://api.mailersend.com/v1/inbound/{inbound_id} ``` ### Request parameters \[!toc] [#request-parameters-toc-4] | URL parameter | Type | Required | Limitations | Details | | ------------- | -------- | -------- | ----------- | ------- | | `inbound_id` | `string` | yes | | | ```php use MailerSend\MailerSend; $mailersend = new MailerSend(['api_key' => 'key']); $mailersend->inbound->delete('inboundId'); ``` [More examples](https://github.com/mailersend/mailersend-php) ```javascript import 'dotenv/config'; import { MailerSend } from "mailersend"; const mailerSend = new MailerSend({ apiKey: process.env.API_KEY, }); mailerSend.email.inbound.delete("inbound_id") .then((response) => console.log(response.body)) .catch((error) => console.log(error.body)); ``` [More examples](https://github.com/mailersend/mailersend-nodejs) ```python from mailersend import MailerSendClient, InboundBuilder ms = MailerSendClient() request = (InboundBuilder() .inbound_id("inbound-id") .build_delete_request()) response = ms.inbound.delete_inbound_route(request) ``` [More examples](https://github.com/mailersend/mailersend-python) ```go package main import ( "context" "github.com/mailersend/mailersend-go" ) var APIKey = "Api Key Here" func main() { // Create an instance of the mailersend client ms := mailersend.NewMailersend(APIKey) ctx := context.TODO() inboundID := "inbound-id" _, _ = ms.Inbound.Delete(ctx, inboundID) } ``` [More examples](https://github.com/mailersend/mailersend-go) ```java import com.mailersend.sdk.MailerSend; import com.mailersend.sdk.exceptions.MailerSendException; public void deleteInboundRoute() { MailerSend ms = new MailerSend(); ms.setToken("Your API token"); try { boolean result = ms.inboundRoutes().deleteRoute("inbound route id"); System.out.println(result); } catch (MailerSendException e) { e.printStackTrace(); } } ``` [More examples](https://github.com/mailersend/mailersend-java) ```ruby require "mailersend-ruby" ms_inbound_routes = Mailersend::InboundRouting.new ms_inbound_routes.delete_route(inbound_id: 'idofroute12412') ``` [More examples](https://github.com/mailersend/mailersend-ruby) ### Responses [#responses-4] #### Valid [#valid-4] ```http Response Code: 204 No Content ``` #### Error [#error-2] ```http Response Code: 404 Not Found ``` ## Webhook payload example [#webhook-payload-example] Once an inbound route has been added, all received emails will be logged in the "Inbound activity" page in the app and will be forwarded to a specified email address or endpoint URL. An example of inbound email forwarded to `endpoint URL`: ```json { "type": "inbound.message", "inbound_id": "your-inbound-id", "url": "https://your-webhook-url", "created_at": "2024-10-24T05:10:57.121199Z", "data": { "object": "message", "id": "6719d6e014059a29f74b16bf", "recipients": { "to": { "raw": "s1krr0oeqilgmcbnohxg@inbound.mailersend.net", "data": [ { "name": "", "email": "s1krr0oeqilgmcbnohxg@inbound.mailersend.net" } ] }, "rcptTo": [ { "email": "s1krr0oeqilgmcbnohxg@inbound.mailersend.net" } ] }, "from": { "raw": "Test User ", "name": "Test User", "email": "sender@example.com" }, "sender": { "email": "sender@example.com" }, "subject": "Test Inbound Routing", "date": "Thu, 24 Oct 2024 05:10:42 +0000", "headers": { "To": "s1krr0oeqilgmcbnohxg@inbound.mailersend.net", "Date": "Thu, 24 Oct 2024 05:10:42 +0000", "From": "Test User ", "Subject": "Test Inbound Routing", "Message-ID": "" }, "text": "Hi,\r\nTesting inbound routing payload sample.\r\n", "html": "
Hi,
Testing inbound routing payload sample.
", "raw": "Your raw message", "attachments": [], "spf_check": { "code": "+", "value": null }, "dkim_check": false, "created_at": "2024-10-24T05:10:56.000000Z" } } ``` # Sending an Email (/api/v1/email) This endpoint allows you to start sending emails through the MailerSend Email API. ## Send an email [#send-an-email] This endpoint allows you to send an asynchronous email. It returns the status of the email sent with an `x-message-id` that can be used to continuously query for the status using the Email API. Send an email using this `POST` request: ```http POST https://api.mailersend.com/v1/email ``` #### Request Body \[!toc] [#request-body-toc] ```json { "from": { "email": "hello@mailersend.com", "name": "MailerSend" }, "to": [ { "email": "john@mailersend.com", "name": "John Mailer" } ], "subject": "Hello from {{company}}!", "text": "This is just a friendly hello from your friends at {{company}}.", "html": "This is just a friendly hello from your friends at {{company}}.", "personalization": [ { "email": "john@mailersend.com", "data": { "company": "MailerSend" } } ] } ``` ```php use MailerSend\MailerSend; use MailerSend\Helpers\Builder\Recipient; use MailerSend\Helpers\Builder\EmailParams; $mailersend = new MailerSend(); $recipients = [ new Recipient('your@client.com', 'Your Client'), ]; $emailParams = (new EmailParams()) ->setFrom('your@domain.com') ->setFromName('Your Name') ->setRecipients($recipients) ->setSubject('Subject') ->setHtml('This is the HTML content') ->setText('This is the text content') ->setReplyTo('reply to') ->setReplyToName('reply to name'); $mailersend->email->send($emailParams); ``` [More examples](https://github.com/mailersend/mailersend-php) ```javascript import 'dotenv/config'; import { MailerSend, EmailParams, Sender, Recipient } from "mailersend"; const mailerSend = new MailerSend({ apiKey: process.env.API_KEY, }); const sentFrom = new Sender("you@yourdomain.com", "Your name"); const recipients = [ new Recipient("your@client.com", "Your Client") ]; const emailParams = new EmailParams() .setFrom(sentFrom) .setTo(recipients) .setReplyTo(sentFrom) .setSubject("This is a Subject") .setHtml("This is the HTML content") .setText("This is the text content"); await mailerSend.email.send(emailParams); ``` [More examples](https://github.com/mailersend/mailersend-nodejs) ```python from mailersend import MailerSendClient, EmailBuilder ms = MailerSendClient() email = (EmailBuilder() .from_email("sender@domain.com", "Your Name") .to_many([{"email": "recipient@domain.com", "name": "Recipient"}]) .subject("Hello from MailerSend!") .html("

Hello World!

") .text("Hello World!") .build()) response = ms.emails.send(email) print(f"Email sent: {response.message_id}") ``` [More examples](https://github.com/mailersend/mailersend-python)
```go package main import ( "context" "fmt" "os" "time" "github.com/mailersend/mailersend-go" ) func main() { // Create an instance of the mailersend client ms := mailersend.NewMailersend(os.Getenv("MAILERSEND_API_KEY")) ctx := context.Background() ctx, cancel := context.WithTimeout(ctx, 5*time.Second) defer cancel() subject := "Subject" text := "This is the text content" html := "

This is the HTML content

" from := mailersend.From{ Name: "Your Name", Email: "your@domain.com", } recipients := []mailersend.Recipient{ { Name: "Your Client", Email: "your@client.com", }, } // Send in 5 minute sendAt := time.Now().Add(time.Minute * 5).Unix() tags := []string{"foo", "bar"} message := ms.Email.NewMessage() message.SetFrom(from) message.SetRecipients(recipients) message.SetSubject(subject) message.SetHTML(html) message.SetText(text) message.SetTags(tags) message.SetSendAt(sendAt) message.SetInReplyTo("client-id") res, _ := ms.Email.Send(ctx, message) fmt.Printf(res.Header.Get("x-message-id")) } ``` [More examples](https://github.com/mailersend/mailersend-go)
```java import com.mailersend.sdk.Email; import com.mailersend.sdk.MailerSend; import com.mailersend.sdk.MailerSendResponse; import com.mailersend.sdk.exceptions.MailerSendException; public void sendEmail() { Email email = new Email(); email.setFrom("name", "your email"); email.addRecipient("name", "your@recipient.com"); // you can also add multiple recipients by calling addRecipient again email.addRecipient("name 2", "your@recipient2.com"); // there's also a recipient object you can use Recipient recipient = new Recipient("name", "your@recipient3.com"); email.addRecipient(recipient); email.setSubject("Email subject"); email.setPlain("This is the text content"); email.setHtml("

This is the HTML content

"); MailerSend ms = new MailerSend(); ms.setToken("Your API token"); try { MailerSendResponse response = ms.emails().send(email); System.out.println(response.messageId); } catch (MailerSendException e) { e.printStackTrace(); } } ``` [More examples](https://github.com/mailersend/mailersend-java)
```ruby require "mailersend-ruby" ms_client = Mailersend::Client.new('your_mailersend_token') # Intialize the email class ms_email = Mailersend::Email.new(ms_client) # Add parameters ms_email.add_recipients("email" => "ron@parksandrec.com", "name" => "Ron") ms_email.add_recipients("email" => "leslie@parksandrec.com", "name" => "Leslie") ms_email.add_from("email" => "april@parksandrec.com", "name" => "April") ms_email.add_subject("Time") ms_email.add_text("Time is money, money is power, power is pizza, and pizza is knowledge. Let's go.") ms_email.add_html("Time is money, money is power, power is pizza, and pizza is knowledge. Let's go.") # Send the email ms_email.send ``` [More examples](https://github.com/mailersend/mailersend-ruby)
#### Request parameters \[!toc] [#request-parameters-toc] *JSON parameters are provided in dot notation* | JSON parameter | Type | Required | Limitations | Details | | --------------------------- | ----------------- | -------- | --------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `from` | `object` | yes \* | | Not required if `template_id` is present and template has default sender set. | | `from.email` | `string` | yes \* | Must be a verified domain or a subdomain from a verified domain . | Not required if `template_id` is present and template has default sender set. Valid email address as per RFC 2821. | | `from.name` | `string` | no | | `from.email` will be used if not provided or, if `template_id` is present with default values, the default subject from that will be used. | | `to` | `object[]` | yes | Min `1`, max `50` | | | `to.*.email` | `string` | yes | | Valid email address as per RFC 2821. | | `to.*.name` | `string` | no | | The name of the recipient. May not contain `;` or `,`. | | `cc` | `object[]` | no | Max 10 | | | `cc.*.email` | `string` | yes | | Valid email address as per RFC 2821. | | `cc.*.name` | `string` | no | | The name of the CC recipient. May not contain `;` or `,`. | | `bcc` | `object[]` | no | Max 10 | | | `bcc.*.email` | `string` | yes | | Valid email address as per RFC 2821. | | `bcc.*.name` | `string` | no | | The name of the BCC recipient. May not contain `;` or `,`. | | `reply_to` | `object` | no | | | | `reply_to.email` | `string` | no | | Valid email address as per RFC 2821. | | `reply_to.name` | `string` | no | | | | `subject` | `string` | yes \* | Max 998 | Not required if `template_id` is present and template has default subject set. | | `text` | `string` | yes \* | Max size of 2 MB. | Email represented in a text (`text/plain`) format. \* Only required if there's no `html` or `template_id` present. | | `html` | `string` | yes \* | Max size of 2 MB. | Email represented in HTML (`text/html`) format. \* Only required if there's no `text` or `template_id` present. | | `attachments` | `object[]` | no | | | | `attachments.*.content` | `string` | yes | Max size of 25MB. *After decoding Base64* | Base64 encoded content of the attachment. | | `attachments.*.disposition` | `string` | no | Must be one of the attachment types: `inline`, `attachment` | Use `inline` to make it accessible for content. use `attachment` to normal attachments | | `attachments.*.filename` | `string` | yes | | | | `attachments.*.id` | `string` | no | Max: `256` | Can be used in content as ``. Must also set `attachments.*.disposition` as `inline`. | | `template_id` | `string` | yes \* | | \* Only required if there's no `text` or `html` present. | | `language` | `string` | no | Nullable. Must be one of the supported languages: `de`, `en`, `es`, `fr`, `it`, `lt`, `nl`, `pl`, `pt-BR` | Language code (e.g. `de`, `fr`, `pt-BR`). When set, MailerSend uses the template's published translation in that language. If no published translation exists for the requested language, the email is sent with the base template content (no error is returned). Only applied when `template_id` is also provided; ignored for raw HTML/text sends. | | `tags` | `string[]` | no | | Limit is max 5 tags. If the template used already has tags, then the request will override them. | | `tags.*` | `string` | no | Max 191 characters | | | `personalization` | `object[]` | no | | Allows using personalization in `{{var}}` syntax. Can be used in the `subject`, `html`, `text` fields. Read more about [advanced personalization](/api/v1/email/features#advanced-personalization). | | `personalization.*.email` | `string` | yes | | Email address that personalization will be applied to. Valid email address as per RFC 2821. | | `personalization.*.data` | `object[]` | yes | | Object with `key: value` pairs. Values will be added to your template using `{{key}}` syntax. | | `precedence_bulk` | `boolean` | no | | This parameter will override domain's advanced settings | | `send_at` | `integer\|string` | no | min: `now`, max: `now + 72hours` | Unix timestamp (integer) or ISO 8601 date string. **Please note that this timestamp is a minimal guarantee and that the email could be delayed due to server load.** | | `in_reply_to` | `string` | no | Max 998 characters. Valid characters: alphanumeric and `_ . @ = < > ( ~ ! # $ % ^ & * + ) - [ ]` | A Message-ID that this email is replying to. **Please note that this feature is available to paid plan accounts only.** | | `references` | `string[]` | no | | List of Message-ID's that the current email is referencing. Read more about [creating email threads](/../../guides/creating-email-threads). **Please note that this feature is available to paid plan accounts only.** | | `references.*` | `string` | yes | Valid characters: alphanumeric and `_ . @ = < > ( ~ ! # $ % ^ & * + ) - [ ]` | | | `settings` | `object` | no | | | | `settings.*` | `boolean` | yes | | Can only contain the keys: `track_clicks`, `track_opens` and `track_content` and a boolean value of `true` or `false`. | | `headers` | `object[]` | no | | **Please note that this feature is available to Professional and Enterprise accounts only** | | `headers.*.name` | `string` | yes | Must be alphanumeric which can contain `-` | | | `headers.*.value` | `string` | yes | | | | `list_unsubscribe` | `string` | no | Accepts a single value that complies with RFC 8058. Max 990 characters. | **Please note that this feature is available to Professional and Enterprise accounts only** | #### Supported file types [#supported-file-types] | File type | Extensions | | ------------------- | ------------------------------------------------------------------------------ | | Text files | .txt, .csv, .log, .css, .ics .xml | | Image files | .jpg, .jpe, .jpeg, .gif, .png, .bmp, .psd, .tif, .tiff, .svg, .indd, .ai, .eps | | Document files | .doc, .docx, .rtf, .odt, .ott, .pdf, .pub, .pages, .mobi, .epub | | Audio files | .mp3, .m4a, .m4v, .wma, .ogg, .flac, .wav, .aif, .aifc, .aiff | | Video files | .mp4, .mov, .avi, .mkv, .mpeg, .mpg, .wmv | | Spreadsheet files | .xls, .xlsx, .ods, .numbers | | Presentation files | .odp, .ppt, .pptx, .pps, .key | | Archive files | .zip, .vcf | | Email files | .eml | | Cryptographic files | .p7c, .p7m, .p7s, .pgp, .asc, .sig | #### Supported HTML tags and attributes in personalization data [#supported-html-tags-and-attributes-in-personalization-data] We allow limited HTML in personalization data to enhance content formatting. Only the following tags and attributes are supported, unsupported elements will be removed for security reasons. | Category | Supported | | ----------------- | ------------------------------------------------------------------------------------------------------------------ | | Container tags | `p` `b` `i` `strong` `em` `a` `li` `ul` `q` `blockquote` `abbr` `address` `cite` `bdo` `strike` `u` `h1` `h2` `h3` | | Self-closing tags | `br` `img` | | Attributes | `id` `class` `style` `href` `src` `width` `height` `alt` `lang` `title` `dir` `cite` `target` | If a scheduled email is sent with a template, and that template is deleted before the sending is triggered, the scheduled email will not be sent. ### Responses [#responses] #### Sending queued [#sending-queued] ```http Response Code: 202 Accepted Response Headers: content-type: text/plain; charset=utf-8 x-message-id: 5e42957d51f1d94a1070a733 Response Body: [EMPTY] ``` #### Sending paused [#sending-paused] ```http Response Code: 202 Accepted Response Headers: content-type: text/plain; charset=utf-8 x-message-id: 5e42957d51f1d94a1070a733 x-send-paused: true Response Body: [EMPTY] ``` #### Validation error [#validation-error] ```http Response Code: 422 Unprocessable Entity Response Headers: content-type: application/json ``` ```json { "message": "The given data was invalid.", "errors": { "from.email": [ "The from.email domain must be verified in your account to send emails. #MS42207" ] } } ``` *See - [Validation errors](/../../general#validation-errors)* #### Validation warning — some suppressed [#validation-warning--some-suppressed] ```http Response Code: 202 Accepted Response Headers: content-type: application/json x-message-id: 5e42957d51f1d94a1070a733 ``` ```json { "message": "There are some warnings for your request.", "warnings": [ { "type": "SOME_SUPPRESSED", "warning": "Some of the recipients have been suppressed.", "recipients": [ { "email": "suppressed@recipient.com", "name": "Suppressed Recipient", "reasons": ["blocklisted"] } ] } ] } ``` #### Validation warning — all suppressed [#validation-warning--all-suppressed] When all recipients are suppressed, the email is not sent and no `x-message-id` header is returned. ```http Response Code: 202 Accepted Response Headers: content-type: application/json ``` ```json { "message": "There are some warnings for your request.", "warnings": [ { "type": "ALL_SUPPRESSED", "message": "All of the recipients provided have been suppressed.", "recipients": [ { "email": "suppressed@recipient.com", "name": "Suppressed Recipient", "reasons": ["blocklisted"] } ] } ] } ``` ### Send encrypted emails [#send-encrypted-emails] You can use MailerSend to send encrypted messages using S/MIME or PGP. The sender encrypts messages that use these protocols. Their contents can only be viewed by recipients with the private keys required to decrypt the messages. MailerSend supports the following MIME types, which you can use to send S/MIME encrypted emails: ``` application/pkcs7-mime application/pkcs7-signature application/x-pkcs7-mime application/x-pkcs7-signature ``` MailerSend also supports the following MIME types, which you can use to send PGP-encrypted emails: ``` application/pgp-encrypted application/pgp-keys application/pgp-signature ``` ## Send bulk emails [#send-bulk-emails] This endpoint allows you to send multiple asynchronous emails. It returns the status of the request sent with a `bulk_email_id` that can be used to continuously query for the status using the Email API. To prevent long waiting periods for a response, each email validation is done after the request and then the result is stored. If there is any validation error, you can query it using the `bulk_email_id` provided. Send a bulk email using this `POST` request: ```http POST https://api.mailersend.com/v1/bulk-email ``` #### Request Body \[!toc] [#request-body-toc-1] ```json [ { "from": { "email": "hello@mailersend.com", "name": "MailerSend" }, "to": [ { "email": "john@mailersend.com", "name": "John Mailer" } ], "subject": "Hello from {{company}}!", "text": "This is just a friendly hello from your friends at {{company}}.", "html": "This is just a friendly hello from your friends at {{company}}.", "personalization": [ { "email": "john@mailersend.com", "data": { "company": "MailerSend" } } ] }, { "from": { "email": "hello@mailersend.com", "name": "MailerSend" }, "to": [ { "email": "jane@mailersend.com", "name": "Jane Mailer" } ], "subject": "Welcome to {{company}}!", "text": "This is a welcoming message from your friends at {{company}}.", "html": "This is a welcoming message from your friends at {{company}}.", "personalization": [ { "email": "jane@mailersend.com", "data": { "company": "MailerSend" } } ] } ] ``` ```php use MailerSend\MailerSend; use MailerSend\Helpers\Builder\Recipient; use MailerSend\Helpers\Builder\EmailParams; $mailersend = new MailerSend(); $recipients = [ new Recipient('your@client.com', 'Your Client'), ]; $bulkEmailParams = []; $bulkEmailParams[] = (new EmailParams()) ->setFrom('your@domain.com') ->setFromName('Your Name') ->setRecipients($recipients) ->setSubject('Subject') ->setHtml('This is the HTML content') ->setText('This is the text content'); $bulkEmailParams[] = (new EmailParams()) ->setFrom('your@domain.com') ->setFromName('Your Name') ->setRecipients($recipients) ->setSubject('Subject') ->setHtml('This is the HTML content') ->setText('This is the text content'); $mailersend->bulkEmail->send($bulkEmailParams); ``` [More examples](https://github.com/mailersend/mailersend-php) ```javascript import 'dotenv/config'; import { MailerSend, EmailParams, Sender, Recipient } from "mailersend"; const mailerSend = new MailerSend({ apiKey: process.env.API_KEY, }); const sentFrom = new Sender("your@yourdomain.com", "Your name"); const bulkEmails = []; const emailParams = new EmailParams() .setFrom(sentFrom) .setTo([ new Recipient("your@client.com", "Your Client") ]) .setSubject("This is a Subject") .setHtml("This is the HTML content") .setText("This is the text content"); bulkEmails.push(emailParams); const emailParams2 = new EmailParams() .setFrom(sentFrom) .setTo([ new Recipient("your_2@client.com", "Your Client 2") ]) .setSubject("This is a Subject 2") .setHtml("This is the HTML content 2") .setText("This is the text content 2"); bulkEmails.push(emailParams2); await mailerSend.email.sendBulk(bulkEmails); ``` [More examples](https://github.com/mailersend/mailersend-nodejs) ```python from mailersend import MailerSendClient, EmailBuilder ms = MailerSendClient() # Create individual EmailRequest objects emails = [ EmailBuilder() .from_email("sender@domain.com", "Sender") .to_many([{"email": "recipient1@domain.com", "name": "Recipient 1"}]) .subject("Bulk email 1") .html("

Hello from bulk email 1

") .text("Hello from bulk email 1") .build(), EmailBuilder() .from_email("sender@domain.com", "Sender") .to_many([{"email": "recipient2@domain.com", "name": "Recipient 2"}]) .subject("Bulk email 2") .html("

Hello from bulk email 2

") .text("Hello from bulk email 2") .build() ] response = ms.emails.send_bulk(emails) print(f"Bulk email ID: {response.bulk_email_id}") ``` [More examples](https://github.com/mailersend/mailersend-python)
```go package main import ( "context" "fmt" "log" "os" "time" "github.com/mailersend/mailersend-go" ) func main() { // Create an instance of the mailersend client ms := mailersend.NewMailersend(os.Getenv("MAILERSEND_API_KEY")) ctx := context.Background() ctx, cancel := context.WithTimeout(ctx, 5*time.Second) defer cancel() subject := "Subject" text := "This is the text content" html := "

This is the HTML content

" from := mailersend.From{ Name: "Your Name", Email: "your@domain.com", } recipients := []mailersend.Recipient{ { Name: "Your Client", Email: "your@client.com", }, } var messages []*mailersend.Message for i := range [2]int{} { msg := &mailersend.Message{ From: from, Recipients: recipients, Subject: fmt.Sprintf("%s %v", subject, i), Text: text, HTML: html, } messages = append(messages, msg) } _, _, err := ms.BulkEmail.Send(ctx, messages) if err != nil { log.Fatal(err) } } ``` [More examples](https://github.com/mailersend/mailersend-go)
```java import com.mailersend.sdk.emails.Email; import com.mailersend.sdk.MailerSend; import com.mailersend.sdk.MailerSendResponse; import com.mailersend.sdk.exceptions.MailerSendException; public void sendBulkEmails() { Email email1 = new Email(); email1.setFrom("name", "your email"); email1.addRecipient("name", "your@first-recipient.com"); email1.setSubject("Email subject 1"); email1.setPlain("This is the text content for the first email"); email1.setHtml("

This is the HTML content for the first email

"); Email email2 = new Email(); email2.setFrom("name", "your email"); email2.addRecipient("name", "your@second-recipient.com"); email2.setSubject("Email subject 2"); email2.setPlain("This is the text content for the second email"); email2.setHtml("

This is the HTML content for the second email

"); MailerSend ms = new MailerSend(); ms.setToken("Your API token"); try { String bulkSendId = ms.emails().bulkSend(new Email[] { email1, email2 }); // you can use the bulkSendId to get the status of the emails System.out.println(bulkSendId); } catch (MailerSendException e) { e.printStackTrace(); } } ``` [More examples](https://github.com/mailersend/mailersend-java)
```ruby require "mailersend-ruby" ms_client = Mailersend::Client.new('your_mailersend_token') ms_bulk_email = Mailersend::BulkEmail.new(ms_client) ms_bulk_email.messages = [ { 'from' => {"email" => "april@parksandrec.com", "name" => "April"}, 'to' => [{"email" => "ron@parksandrec.com", "name" => "Ron"}], 'subject' => "Time", 'text' => "Time is money, money is power, power is pizza, and pizza is knowledge. Let's go.", 'html' => "Time is money, money is power, power is pizza, and pizza is knowledge. Let's go.", }, { 'from' => {"email" => "april@parksandrec.com", "name" => "April"}, 'to' => [{"email" => "leslie@parksandrec.com", "name" => "Leslie"}], 'subject' => "Lorem Ipsum", 'text' => "Lorem ipsum dolor sit amet, consectetur adipiscing elit.", 'html' => "

Lorem ipsum dolor sit amet, consectetur adipiscing elit.

", } ] ms_bulk_email.send ``` [More examples](https://github.com/mailersend/mailersend-ruby)
#### Request parameters \[!toc] [#request-parameters-toc-1] *JSON parameters are provided in dot notation* | JSON parameter | Type | Required | Limitations | Details | | -------------- | ---------- | -------- | ------------------------------------------------ | ------------------------------------------------------------------------ | | `*` | `object[]` | yes | Must be an array. | Array of email objects. | | `*.*` | `object` | yes | Must be an [email](/email#send-an-email) object. | See [email](/email#send-an-email) object for detailed options available. | #### Limitations [#limitations] | Description | Limit | | ------------------------------------------------------ | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | Total size of the JSON payload | **50MB** | | Number of individual email objects in a single request | **5** for Trial plan accounts.
**500** for Hobby, Starter, Professional or Enterprise plan accounts. | | Number of recipients per email object. | See **[Email endpoint](/email#send-an-email)**. | | API requests per minute | **10** for Trial and Hobby plan accounts.
**15** for Starter plan accounts.
**30** for Professional plan accounts.
**60** for Enterprise plan accounts. | *If not mentioned, the limits are the same as for the generic Email API endpoint.* ### Responses [#responses-1] ```http Response Code: 202 Accepted Response Headers: content-type: application/json ``` ```json { "message": "The bulk email is being processed.", "bulk_email_id": "614470d1588b866d0454f3e2" } ``` ### Errors [#errors] #### Validation errors [#validation-errors] Validation errors, as well as any other issues like failed emails, are stored in the database. You can check them by calling the 'Get bulk email' endpoint. Validation errors are indexed by the order they are sent: `message.{order_index}`. #### Suppression errors [#suppression-errors] If one or more recipients specified in the messages are suppressed, similarly to the validation errors, they are stored and can be checked with the 'Get bulk email' endpoint. The suppression errors are indexed by `x-message-id`. ## Get bulk email status [#get-bulk-email-status] Get the bulk email information like validation errors, failed emails and more. Check the bulk email status using this `GET` request: ```http GET https://api.mailersend.com/v1/bulk-email/{bulk_email_id} ``` #### Request parameters \[!toc] [#request-parameters-toc-2] | URL parameter | Type | Required | Limitations | Details | | --------------- | -------- | -------- | ----------- | ------- | | `bulk_email_id` | `string` | yes | | | ```php use MailerSend\MailerSend; $mailersend = new MailerSend(); $mailersend->bulkEmail->getStatus('bulk_email_id'); ``` [More examples](https://github.com/mailersend/mailersend-php) ```javascript import 'dotenv/config'; import { MailerSend } from "mailersend"; const mailerSend = new MailerSend({ apiKey: process.env.API_KEY, }); mailerSend.email.getBulkStatus('bulk_email_id') // bulk email Id e.g 63af1fdb790d97105a090001 .then((response) => { console.log(response.body); }); ``` [More examples](https://github.com/mailersend/mailersend-nodejs) ```python from mailersend import MailerSendClient ms = MailerSendClient() response = ms.emails.get_bulk_status("bulk-email-id") print(f"Status: {response.state}") ``` [More examples](https://github.com/mailersend/mailersend-python) ```go package main import ( "context" "time" "log" "github.com/mailersend/mailersend-go" ) var APIKey = "Api Key Here" func main() { // Create an instance of the mailersend client ms := mailersend.NewMailersend(APIKey) ctx := context.Background() ctx, cancel := context.WithTimeout(ctx, 5*time.Second) defer cancel() _, _, err := ms.BulkEmail.Status(ctx, "bulk-email-id") if err != nil { log.Fatal(err) } } ``` [More examples](https://github.com/mailersend/mailersend-go) ```java import com.mailersend.sdk.emails.Email; import com.mailersend.sdk.emails.BulkSendStatus; import com.mailersend.sdk.MailerSend; import com.mailersend.sdk.MailerSendResponse; import com.mailersend.sdk.exceptions.MailerSendException; public void getBulkEmailsStatus() { MailerSend ms = new MailerSend(); ms.setToken("Your API token"); try { BulkSendStatus status = ms.emails().bulkSendStatus("bulk send id"); System.out.println(status.state); } catch (MailerSendException e) { e.printStackTrace(); } } ``` [More examples](https://github.com/mailersend/mailersend-java) ```ruby require "mailersend-ruby" ms_client = Mailersend::Client.new('your_mailersend_token') ms_bulk_email = Mailersend::BulkEmail.new(ms_client) ms_bulk_email.get_bulk_status(bulk_email_id: 'yourbulkemailid') ``` [More examples](https://github.com/mailersend/mailersend-ruby) ### Responses [#responses-2] #### Valid [#valid] ```http Response Code: 200 OK Response Headers: content-type: application/json ``` ```json { "data": { "id": "614470d1588b866d0454f3e2", "state": "completed", "total_recipients_count": 1, "suppressed_recipients_count": 0, "suppressed_recipients": null, "validation_errors_count": 0, "validation_errors": null, "messages_id": "['61487a14608b1d0b4d506633']", "created_at": "2021-09-17T10:41:21.892000Z", "updated_at": "2021-09-17T10:41:23.684000Z" } } ``` #### Invalid [#invalid] ```http Response Code: 404 Not Found ``` # Scheduled messages (/api/v1/email/message-schedules) Use the `GET` request to retrieve information about scheduled messages. Scheduled messages are stored and queued until the Unix timestamp is reached. Please note that this timestamp is a minimal guarantee and that the email could be delayed due to server load. ## Get list of scheduled messages [#get-list-of-scheduled-messages] Get information on scheduled messages, such as subject, time of creation, and time of sending, with this `GET` request: ```http GET https://api.mailersend.com/v1/message-schedules ``` #### Request parameters \[!toc] [#request-parameters-toc] *JSON parameters are provided in dot notation* | URL parameter | Type | Required | Limitations | Details | | ------------- | -------- | -------- | --------------------- | -------------------------------------- | | `domain_id` | `string` | no | | | | `status` | `string` | no | | Statuses: `scheduled`, `sent`, `error` | | `page` | `int` | no | | | | `limit` | `int` | no | Min: `10`, Max: `100` | Default: `25` | ```php use MailerSend\MailerSend; use \MailerSend\Common\Constants; $mailersend = new MailerSend(); $mailersend->scheduleMessages->getAll( 'domain_id', Constants::STATUS_SCHEDULED, $page = 3, $limit = 100 ) ``` [More examples](https://github.com/mailersend/mailersend-php) ```javascript import 'dotenv/config'; import { MailerSend} from "mailersend"; const mailerSend = new MailerSend({ apiKey: process.env.API_KEY, }); mailerSend.email.schedule.list() .then((response) => console.log(response.body)) .catch((error) => console.log(error.body)); ``` [More examples](https://github.com/mailersend/mailersend-nodejs) ```python from mailersend import MailerSendClient, SchedulesBuilder ms = MailerSendClient() request = (SchedulesBuilder() .domain_id("domain-id") .build_list_request()) response = ms.schedules.list_schedules(request) ``` [More examples](https://github.com/mailersend/mailersend-python) ```go package main import ( "context" "log" "github.com/mailersend/mailersend-go" ) var APIKey = "Api Key Here" func main() { // Create an instance of the mailersend client ms := mailersend.NewMailersend(APIKey) ctx := context.TODO() domainID := "domain-id" _, _, err := ms.ScheduleMessage.List(ctx, domainID) if err != nil { log.Fatal(err) } } ``` [More examples](https://github.com/mailersend/mailersend-go) ```java import com.mailersend.sdk.MailerSend; import com.mailersend.sdk.exceptions.MailerSendException; import com.mailersend.sdk.scheduledmessages.ScheduledMessagesList; import com.mailersend.sdk.scheduledmessages.ScheduledMessage; public void getScheduledMessages() { MailerSend ms = new MailerSend(); ms.setToken("Your API token"); try { ScheduledMessagesList messages = ms.scheduledmessages().getScheduledMessages(); for (ScheduledMessage message : messages.scheduledMessages) { System.out.println(message.id); System.out.println(message.subject); } } catch (MailerSendException e) { e.printStackTrace(); } } ``` [More examples](https://github.com/mailersend/mailersend-java) ```ruby require "mailersend-ruby" ms_client = Mailersend::Client.new('your_mailersend_token') ms_scheduled_messages = Mailersend::ScheduledMessages.new(ms_client) ms_scheduled_messages.get_list ``` [More examples](https://github.com/mailersend/mailersend-ruby) ### Responses [#responses] #### Valid [#valid] ```http Response Code: 200 OK Response Headers: content-type: application/json ``` ```json { "data": [ { "message_id": "61e01c6a7f97913a17075262", "subject": "Hello from Company", "send_at": "2022-01-01T12:00:00.000000Z", "status": "scheduled", "status_message": null, "created_at": "2022-01-17:00:00.000000Z" }, ... ] } ``` #### Error [#error] ```http Response Code: 422 Unprocessable Entity ``` *See - [Validation errors](/../../general#validation-errors)* ## Get a single scheduled message [#get-a-single-scheduled-message] Get information about a specific scheduled message, like its subject, creation date, sending date and domain, with this `GET` request: ```http GET https://api.mailersend.com/v1/message-schedules/{message_id} ``` #### Request parameters \[!toc] [#request-parameters-toc-1] | URL parameter | Type | Required | Limitations | Details | | ------------- | ------ | -------- | ----------- | ---------------------------------------------------------------------------------------- | | `message_id` | string | yes | | Message ID from the Send an email's response headers or Get scheduled messages response. | ```php use MailerSend\MailerSend; $mailersend = new MailerSend(); $mailersend->scheduleMessages->find('message_id'); ``` [More examples](https://github.com/mailersend/mailersend-php) ```javascript import 'dotenv/config'; import { MailerSend} from "mailersend"; const mailerSend = new MailerSend({ apiKey: process.env.API_KEY, }); mailerSend.email.schedule.single("message_id") .then((response) => console.log(response.body)) .catch((error) => console.log(error.body)); ``` [More examples](https://github.com/mailersend/mailersend-nodejs) ```python from mailersend import MailerSendClient, SchedulesBuilder ms = MailerSendClient() request = (SchedulesBuilder() .message_id("scheduled-id") .build_get_request()) response = ms.schedules.get_schedule(request) ``` [More examples](https://github.com/mailersend/mailersend-python) ```go package main import ( "context" "log" "github.com/mailersend/mailersend-go" ) var APIKey = "Api Key Here" func main() { // Create an instance of the mailersend client ms := mailersend.NewMailersend(APIKey) ctx := context.TODO() messageID := "message-id" _, _, err := ms.ScheduleMessage.Get(ctx, messageID) if err != nil { log.Fatal(err) } } ``` [More examples](https://github.com/mailersend/mailersend-go) ```java import com.mailersend.sdk.MailerSend; import com.mailersend.sdk.exceptions.MailerSendException; import com.mailersend.sdk.scheduledmessages.ScheduledMessage; public void getScheduledMessage() { MailerSend ms = new MailerSend(); ms.setToken("Your API token"); try { ScheduledMessage message = ms.scheduledmessages().getScheduledMessage("message id"); System.out.println(message.id); System.out.println(message.subject); } catch (MailerSendException e) { e.printStackTrace(); } } ``` [More examples](https://github.com/mailersend/mailersend-java) ```ruby require "mailersend-ruby" ms_client = Mailersend::Client.new('your_mailersend_token') ms_scheduled_messages = Mailersend::ScheduledMessages.new(ms_client) ms_scheduled_messages.get_single(message_id: 'mess11454') ``` [More examples](https://github.com/mailersend/mailersend-ruby) ### Responses [#responses-1] #### Valid [#valid-1] ```http Response Code: 200 OK Response Headers: content-type: application/json ``` ```json { "data": { "message_id": "61e01f471053b349a5478a52", "subject": "Hello from Company", "send_at": "2022-01-01T12:00:00.000000Z", "status": "scheduled", "status_message": null, "created_at": "2022-01-01T17:00:00.000000Z", "domain": { "id": "7z3m5jgrogdpyo6n", "name": "mailersend.com", "created_at": "2022-01-01T12:00:00.000000Z", "updated_at": "2022-01-01T12:00:00.000000Z" }, "message": { "id": "61e01f471053b349a5478a52", "created_at": "2022-01-01T12:00:00.000000Z", "updated_at": "2022-01-01T12:00:00.000000Z" } } } ``` #### Error [#error-1] ```http Response Code: 404 Not Found ``` *See - [Validation errors](/../../general#validation-errors)* ## Delete a scheduled message [#delete-a-scheduled-message] Delete a scheduled message with this `DELETE` request: ```http DELETE https://api.mailersend.com/v1/message-schedules/{message_id} ``` #### Request parameters \[!toc] [#request-parameters-toc-2] | URL parameter | Type | Required | Limitations | Details | | ------------- | ------ | -------- | ---------------------------------------------------------------------------- | ------- | | `message_id` | string | yes | A scheduled message can be deleted up to 10 minutes before the sending time. | | ```php use MailerSend\MailerSend; use \MailerSend\Common\Constants; $mailersend = new MailerSend(); $mailersend->scheduleMessages->delete('message_id'); ``` [More examples](https://github.com/mailersend/mailersend-php) ```javascript import 'dotenv/config'; import { MailerSend} from "mailersend"; const mailerSend = new MailerSend({ apiKey: process.env.API_KEY, }); mailerSend.email.schedule.delete("message_id") .then((response) => console.log(response.body)) .catch((error) => console.log(error.body)); ``` [More examples](https://github.com/mailersend/mailersend-nodejs) ```python from mailersend import MailerSendClient, SchedulesBuilder ms = MailerSendClient() request = (SchedulesBuilder() .message_id("scheduled-id") .build_delete_request()) response = ms.schedules.delete_schedule(request) ``` [More examples](https://github.com/mailersend/mailersend-python) ```go package main import ( "context" "log" "github.com/mailersend/mailersend-go" ) var APIKey = "Api Key Here" func main() { // Create an instance of the mailersend client ms := mailersend.NewMailersend(APIKey) ctx := context.TODO() messageID := "message-id" _, err := ms.ScheduleMessage.Delete(ctx, messageID) if err != nil { log.Fatal(err) } } ``` [More examples](https://github.com/mailersend/mailersend-go) ```java import com.mailersend.sdk.MailerSend; import com.mailersend.sdk.exceptions.MailerSendException; import com.mailersend.sdk.scheduledmessages.ScheduledMessage; public void deleteScheduledMessage() { MailerSend ms = new MailerSend(); ms.setToken("Your API token"); try { boolean result = ms.scheduledmessages().deleteScheduledMessage("message id"); System.out.println(result); } catch (MailerSendException e) { e.printStackTrace(); } } ``` [More examples](https://github.com/mailersend/mailersend-java) ```ruby require "mailersend-ruby" ms_client = Mailersend::Client.new('your_mailersend_token') ms_scheduled_messages = Mailersend::ScheduledMessages.new(ms_client) ms_scheduled_messages.delete(message_id: 'mess11454') ``` [More examples](https://github.com/mailersend/mailersend-ruby) ### Responses [#responses-2] #### Valid [#valid-2] ```http Response Code: 204 OK Response Body: [EMPTY] ``` #### Error [#error-2] ```http Response Code: 404 Not Found ``` # Messages (/api/v1/email/messages) Messages are resources that are created from a single Email API request. ## Get a list of messages [#get-a-list-of-messages] Retrieve a information about all messaged with this `GET` request. ### Request [#request] ```http GET https://api.mailersend.com/v1/messages ``` #### Request parameters \[!toc] [#request-parameters-toc] | Query parameter | Type | Required | Limitations | Details | | --------------- | -------- | -------- | --------------------- | ----------------- | | `page` | `int` | no | | | | `limit` | `int` | no | Min: `10`, Max: `100` | Default: `25` | | `domain_id` | `string` | no | | Filter by domain. | ```php use MailerSend\MailerSend; $mailersend = new MailerSend(['api_key' => 'key']); $mailersend->messages->get($limit = 100, $page = 3, $domainId = 'domain_id'); ``` [More examples](https://github.com/mailersend/mailersend-php) ```javascript import 'dotenv/config'; import { MailerSend} from "mailersend"; const mailerSend = new MailerSend({ apiKey: process.env.API_KEY, }); mailerSend.email.message.list() .then((response) => console.log(response.body)) .catch((error) => console.log(error.body)); ``` [More examples](https://github.com/mailersend/mailersend-nodejs) ```python from mailersend import MailerSendClient, MessagesBuilder ms = MailerSendClient() request = (MessagesBuilder() .build_list_request()) response = ms.messages.list_messages(request) ``` [More examples](https://github.com/mailersend/mailersend-python) ```go package main import ( "context" "log" "time" "github.com/mailersend/mailersend-go" ) var APIKey = "Api Key Here" func main() { // Create an instance of the mailersend client ms := mailersend.NewMailersend(APIKey) ctx := context.Background() ctx, cancel := context.WithTimeout(ctx, 5*time.Second) defer cancel() options := &mailersend.ListMessageOptions{ Page: 1, Limit: 25, } _, _, err := ms.Message.List(ctx, options) if err != nil { log.Fatal(err) } } ``` [More examples](https://github.com/mailersend/mailersend-go) ```java import com.mailersend.sdk.MailerSend; import com.mailersend.sdk.exceptions.MailerSendException; import com.mailersend.sdk.messages.Message; import com.mailersend.sdk.messages.MessagesList; public void MessagesList() { MailerSend ms = new MailerSend(); ms.setToken("token"); try { MessagesList list = ms.messages().getMessages(); for (MessageListItem message : list.messages) { System.out.println(message.id); System.out.println(message.createdAt.toString()); } } catch (MailerSendException e) { e.printStackTrace(); } } ``` [More examples](https://github.com/mailersend/mailersend-java) ```ruby require "mailersend-ruby" ms_messages = Mailersend::Messages.new ms_messages.list(page: 1, limit: 10) ``` [More examples](https://github.com/mailersend/mailersend-ruby) ### Responses [#responses] #### Valid [#valid] ```http Response Code: 200 OK Response Headers: content-type: application/json ``` ```json { "data": [ { "id": "5ee0b182b251345e407c935a", "created_at": "2020-06-10T10:10:10.377000Z", "updated_at": "2020-06-10T10:10:10.377000Z" }, { "id": "5ee0b182b251345e407c935c", "created_at": "2020-06-10T10:10:10.385000Z", "updated_at": "2020-06-10T10:10:10.385000Z" }, { "id": "5ee0b182b251345e407c935d", "created_at": "2020-06-10T10:10:10.386000Z", "updated_at": "2020-06-10T10:10:10.386000Z" }, { "id": "5ee0b182b251345e407c935e", "created_at": "2020-06-10T10:10:10.388000Z", "updated_at": "2020-06-10T10:10:10.388000Z" } ], "links": { "first": "https:\/\/www.mailersend.io\/api\/v1\/messages?page=1", "last": "https:\/\/www.mailersend.io\/api\/v1\/messages?page=1", "prev": null, "next": null }, "meta": { "current_page": 1, "from": 1, "last_page": 1, "path": "https:\/\/www.mailersend.io\/api\/v1\/messages", "per_page": 25, "to": 4, "total": 4 } } ``` #### Error [#error] ```http Response Code: 422 Unprocessable Entity ``` *See - [Validation errors](/../../general#validation-errors)* ## Get information for a single message [#get-information-for-a-single-message] #### Overview [#overview] Retrieve information for a single message with this `GET` request. ### Request [#request-1] ```http GET https://api.mailersend.com/v1/messages/{message_id} ``` #### Request parameters \[!toc] [#request-parameters-toc-1] | URL parameter | Type | Required | Limitations | Details | | ------------- | -------- | -------- | ----------- | ------- | | `message_id` | `string` | yes | | | ```php use MailerSend\MailerSend; $mailersend = new MailerSend(['api_key' => 'key']); $mailersend->messages->find('message_id'); ``` [More examples](https://github.com/mailersend/mailersend-php) ```javascript import 'dotenv/config'; import { MailerSend} from "mailersend"; const mailerSend = new MailerSend({ apiKey: process.env.API_KEY, }); mailerSend.email.message.single("message_id") .then((response) => console.log(response.body)) .catch((error) => console.log(error.body)); ``` [More examples](https://github.com/mailersend/mailersend-nodejs) ```python from mailersend import MailerSendClient, MessagesBuilder ms = MailerSendClient() request = (MessagesBuilder() .message_id("message-id") .build_get_request()) response = ms.messages.get_message(request) ``` [More examples](https://github.com/mailersend/mailersend-python) ```go package main import ( "context" "log" "time" "github.com/mailersend/mailersend-go" ) var APIKey = "Api Key Here" func main() { // Create an instance of the mailersend client ms := mailersend.NewMailersend(APIKey) ctx := context.Background() ctx, cancel := context.WithTimeout(ctx, 5*time.Second) defer cancel() messageID := "message-id" _, _, err := ms.Message.Get(ctx, messageID) if err != nil { log.Fatal(err) } } ``` [More examples](https://github.com/mailersend/mailersend-go) ```java import com.mailersend.sdk.MailerSend; import com.mailersend.sdk.exceptions.MailerSendException; import com.mailersend.sdk.messages.Message; import com.mailersend.sdk.messages.MessagesListItem; public void SingleMessage() { MailerSend ms = new MailerSend(); ms.setToken("token"); try { Message message = ms.messages().getMessage("message id"); System.out.println(message.id); System.out.println(message.createdAt.toString()); System.out.println(message.domain.name); } catch (MailerSendException e) { e.printStackTrace(); } } ``` [More examples](https://github.com/mailersend/mailersend-java) ```ruby require "mailersend-ruby" ms_messages = Mailersend::Messages.new ms_messages.single(message_id: "mess11454") ``` [More examples](https://github.com/mailersend/mailersend-ruby) ### Responses [#responses-1] #### Valid [#valid-1] | Response key | Type | Details | | --------------- | ---------- | ----------------------------------------------------------------- | | `data.emails.*` | `object[]` | Will include `email` data if it has been created in the database. | | `data.domain.*` | `object` | Includes data for a `domain` that is attached to the message. | ```http Response Code: 200 OK Response Headers: content-type: application/json ``` ```json { "data": { "id": "5ee0b183b251345e407c936a", "created_at": "2020-06-10T10:10:11.231000Z", "updated_at": "2020-06-10T10:10:11.231000Z", "emails": [], "domain": { "id": "zo8zdo", "name": "example.net", "dkim": true, "spf": true, "mx": false, "tracking": false, "is_verified": true, "is_cname_verified": false, "is_dns_active": true, "is_cname_active": false, "is_tracking_allowed": false, "has_not_queued_messages": true, "not_queued_messages_count": 1, "domain_settings": { "send_paused": false, "track_clicks": true, "track_opens": true, "track_unsubscribe": true, "track_unsubscribe_html": "

Click here to unsubscribe<\/a><\/p>", "track_unsubscribe_plain": "Click here to unsubscribe: {{unsubscribe}}", "track_content": true, "custom_tracking_enabled": false, "custom_tracking_subdomain": "email" }, "created_at": "2020-06-10 10:10:11", "updated_at": "2020-06-10 10:10:11" } } } ``` #### Error [#error-1] ```http Response Code: 404 Not Found ``` # Recipients (/api/v1/email/recipients) Fetch the email addresses of recipients and other relevant information. ## Get recipients [#get-recipients] Retrieve the email addresses of recipients using this `GET` request: ```http GET https://api.mailersend.com/v1/recipients ``` #### Request parameters \[!toc] [#request-parameters-toc] | Query parameter | Type | Required | Limitations | Details | | --------------- | -------- | -------- | --------------------- | ------------- | | `domain_id` | `string` | no | | | | `page` | `int` | no | | | | `limit` | `int` | no | Min: `10`, Max: `100` | Default: `25` | ```php use MailerSend\MailerSend; $mailersend = new MailerSend(['api_key' => 'key']); $mailersend->recipients->get(null, $limit = 100, $page = 3); // Or for a specific domain $mailersend->recipients->get('domain_id', $limit = 100, $page = 3); ``` [More examples](https://github.com/mailersend/mailersend-php) ```javascript import 'dotenv/config'; import { MailerSend } from "mailersend"; const mailerSend = new MailerSend({ apiKey: process.env.API_KEY, }); mailerSend.email.recipient.list({ domain_id: "domain_id", limit: 10, }) .then((response) => console.log(response.body)) .catch((error) => console.log(error.body)); ``` [More examples](https://github.com/mailersend/mailersend-nodejs) ```python from mailersend import MailerSendClient, RecipientsBuilder ms = MailerSendClient() request = (RecipientsBuilder() .domain_id("domain-id") .build_recipients_list_request()) response = ms.recipients.list_recipients(request) ``` [More examples](https://github.com/mailersend/mailersend-python) ```go package main import ( "context" "log" "time" "github.com/mailersend/mailersend-go" ) var APIKey = "Api Key Here" func main() { // Create an instance of the mailersend client ms := mailersend.NewMailersend(APIKey) ctx := context.Background() ctx, cancel := context.WithTimeout(ctx, 5*time.Second) defer cancel() options := &mailersend.ListRecipientOptions{ //DomainID: domainID, Page: 1, Limit: 25, } _, _, err := ms.Recipient.List(ctx, options) if err != nil { log.Fatal(err) } } ``` [More examples](https://github.com/mailersend/mailersend-go) ```java import com.mailersend.sdk.MailerSend; import com.mailersend.sdk.exceptions.MailerSendException; import com.mailersend.sdk.util.ApiRecipient; import com.mailersend.sdk.util.ApiRecipientsList; public void GetRecipients() { MailerSend ms = new MailerSend(); ms.setToken("mailersend token"); try { ApiRecipientsList list = ms.recipients().getRecipients(); for (ApiRecipient recipient : list.recipients) { System.out.println(recipient.id); System.out.println(recipient.email); } } catch (MailerSendException e) { e.printStackTrace(); } } ``` [More examples](https://github.com/mailersend/mailersend-java) ```ruby require "mailersend-ruby" ms_recipients = Mailersend::Recipients.new ms_recipients.list(page: 1, limit: 10) ``` [More examples](https://github.com/mailersend/mailersend-ruby) ### Responses [#responses] #### Valid [#valid] ```http Response Code: 200 OK Response Headers: content-type: application/json ``` ```json { "data": [ { "id": "5ee0b174b251345e407c92dc", "email": "dsanford@example.net", "created_at": "2020-06-10 10:09:56", "updated_at": "2020-06-10 10:09:56", "deleted_at": "" }, { "id": "5ee0b174b251345e407c92dd", "email": "konopelski.nina@example.com", "created_at": "2020-06-10 10:09:56", "updated_at": "2020-06-10 10:09:56", "deleted_at": "" }, { "id": "5ee0b174b251345e407c92de", "email": "hester.howe@example.net", "created_at": "2020-06-10 10:09:56", "updated_at": "2020-06-10 10:09:56", "deleted_at": "" } ], "links": { "first": "https:\/\/www.mailersend.io\/api\/v1\/recipients?page=1", "last": "https:\/\/www.mailersend.io\/api\/v1\/recipients?page=1", "prev": null, "next": null }, "meta": { "current_page": 1, "from": 1, "last_page": 1, "path": "https:\/\/www.mailersend.io\/api\/v1\/recipients", "per_page": 25, "to": 3, "total": 3 } } ``` #### Error [#error] ```http Response Code: 422 Unprocessable Entity ``` *See - [Validation errors](/../../general#validation-errors)* ## Get a single recipient [#get-a-single-recipient] Retrieve the information of a single recipient and its domain using this `GET` request: ```http GET https://api.mailersend.com/v1/recipients/{recipient_id} ``` #### Request parameters \[!toc] [#request-parameters-toc-1] | URL parameter | Type | Required | Limitations | Details | | -------------- | -------- | -------- | ----------- | ------- | | `recipient_id` | `string` | yes | | | ```php use MailerSend\MailerSend; $mailersend = new MailerSend(['api_key' => 'key']); $mailersend->recipients->find('recipient_id'); ``` [More examples](https://github.com/mailersend/mailersend-php) ```javascript import 'dotenv/config'; import { MailerSend} from "mailersend"; const mailerSend = new MailerSend({ apiKey: process.env.API_KEY, }); mailerSend.email.recipient.single("recipient_id") .then((response) => console.log(response.body)) .catch((error) => console.log(error.body)); ``` [More examples](https://github.com/mailersend/mailersend-nodejs) ```python from mailersend import MailerSendClient, RecipientsBuilder ms = MailerSendClient() request = (RecipientsBuilder() .recipient_id("recipient-id") .build_recipient_get_request()) response = ms.recipients.get_recipient(request) ``` [More examples](https://github.com/mailersend/mailersend-python) ```go package main import ( "context" "log" "time" "github.com/mailersend/mailersend-go" ) var APIKey = "Api Key Here" func main() { // Create an instance of the mailersend client ms := mailersend.NewMailersend(APIKey) ctx := context.Background() ctx, cancel := context.WithTimeout(ctx, 5*time.Second) defer cancel() recipientID := "recipient-id" _, _, err := ms.Recipient.Get(ctx, recipientID) if err != nil { log.Fatal(err) } } ``` [More examples](https://github.com/mailersend/mailersend-go) ```java import com.mailersend.sdk.MailerSend; import com.mailersend.sdk.exceptions.MailerSendException; import com.mailersend.sdk.recipients.Recipient; public void GetSingleRecipient() { MailerSend ms = new MailerSend(); ms.setToken("mailersend token"); try { Recipient recipient = ms.recipients().getRecipient("recipient id"); System.out.println(recipient.email); } catch (MailerSendException e) { e.printStackTrace(); } } ``` [More examples](https://github.com/mailersend/mailersend-java) ```ruby require "mailersend-ruby" ms_recipients = Mailersend::Recipients.new ms_recipients.single(recipient_id: "id124") ``` [More examples](https://github.com/mailersend/mailersend-ruby) ### Responses [#responses-1] #### Valid [#valid-1] ```http Response Code: 200 OK Response Headers: content-type: application/json ``` ```json { "data": { "id": "5ee0b185b251345e407c938e", "email": "hauck.sincere@example.net", "created_at": "2020-06-10 10:10:13", "updated_at": "2020-06-10 10:10:13", "deleted_at": "", "emails": [], "domain": { "id": "2j6xej", "name": "example.org", "dkim": true, "spf": true, "mx": false, "tracking": false, "is_verified": true, "is_cname_verified": false, "is_dns_active": true, "is_cname_active": false, "is_tracking_allowed": false, "has_not_queued_messages": false, "not_queued_messages_count": 0, "domain_settings": { "send_paused": false, "track_clicks": true, "track_opens": true, "track_unsubscribe": true, "track_unsubscribe_html": "

Click here to unsubscribe<\/a><\/p>", "track_unsubscribe_plain": "Click here to unsubscribe: {{unsubscribe}}", "track_content": true, "custom_tracking_enabled": false, "custom_tracking_subdomain": "email" }, "created_at": "2020-06-10 10:10:13", "updated_at": "2020-06-10 10:10:13" } } } ``` #### Error [#error-1] ```http Response Code: 404 Not Found ``` ## Delete a recipient [#delete-a-recipient] Delete the information of a single recipient and its domain using this `DELETE` request: ```http DELETE https://api.mailersend.com/v1/recipients/{recipient_id} ``` #### Request parameters \[!toc] [#request-parameters-toc-2] | URL parameter | Type | Required | Limitations | Details | | -------------- | -------- | -------- | ----------- | ------- | | `recipient_id` | `string` | yes | | | ```php use MailerSend\MailerSend; $mailersend = new MailerSend(['api_key' => 'key']); $mailersend->recipients->delete('recipient_id'); ``` [More examples](https://github.com/mailersend/mailersend-php) ```javascript import 'dotenv/config'; import { MailerSend} from "mailersend"; const mailerSend = new MailerSend({ apiKey: process.env.API_KEY, }); mailerSend.email.recipient.delete("recipient_id") .then((response) => console.log(response.body)) .catch((error) => console.log(error.body)); ``` [More examples](https://github.com/mailersend/mailersend-nodejs) ```python from mailersend import MailerSendClient, RecipientsBuilder ms = MailerSendClient() request = (RecipientsBuilder() .recipient_id("recipient-id") .build_recipient_delete_request()) response = ms.recipients.delete_recipient(request) ``` [More examples](https://github.com/mailersend/mailersend-python) ```go package main import ( "context" "log" "time" "github.com/mailersend/mailersend-go" ) var APIKey = "Api Key Here" func main() { // Create an instance of the mailersend client ms := mailersend.NewMailersend(APIKey) ctx := context.Background() ctx, cancel := context.WithTimeout(ctx, 5*time.Second) defer cancel() recipientID := "recipient-id" _, err := ms.Recipient.Delete(ctx, recipientID) if err != nil { log.Fatal(err) } } ``` [More examples](https://github.com/mailersend/mailersend-go) ```java import com.mailersend.sdk.MailerSend; import com.mailersend.sdk.exceptions.MailerSendException; import com.mailersend.sdk.MailerSendResponse; public void DeleteRecipient() { MailerSend ms = new MailerSend(); ms.setToken("mailersend token"); try { MailerSendResponse response = ms.recipients().deleteRecipient("recipient id"); System.out.println(response.responseStatusCode); } catch (MailerSendException e) { e.printStackTrace(); } } ``` [More examples](https://github.com/mailersend/mailersend-java) ```ruby require "mailersend-ruby" ms_recipients = Mailersend::Recipients.new ms_recipients.delete(recipient_id: "id124") ``` [More examples](https://github.com/mailersend/mailersend-ruby) ### Responses [#responses-2] #### Valid [#valid-2] ```http Response Code: 204 No Content Response Body: [EMPTY] ``` #### Error [#error-2] ```http Response Code: 404 Not Found ``` ## Get recipients from a suppression list [#get-recipients-from-a-suppression-list] ### Blocklist [#blocklist] Retrieve the recipients in a blocklist of an account or domain by passing the blocklist ID with this `GET` request: ```http GET https://api.mailersend.com/v1/suppressions/blocklist ``` #### Request parameters \[!toc] [#request-parameters-toc-3] | Query parameter | Type | Required | Limitations | Details | | --------------- | -------- | -------- | --------------------- | ------------- | | `domain_id` | `string` | no | | | | `limit` | `int` | no | Min: `10`, Max: `100` | Default: `10` | | `page` | `int` | no | | | ```php use MailerSend\MailerSend; $mailersend = new MailerSend(['api_key' => 'key']); $mailersend->blocklist->getAll('domain_id', 15); ``` [More examples](https://github.com/mailersend/mailersend-php) ```javascript import 'dotenv/config'; import { BlockListType, MailerSend} from "mailersend"; const mailerSend = new MailerSend({ apiKey: process.env.API_KEY, }); mailerSend.email.recipient.blockList( { domain_id: "domain_id", }, BlockListType.BLOCK_LIST ) .then((response) => console.log(response.body)) .catch((error) => console.log(error.body)); ``` [More examples](https://github.com/mailersend/mailersend-nodejs) ```python from mailersend import MailerSendClient, RecipientsBuilder ms = MailerSendClient() request = (RecipientsBuilder() .domain_id("domain-id") .build_suppression_list_request()) response = ms.recipients.list_blocklist(request) ``` [More examples](https://github.com/mailersend/mailersend-python) ```go package main import ( "context" "log" "time" "github.com/mailersend/mailersend-go" ) var APIKey = "Api Key Here" func main() { // Create an instance of the mailersend client ms := mailersend.NewMailersend(APIKey) ctx := context.Background() ctx, cancel := context.WithTimeout(ctx, 5*time.Second) defer cancel() listOptions := &mailersend.SuppressionOptions{ DomainID: "domain-id", Page: 1, Limit: 25, } // List Block List Recipients _, _, err := ms.Suppression.ListBlockList(ctx, listOptions) if err != nil { log.Fatal(err) } // List Hard Bounces _, _, _ = ms.Suppression.ListHardBounces(ctx, listOptions) // List Spam Complaints _, _, _ = ms.Suppression.ListSpamComplaints(ctx, listOptions) // List Unsubscribes _, _, _ = ms.Suppression.ListUnsubscribes(ctx, listOptions) } ``` [More examples](https://github.com/mailersend/mailersend-go) ```java import com.mailersend.sdk.MailerSend; import com.mailersend.sdk.MailerSendResponse; import com.mailersend.sdk.exceptions.MailerSendException; import com.mailersend.sdk.recipients.BlocklistItem; import com.mailersend.sdk.recipients.BlocklistListResponse; import com.mailersend.sdk.recipients.SuppressionItem; import com.mailersend.sdk.recipients.SuppressionList; public void GetRecipientsFromSuppressionList() { MailerSend ms = new MailerSend(); ms.setToken("mailersend token"); try { BlocklistListResponse blocklist = ms.recipients().suppressions().getBlocklist(); for (BlocklistItem item : blocklist.items) { System.out.println(item.id); System.out.println(item.pattern); System.out.println(item.type); } SuppressionList hardBounces = ms.recipients().suppressions().getHardBounces(); for (SuppressionItem item : hardBounces.items) { System.out.println(item.id); System.out.println(item.recipient.email); } SuppressionList spamComplaints = ms.recipients().suppressions().getSpamComplaints(); for (SuppressionItem item : spamComplaints.items) { System.out.println(item.id); System.out.println(item.recipient.email); } SuppressionList unsubscribes = ms.recipients().suppressions().getUnsubscribes(); for (SuppressionItem item : unsubscribes.items) { System.out.println(item.id); System.out.println(item.recipient.email); } } catch (MailerSendException e) { e.printStackTrace(); } } ``` [More examples](https://github.com/mailersend/mailersend-java) ```ruby require "mailersend-ruby" ms_suppressions = Mailersend::Suppressions.new // List from Blocklist ms_suppressions.get_from_blocklist(domain_id: "xxx2241ll") // List from Hard Bounces ms_suppressions.get_hard_bounces(domain_id: "xxx2241ll") // List from Spam Complaints ms_suppressions.get_spam_complaints(domain_id: "xxx2241ll") // List from Unsubscribers ms_suppressions.get_unsubscribes(domain_id: "xxx2241ll") ``` [More examples](https://github.com/mailersend/mailersend-ruby) #### Responses [#responses-3] | Response key | Type | Details | | --------------- | ---------- | ------------------------------------------------------------------------------------------------------------------------------------------------ | | `data.*` | `object[]` | Array of recipients in the blocklist. | | `data.*.domain` | `object` | Includes data of the domain related to the blocklist. When this property is `null`, the blocklist is attached to an account instead of a domain. | #### Valid [#valid-3] ```http Response Code: 200 OK Response Headers: content-type: application/json ``` ```json { "data": [ { "id": "60f0176881bf3d1fe618daae", "type": "pattern", "pattern": ".*@example.net", "domain": { "id": "7nxe3yjmeq28vp0k", "name": "mailersend.com", "created_at": "2021-07-15T11:04:44.000000Z", "updated_at": "2021-07-15T11:04:45.000000Z" }, "created_at": "2021-07-14T07:04:01.298000Z", "updated_at": "2021-07-14T07:04:01.298000Z" } ] } ``` #### Error [#error-3] ```http Response Code: 422 Unprocessable Entity ``` *See - [Validation errors](/../../general#validation-errors)* ### Hard Bounces [#hard-bounces] Retrieve the hard bounced recipients of an account or domain by passing its ID with this `GET` request: ```http GET https://api.mailersend.com/v1/suppressions/hard-bounces ``` #### Request parameters \[!toc] [#request-parameters-toc-4] | Query parameter | Type | Required | Limitations | Details | | --------------- | -------- | -------- | --------------------- | ------------- | | `domain_id` | `string` | no | | | | `limit` | `int` | no | Min: `10`, Max: `100` | Default: `10` | | `page` | `int` | no | | | #### Responses [#responses-4] | Response key | Type | Details | | ------------------------- | ---------- | ------------------------------------- | | `data.*` | `object[]` | Array of hard bounces. | | `data.*.recipient` | `object` | Recipient related to the hard bounce. | | `data.*.recipient.domain` | `object` | Domain related to the hard bounce. | #### Valid [#valid-4] ```http Response Code: 200 OK Response Headers: content-type: application/json ``` ```json { "data": [ { "id": "60f0176881bf3d1fe618dab0", "reason": "Unknown reason", "created_at": "2021-06-29T07:04:01.298000Z", "recipient": { "id": "60f0176881bf3d1fe618daaf", "email": "test@example.com", "created_at": "2021-06-29T07:04:01.298000Z", "updated_at": "2021-06-29T07:04:01.298000Z", "deleted_at": "", "domain": { "id": "7nxe3yjmeq28vp0k", "name": "mailersend.com", "created_at": "2021-07-15T11:04:44.000000Z", "updated_at": "2021-07-15T11:04:45.000000Z" } } } ] } ``` #### Error [#error-4] ```http Response Code: 422 Unprocessable Entity ``` *See - [Validation errors](/../../general#validation-errors)* ### Spam Complaints [#spam-complaints] Retrieve the recipients who have made a spam complaint for an account or domain by passing its ID with this `GET` request: ```http GET https://api.mailersend.com/v1/suppressions/spam-complaints ``` #### Request parameters \[!toc] [#request-parameters-toc-5] | Query parameter | Type | Required | Limitations | Details | | --------------- | -------- | -------- | --------------------- | ------------- | | `domain_id` | `string` | no | | | | `limit` | `int` | no | Min: `10`, Max: `100` | Default: `10` | | `page` | `int` | no | | | ### Responses [#responses-5] | Response key | Type | Details | | ------------------------- | ---------- | ---------------------------------------- | | `data.*` | `object[]` | Array of spam complaints. | | `data.*.recipient` | `object` | Recipient related to the spam complaint. | | `data.*.recipient.domain` | `object` | Domain related to the spam complaint. | #### Valid [#valid-5] ```http Response Code: 200 OK Response Headers: content-type: application/json ``` ```json { "data": [ { "id": "60f0176981bf3d1fe618dab4", "created_at": "2021-06-29T07:04:01.298000Z", "recipient": { "id": "60f0176881bf3d1fe618dab3", "email": "pmcdermott@example.net", "created_at": "2021-06-29T07:04:01.298000Z", "updated_at": "2021-06-29T07:04:01.298000Z", "deleted_at": "", "domain": { "id": "7nxe3yjmeq28vp0k", "name": "mailersend.com", "created_at": "2021-07-15T11:04:44.000000Z", "updated_at": "2021-07-15T11:04:45.000000Z" } } } ] } ``` #### Error [#error-5] ```http Response Code: 422 Unprocessable Entity ``` *See - [Validation errors](/../../general#validation-errors)* ### Unsubscribes [#unsubscribes] Retrieve the unsubscribed recipients for an account or domain by passing its ID with this `GET` request: ```http GET https://api.mailersend.com/v1/suppressions/unsubscribes ``` #### Request parameters \[!toc] [#request-parameters-toc-6] | Query parameter | Type | Required | Limitations | Details | | --------------- | -------- | -------- | --------------------- | ------------- | | `domain_id` | `string` | no | | | | `limit` | `int` | no | Min: `10`, Max: `100` | Default: `10` | | `page` | `int` | no | | | ### Responses [#responses-6] | Response key | Type | Details | | ------------------------- | ---------- | ------------------------------------- | | `data.*` | `object[]` | Array of unsubscribes. | | `data.*.recipient` | `object` | Recipient related to the unsubscribe. | | `data.*.recipient.domain` | `object` | Domain related to the unsubscribe. | #### Valid [#valid-6] ```http Response Code: 200 OK Response Headers: content-type: application/json ``` ```json { "data": [ { "id": "60f0176881bf3d1fe618dab2", "reason": "NEVER_SIGNED", "readable_reason": "I never signed up for this mailing list", "recipient": { "id": "60f0176881bf3d1fe618dab1", "email": "taya86@example.com", "created_at": "2021-06-29T07:04:01.298000Z", "updated_at": "2021-06-29T07:04:01.298000Z", "deleted_at": "", "domain": { "id": "7nxe3yjmeq28vp0k", "name": "mailersend.com", "created_at": "2021-07-15T11:04:44.000000Z", "updated_at": "2021-07-15T11:04:45.000000Z" } }, "created_at": "2021-06-29T07:04:01.298000Z" } ] } ``` #### Error [#error-6] ```http Response Code: 422 Unprocessable Entity ``` *See - [Validation errors](/../../general#validation-errors)* ### On Hold List [#on-hold-list] Retrieve on hold recipients for an account or domain by passing its ID with this `GET` request: ```http GET https://api.mailersend.com/v1/suppressions/on-hold-list ``` #### Request parameters \[!toc] [#request-parameters-toc-7] | Query parameter | Type | Required | Limitations | Details | | --------------- | -------- | -------- | --------------------- | ------------- | | `domain_id` | `string` | no | | | | `limit` | `int` | no | Min: `10`, Max: `100` | Default: `10` | | `page` | `int` | no | | | ### Responses [#responses-7] | Response key | Type | Details | | ------------------------- | ---------- | ---------------------------------------- | | `data.*` | `object[]` | Array of on hold list. | | `data.*.recipient` | `object` | Recipient on hold. | | `data.*.recipient.domain` | `object` | Domain related to the on hold recipient. | #### Valid [#valid-7] ```http Response Code: 200 OK Response Headers: content-type: application/json ``` ```json { "data": [ { "id": "64c760a33e2db0f6340f4710", "created_at": "2023-07-15T19:22:37.579000Z", "on_hold_until": "2023-07-18T19:22:37.579000Z", "email": "shanna.fadel@example.net", "recipient": { "id": "64c760a33e2db0f6340f470f", "email": "shanna.fadel@example.net", "created_at": "2023-07-15T19:22:37.579000Z", "updated_at": "2023-07-15T19:22:37.579000Z", "deleted_at": "", "domain": { "id": "7nxe3yjmeq28vp0k", "name": "mailerlite.com", "created_at": "2023-07-31T07:18:59.000000Z", "updated_at": "2023-07-31T07:19:23.000000Z" } } } ] } ``` #### Error [#error-7] ```http Response Code: 422 Unprocessable Entity ``` *See - [Validation errors](/../../general#validation-errors)* ## Add recipients to a suppression list [#add-recipients-to-a-suppression-list] ### Blocklist [#blocklist-1] Add a recipient to a blocklist with this `POST` request: ```http POST https://api.mailersend.com/v1/suppressions/blocklist ``` #### Request Body \[!toc] [#request-body-toc] ```json { "domain_id": "83gwk2j7zqz1nxyd", "recipients": [ "test@example.com" ], "patterns": [ ".*@example.com" ] } ``` ```php use MailerSend\MailerSend; use MailerSend\Helpers\Builder\BlocklistParams; $mailersend = new MailerSend(['api_key' => 'key']); $params = (new BlocklistParams()) ->setDomainId('domain_id') ->setRecipients(['recipient_one', 'recipient_two']) ->setPatterns(['pattern_one', 'pattern_two']); $mailersend->blocklist->create($params); ``` [More examples](https://github.com/mailersend/mailersend-php) ```javascript import 'dotenv/config'; import { BlockListType, MailerSend } from "mailersend"; const mailerSend = new MailerSend({ apiKey: process.env.API_KEY, }); mailerSend.email.recipient.blockRecipients({ domain_id: 'domain_id', recipients: [ "test@example.com" ] }, BlockListType.BLOCK_LIST) .then((response) => console.log(response.body)) .catch((error) => console.log(error.body)); ``` [More examples](https://github.com/mailersend/mailersend-nodejs) ```python from mailersend import MailerSendClient, RecipientsBuilder ms = MailerSendClient() # Using specific emails request = (RecipientsBuilder() .domain_id("domain-id") .recipients(["blocked@example.com", "spam@example.com"]) .build_suppression_add_request()) response = ms.recipients.add_to_blocklist(request) ``` [More examples](https://github.com/mailersend/mailersend-python) ```go package main import ( "context" "time" "github.com/mailersend/mailersend-go" ) var APIKey = "Api Key Here" func main() { // Create an instance of the mailersend client ms := mailersend.NewMailersend(APIKey) ctx := context.Background() ctx, cancel := context.WithTimeout(ctx, 5*time.Second) defer cancel() // Add Recipient to Block List createSuppressionBlockOptions := &mailersend.CreateSuppressionBlockOptions{ DomainID: "domain-id", Recipients: []string{"test@example.com"}, Patterns: []string{".*@example.com"}, } _, _, _ = ms.Suppression.CreateBlock(ctx, createSuppressionBlockOptions) // Add Recipient to Hard Bounces createSuppressionHardBounceOptions := &mailersend.CreateSuppressionOptions{ DomainID: "domain-id", Recipients: []string{"test@example.com"}, } _, _, _ = ms.Suppression.CreateHardBounce(ctx, createSuppressionHardBounceOptions) // Add Recipient to Spam Complaints createSuppressionSpamComplaintsOptions := &mailersend.CreateSuppressionOptions{ DomainID: "domain-id", Recipients: []string{"test@example.com"}, } _, _, _ = ms.Suppression.CreateHardBounce(ctx, createSuppressionSpamComplaintsOptions) // Add Recipient to Unsubscribes createSuppressionUnsubscribesOptions := &mailersend.CreateSuppressionOptions{ DomainID: "domain-id", Recipients: []string{"test@example.com"}, } _, _, _ = ms.Suppression.CreateHardBounce(ctx, createSuppressionUnsubscribesOptions) } ``` [More examples](https://github.com/mailersend/mailersend-go) ```java import com.mailersend.sdk.MailerSend; import com.mailersend.sdk.MailerSendResponse; import com.mailersend.sdk.exceptions.MailerSendException; import com.mailersend.sdk.recipients.BlocklistItem; import com.mailersend.sdk.recipients.BlocklistListResponse; import com.mailersend.sdk.recipients.SuppressionItem; import com.mailersend.sdk.recipients.SuppressionList; public void AddRecipientsToSuppressionList() { MailerSend ms = new MailerSend(); ms.setToken("mailersend token"); try { // blocklist ms.recipients().suppressions().addBuilder().pattern(".*@example.com"); ms.recipients().suppressions().addBuilder().recipient("test@example.com"); BlocklistItem[] items = ms.recipients().suppressions().addBuilder().addToBlocklist(); for (BlocklistItem item : items) { System.out.println(item.id); } // hard bounces ms.recipients().suppressions().addBuilder().recipient("test@example.com"); ms.recipients().suppressions().addBuilder().domainId(TestHelper.domainId); SuppressionList list = ms.recipients().suppressions().addBuilder().addRecipientsToHardBounces(); for (SuppressionItem item : list.items) { System.out.println(item.id); } // spam complaints ms.recipients().suppressions().addBuilder().recipient("test@example.com"); ms.recipients().suppressions().addBuilder().domainId(TestHelper.domainId); list = ms.recipients().suppressions().addBuilder().addRecipientsToSpamComplaints(); for (SuppressionItem item : list.items) { System.out.println(item.id); } // unsubscribes ms.recipients().suppressions().addBuilder().recipient("test@example.com"); ms.recipients().suppressions().addBuilder().domainId(TestHelper.domainId); list = ms.recipients().suppressions().addBuilder().addRecipientsToUnsubscribes(); for (SuppressionItem item : list.items) { System.out.println(item.id); } } catch (MailerSendException e) { e.printStackTrace(); } } ``` [More examples](https://github.com/mailersend/mailersend-java) ```ruby require "mailersend-ruby" ms_suppressions = Mailersend::Suppressions.new // Add Recipient to Block List using recipients ms_suppressions.add_to_blocklist(domain_id: "xxx2241ll", recipients: ["blocked@client.com"]) // Add Recipient to Block List using patterns ms_suppressions.add_to_blocklist(domain_id: "xxx2241ll", patterns: ["*@client.com"]) // Add Recipient to Hard Bounces ms_suppressions.add_to_hard_bounces(domain_id: "xxx2241ll", recipients: ["bounced@client.com"]) // Add Recipient to Spam Complaints ms_suppressions.add_to_spam_complaints(domain_id: "xxx2241ll", recipients: ["bounced@client.com"]) // Add Recipient to Unsubscribes ms_suppressions.add_to_unsubscribers(domain_id: "xxx2241ll", recipients: ["bounced@client.com"]) ``` [More examples](https://github.com/mailersend/mailersend-ruby) #### Request parameters \[!toc] [#request-parameters-toc-8] *JSON parameters are provided in dot notation.* | JSON parameter | Type | Required | Limitations | Details | | -------------- | ---------- | -------- | ---------------------------------------------------------- | ------- | | `domain_id` | `string` | no | | | | `recipients[]` | `string[]` | no | If `patterns` is not defined, this property is required. | | | `recipients.*` | `string` | yes | Must be an email. | | | `patterns[]` | `string[]` | no | If `recipients` is not defined, this property is required. | | | `patterns.*` | `string` | yes | | | ### Responses [#responses-8] | Response key | Type | Details | | ------------ | ---------- | ----------------------------------- | | `data.*` | `object[]` | Array of blocklist entries created. | #### Valid [#valid-8] ```http Response Code: 201 Created Response Headers: content-type: application/json ``` ```json { "data": [ { "id": "60f198790542d97fb66dfe52", "type": "exact", "pattern": "test@example.com", "created_at": "2021-07-16T14:32:25.457000Z", "updated_at": "2021-07-16T14:32:25.457000Z" }, { "id": "60f198790542d97fb66dfe53", "type": "pattern", "pattern": ".*@example.com", "created_at": "2021-07-16T14:32:25.476000Z", "updated_at": "2021-07-16T14:32:25.476000Z" } ] } ``` #### Error [#error-8] ```http Response Code: 422 Unprocessable Entity ``` *See - [Validation errors](/../../general#validation-errors)* ### Hard Bounces [#hard-bounces-1] Add a hard bounce for one or more recipients with this `POST` request: ```http POST https://api.mailersend.com/v1/suppressions/hard-bounces ``` #### Request Body \[!toc] [#request-body-toc-1] ```json { "domain_id": "83gwk2j7zqz1nxyd", "recipients": [ "test@example.com" ] } ``` #### Request parameters \[!toc] [#request-parameters-toc-9] *JSON parameters are provided in dot notation.* | JSON parameter | Type | Required | Limitations | Details | | -------------- | ---------- | -------- | ----------------- | ------- | | `domain_id` | `string` | yes | | | | `recipients[]` | `string[]` | yes | | | | `recipients.*` | `string` | yes | Must be an email. | | ### Responses [#responses-9] | Response key | Type | Details | | ---------------------- | ---------- | ------------------------------------- | | `data.*` | `object[]` | Array of hard bounces created. | | `data.*.recipient` | `object` | Recipient related to the hard bounce. | | `data.*.domain.domain` | `object` | Domain related to the hard bounce. | #### Valid [#valid-9] ```http Response Code: 201 Created Response Headers: content-type: application/json ``` ```json { "data": [ { "id": "60f1a0195c14080bbc606293", "reason": null, "created_at": "2021-07-16T15:04:57.939000Z", "recipient": { "id": "60f1a0195c14080bbc606292", "email": "test@example.com", "created_at": "2021-07-16T15:04:57.888000Z", "updated_at": "2021-07-16T15:04:57.907000Z", "deleted_at": "", "domain": { "id": "7nxe3yjmeq28vp0k", "name": "mailersend.com", "created_at": "2021-07-15T11:04:44.000000Z", "updated_at": "2021-07-15T11:04:45.000000Z" } } } ] } ``` #### Error [#error-9] ```http Response Code: 422 Unprocessable Entity ``` *See - [Validation errors](/../../general#validation-errors)* ### Spam Complaints [#spam-complaints-1] Add a spam complaint for one or more recipients with this `POST` request: ```http POST https://api.mailersend.com/v1/suppressions/spam-complaints ``` #### Request Body \[!toc] [#request-body-toc-2] ```json { "domain_id": "83gwk2j7zqz1nxyd", "recipients": [ "test@example.com" ] } ``` #### Request parameters \[!toc] [#request-parameters-toc-10] *JSON parameters are provided in dot notation.* | JSON parameter | Type | Required | Limitations | Details | | -------------- | ---------- | -------- | ----------------- | ------- | | `domain_id` | `string` | yes | | | | `recipients[]` | `string[]` | yes | | | | `recipients.*` | `string` | yes | Must be an email. | | ### Responses [#responses-10] | Response key | Type | Details | | ------------------------- | ---------- | ---------------------------------------- | | `data.*` | `object[]` | Array of spam complaints created. | | `data.*.recipient` | `object` | Recipient related to the spam complaint. | | `data.*.recipient.domain` | `object` | Domain related to the spam complaint. | #### Valid [#valid-10] ```http Response Code: 201 Created Response Headers: content-type: application/json ``` ```json { "data": [ { "id": "60f1a9fa33d68f023f2d3972", "created_at": "2021-07-16T15:47:06.280000Z", "recipient": { "id": "60f1a0195c14080bbc606292", "email": "test@example.com", "created_at": "2021-07-16T15:04:57.888000Z", "updated_at": "2021-07-16T15:47:06.244000Z", "deleted_at": "", "domain": { "id": "7nxe3yjmeq28vp0k", "name": "mailersend.com", "created_at": "2021-07-15T11:04:44.000000Z", "updated_at": "2021-07-15T11:04:45.000000Z" } } } ] } ``` #### Error [#error-10] ```http Response Code: 422 Unprocessable Entity ``` *See - [Validation errors](/../../general#validation-errors)* ### Unsubscribes [#unsubscribes-1] Set one or more recipients as unsubscribed with this `POST` request: ```http POST https://api.mailersend.com/v1/suppressions/unsubscribes ``` #### Request Body \[!toc] [#request-body-toc-3] ```json { "domain_id": "83gwk2j7zqz1nxyd", "recipients": [ "test@example.com" ] } ``` #### Request parameters \[!toc] [#request-parameters-toc-11] *JSON parameters are provided in dot notation.* | JSON parameter | Type | Required | Limitations | Details | | -------------- | ---------- | -------- | ----------------- | ------- | | `domain_id` | `string` | yes | | | | `recipients[]` | `string[]` | yes | | | | `recipients.*` | `string` | yes | Must be an email. | | ### Responses [#responses-11] | Response key | Type | Details | | ------------------------- | ---------- | ------------------------------------- | | `data.*` | `object[]` | Array of unsubscribe entries created. | | `data.*.recipient` | `object` | Recipient related to the unsubscribe. | | `data.*.recipient.domain` | `object` | Domain related to the unsubscribe. | #### Valid [#valid-11] ```http Response Code: 201 Created Response Headers: content-type: application/json ``` ```json { "data": [ { "id": "60f53a20506faf239d471ff2", "reason": null, "readable_reason": null, "recipient": { "id": "60f1a0195c14080bbc606292", "email": "test@example.com", "created_at": "2021-07-16T15:04:57.888000Z", "updated_at": "2021-07-19T08:38:56.243000Z", "deleted_at": "", "domain": { "id": "7nxe3yjmeq28vp0k", "name": "mailersend.com", "created_at": "2021-07-15T11:04:44.000000Z", "updated_at": "2021-07-15T11:04:45.000000Z" } }, "created_at": "2021-07-19T08:38:56.283000Z" } ] } ``` #### Error [#error-11] ```http Response Code: 422 Unprocessable Entity ``` *See - [Validation errors](/../../general#validation-errors)* ## Delete recipients from a suppression list [#delete-recipients-from-a-suppression-list] ### Blocklist [#blocklist-2] Delete one or more blocklist entries with this `DELETE` request: ```http DELETE https://api.mailersend.com/v1/suppressions/blocklist ``` #### Request Body \[!toc] [#request-body-toc-4] To delete specific entries: ```json { "ids": [ "60f198790542d97fb66dfe52", "60f198790542d97fb66dfe53" ] } ``` To delete all entries: ```json { "all": true } ``` ```php use MailerSend\MailerSend; $mailersend = new MailerSend(['api_key' => 'key']); // Delete specific instances $mailersend->blocklist->delete(['id_one', 'id_two']); // or delete all $mailersend->blocklist->delete(null, true); // You can also specify the domain $mailersend->blocklist->delete(['id'], false, 'domain_id'); ``` [More examples](https://github.com/mailersend/mailersend-php) ```javascript import 'dotenv/config'; import { BlockListType, MailerSend } from "mailersend"; const mailerSend = new MailerSend({ apiKey: process.env.API_KEY, }); mailerSend.email.recipient.delBlockListRecipients( ["recipient_id", "recipient_id"], BlockListType.BLOCK_LIST ) .then((response) => console.log(response.body)) .catch((error) => console.log(error.body)); ``` [More examples](https://github.com/mailersend/mailersend-nodejs) ```python from mailersend import MailerSendClient, RecipientsBuilder ms = MailerSendClient() # Delete specific entries by IDs request = (RecipientsBuilder() .domain_id("domain-id") .ids(["recipient-id-1", "recipient-id-2"]) .build_suppression_delete_request()) response = ms.recipients.delete_from_blocklist(request) ``` [More examples](https://github.com/mailersend/mailersend-python) ```go package main import ( "context" "time" "github.com/mailersend/mailersend-go" ) var APIKey = "Api Key Here" func main() { // Create an instance of the mailersend client ms := mailersend.NewMailersend(APIKey) ctx := context.Background() ctx, cancel := context.WithTimeout(ctx, 5*time.Second) defer cancel() domainID := "domain-id" // Delete All {type} // mailersend.BlockList // mailersend.HardBounces // mailersend.SpamComplaints // mailersend.Unsubscribes _, _ = ms.Suppression.DeleteAll(ctx, domainID, mailersend.Unsubscribes) // Delete deleteSuppressionOption := &mailersend.DeleteSuppressionOptions{ DomainID: domainID, Ids: []string{"suppression-id"}, } _, _ = ms.Suppression.Delete(ctx, deleteSuppressionOption, mailersend.Unsubscribes) } ``` [More examples](https://github.com/mailersend/mailersend-go) ```java import com.mailersend.sdk.MailerSend; import com.mailersend.sdk.MailerSendResponse; import com.mailersend.sdk.exceptions.MailerSendException; import com.mailersend.sdk.recipients.BlocklistItem; import com.mailersend.sdk.recipients.BlocklistListResponse; import com.mailersend.sdk.recipients.SuppressionItem; import com.mailersend.sdk.recipients.SuppressionList; public void DeleteRecipientsFromSuppressionList () { MailerSend ms = new MailerSend(); ms.setToken("mailersend token"); try { // delete from blocklist BlocklistListResponse blocklist = ms.recipients().suppressions().getBlocklist(); if (blocklist.items.length == 0) { fail(); } String itemId = blocklist.items[0].id; MailerSendResponse response = ms.recipients().suppressions().deleteBlocklistItems(new String[] { itemId }); System.out.println(response.responseStatusCode); // delete from hard bounces SuppressionList hardBounces = ms.recipients().suppressions().getHardBounces(); if (hardBounces.items.length == 0) { fail(); } itemId = hardBounces.items[0].id; response = ms.recipients().suppressions().deleteHardBouncesItems(new String[] { itemId }); System.out.println(response.responseStatusCode); // delete from spam complaints SuppressionList spamComplaints = ms.recipients().suppressions().getSpamComplaints(); if (spamComplaints.items.length == 0) { fail(); } itemId = spamComplaints.items[0].id; response = ms.recipients().suppressions().deleteSpamComplaintsItems(new String[] { itemId }); System.out.println(response.responseStatusCode); // delete from unsubscribes SuppressionList unsubscribes = ms.recipients().suppressions().getUnsubscribes(); if (unsubscribes.items.length == 0) { fail(); } itemId = unsubscribes.items[0].id; response = ms.recipients().suppressions().deleteUnsubscribesItems(new String[] { itemId }); System.out.println(response.responseStatusCode); } catch (MailerSendException e) { e.printStackTrace(); } } ``` [More examples](https://github.com/mailersend/mailersend-java) ```ruby require "mailersend-ruby" ms_suppressions = Mailersend::Suppressions.new // Delete from Block List ms_suppressions.delete_from_blocklist(domain_id: 'yourdomainid', ids: ["xxx2241ll"]) // Delete from Hard Bounces ms_suppressions.delete_from_hard_bounces(domain_id: 'yourdomainid', ids: ["xxx2241ll"]) // Delete from Spam Complaints ms_suppressions.delete_from_spam_complaints(domain_id: 'yourdomainid', ids: ["xxx2241ll"]) // Delete from Unsubscribes ms_suppressions.delete_from_unsubscribers(domain_id: 'yourdomainid', ids: ["xxx2241ll"]) ``` [More examples](https://github.com/mailersend/mailersend-ruby) #### Request parameters \[!toc] [#request-parameters-toc-12] *JSON parameters are provided in dot notation.* | JSON parameter | Type | Required | Limitations | Details | | -------------- | ---------- | -------- | --------------------------------- | ------- | | `domain_id` | `string` | no | | | | `ids` | `string[]` | no | Required if `all` is not defined. | | | `all` | `boolean` | no | Required if `ids` is not defined. | | ### Responses [#responses-12] #### Valid [#valid-12] ```http Response Code: 200 OK Response Body: [EMPTY] ``` #### Error [#error-12] ```http Response Code: 422 Unprocessable Entity ``` ```json { "message": "The given data was invalid.", "errors": { "ids.0": [ "The selected ids.0 is invalid." ], "ids.1": [ "The selected ids.1 is invalid." ] } } ``` *See - [Validation errors](/../../general#validation-errors)* ### Hard Bounces [#hard-bounces-2] Delete one or more hard bounces from recipients by passing the hard bounces IDs with this `DELETE` request: ```http DELETE https://api.mailersend.com/v1/suppressions/hard-bounces ``` #### Request Body \[!toc] [#request-body-toc-5] To delete specific entries: ```json { "ids": [ "60d0563fd4fb3212e2065522", "60ae0999c3da7c275f3b5589" ] } ``` To delete all entries: ```json { "all": true } ``` #### Request parameters \[!toc] [#request-parameters-toc-13] *JSON parameters are provided in dot notation.* | JSON parameter | Type | Required | Limitations | Details | | -------------- | ---------- | -------- | --------------------------------- | ------- | | `domain_id` | `string` | no | | | | `ids` | `string[]` | no | Required if `all` is not defined. | | | `all` | `boolean` | no | Required if `ids` is not defined. | | ### Responses [#responses-13] #### Valid [#valid-13] ```http Response Code: 200 OK Response Body: [EMPTY] ``` #### Error [#error-13] ```http Response Code: 422 Unprocessable Entity ``` ```json { "message": "The given data was invalid.", "errors": { "ids.0": [ "The selected ids.0 is invalid." ], "ids.1": [ "The selected ids.1 is invalid." ] } } ``` *See - [Validation errors](/../../general#validation-errors)* ### Spam Complaints [#spam-complaints-2] Delete one or more spam complaints from recipients by providing the spam complaint IDs with this `DELETE` request: ```http DELETE https://api.mailersend.com/v1/suppressions/spam-complaints ``` #### Request Body \[!toc] [#request-body-toc-6] To delete specific entries: ```json { "ids": [ "60d32115d14907786d7fdd42", "60ae0999c3da7c275f3b558e" ] } ``` To delete all entries: ```json { "all": true } ``` #### Request parameters \[!toc] [#request-parameters-toc-14] *JSON parameters are provided in dot notation.* | JSON parameter | Type | Required | Limitations | Details | | -------------- | ---------- | -------- | --------------------------------- | ------- | | `domain_id` | `string` | no | | | | `ids` | `string[]` | no | Required if `all` is not defined. | | | `all` | `boolean` | no | Required if `ids` is not defined. | | ### Responses [#responses-14] #### Valid [#valid-14] ```http Response Code: 200 OK Response Body: [EMPTY] ``` #### Error [#error-14] ```http Response Code: 422 Unprocessable Entity ``` ```json { "message": "The given data was invalid.", "errors": { "ids.0": [ "The selected ids.0 is invalid." ], "ids.1": [ "The selected ids.1 is invalid." ] } } ``` *See - [Validation errors](/../../general#validation-errors)* ### Unsubscribes [#unsubscribes-2] Delete one or more unsubscribe entries from recipients by passing the unsubscribe IDs with this `DELETE` request: ```http DELETE https://api.mailersend.com/v1/suppressions/unsubscribes ``` #### Request Body \[!toc] [#request-body-toc-7] To delete specific entries: ```json { "ids": [ "60d3169d8dc7b007f356d142", "60ae0999c3da7c275f3b558b" ] } ``` To delete all entries: ```json { "all": true } ``` #### Request parameters \[!toc] [#request-parameters-toc-15] *JSON parameters are provided in dot notation.* | JSON parameter | Type | Required | Limitations | Details | | -------------- | ---------- | -------- | --------------------------------- | ------- | | `domain_id` | `string` | no | | | | `ids` | `string[]` | no | Required if `all` is not defined. | | | `all` | `boolean` | no | Required if `ids` is not defined. | | ### Responses [#responses-15] #### Valid [#valid-15] ```http Response Code: 200 OK Response Body: [EMPTY] ``` #### Error [#error-15] ```http Response Code: 422 Unprocessable Entity ``` ```json { "message": "The given data was invalid.", "errors": { "ids.0": [ "The selected ids.0 is invalid." ], "ids.1": [ "The selected ids.1 is invalid." ] } } ``` *See - [Validation errors](/../../general#validation-errors)* ### On Hold List [#on-hold-list-1] Delete one or more recipient entries from on hold list by passing the on hold list IDs with this `DELETE` request: ```http DELETE https://api.mailersend.com/v1/suppressions/on-hold-list ``` #### Request Body \[!toc] [#request-body-toc-8] To delete specific entries: ```json { "ids": [ "64c760a33e2db0f6340f4710", "64c760a33e2db0f6340f470e" ] } ``` To delete all entries: ```json { "all": true } ``` #### Request parameters \[!toc] [#request-parameters-toc-16] *JSON parameters are provided in dot notation.* | JSON parameter | Type | Required | Limitations | Details | | -------------- | ---------- | -------- | --------------------------------- | ------- | | `domain_id` | `string` | no | | | | `ids` | `string[]` | no | Required if `all` is not defined. | | | `all` | `boolean` | no | Required if `ids` is not defined. | | ### Responses [#responses-16] #### Valid [#valid-16] ```http Response Code: 200 OK Response Body: [EMPTY] ``` #### Error [#error-16] ```http Response Code: 422 Unprocessable Entity ``` ```json { "message": "The given data was invalid.", "errors": { "ids.0": [ "The selected ids.0 is invalid." ], "ids.1": [ "The selected ids.1 is invalid." ] } } ``` *See - [Validation errors](/../../general#validation-errors)* # Sender Identities (/api/v1/email/sender-identity) ## Get a list of sender identities [#get-a-list-of-sender-identities] Retrieve information about sender identities with this `GET` request: ```http GET https://api.mailersend.com/v1/identities ``` #### Request parameters \[!toc] [#request-parameters-toc] | Query parameter | Type | Required | Limitations | Details | | --------------- | -------- | -------- | ------------------------------------ | ------------------------ | | `domain_id` | `string` | no | | | | `page` | `int` | no | | | | `limit` | `int` | no | Min: `10`, Max: `100` | Default: `25` | | `query` | `string` | no | | Filter by email address. | | `order_by` | `string` | no | `email`, `created_at`, `verified_at` | | | `order` | `string` | no | `asc`, `desc` | | ```php use MailerSend\MailerSend; $mailersend = new MailerSend(['api_key' => 'key']); $mailersend->senderIdentity->getAll($domainId = 'domainId', $page = 1, $limit = 10); ``` [More examples](https://github.com/mailersend/mailersend-php) ```javascript import 'dotenv/config'; import { MailerSend } from "mailersend"; const mailerSend = new MailerSend({ apiKey: process.env.API_KEY, }); mailerSend.email.identity.list() .then((response) => console.log(response.body)) .catch((error) => console.log(error.body)); ``` [More examples](https://github.com/mailersend/mailersend-nodejs) ```python from mailersend import MailerSendClient, IdentityBuilder ms = MailerSendClient() request = (IdentityBuilder() .domain_id("domain-id") .build_list_request()) response = ms.identities.list_identities(request) ``` [More examples](https://github.com/mailersend/mailersend-python) ```go package main import ( "context" "log" "time" "github.com/mailersend/mailersend-go" ) var APIKey = "Api Key Here" func main() { // Create an instance of the mailersend client ms := mailersend.NewMailersend(APIKey) ctx := context.Background() ctx, cancel := context.WithTimeout(ctx, 5*time.Second) defer cancel() domainID := "domain-id" options := &mailersend.ListIdentityOptions{ DomainID: domainID, Page: 1, Limit: 25, } _, _, err := ms.Identity.List(ctx, options) if err != nil { log.Fatal(err) } } ``` [More examples](https://github.com/mailersend/mailersend-go) ```java import com.mailersend.sdk.MailerSend; import com.mailersend.sdk.identities.Identity; import com.mailersend.sdk.identities.IdentitiesList; import com.mailersend.sdk.exceptions.MailerSendException; public void ListIdentities() { MailerSend ms = new MailerSend(); ms.setToken("api token"); try { IdentitiesList list = ms.identities().getIdentities("domain-id", 1, 25); for (Identity identity : list.identities) { System.out.println(identity.id); System.out.println(identity.email); } } catch (MailerSendException e) { e.printStackTrace(); } } ``` [More examples](https://github.com/mailersend/mailersend-java) ```ruby require "mailersend-ruby" ms_sender_identity = Mailersend::SenderIdentity.new ms_sender_identity.list ``` [More examples](https://github.com/mailersend/mailersend-ruby) ### Responses [#responses] #### Valid [#valid] ```http Response Code: 200 OK Response Headers: content-type: application/json ``` ```json { "data": [ { "id": "7nxe3yjmeq28vp0k", "email": "john@test.com", "name": "John Doe", "reply_to_email": null, "reply_to_name": null, "is_verified": false, "resends": 0, "add_note": false, "personal_note": null, "domain": { "id": "7nxe3yjmeq28vp0k", "name": "test.com", "created_at": "2022-11-29T10:43:22.000000Z", "updated_at": "2022-11-29T10:43:32.000000Z" } } ] } ``` #### Error [#error] ```http Response Code: 404 Not Found ``` ## Get a single sender identity [#get-a-single-sender-identity] If you want to retrieve a single sender identity, use this `GET` request: ```http GET https://api.mailersend.com/v1/identities/{identity_id} ``` #### Request parameters \[!toc] [#request-parameters-toc-1] | URL parameter | Type | Required | Limitations | Details | | ------------- | -------- | -------- | ----------- | ------- | | `identity_id` | `string` | yes | | | ```php use MailerSend\MailerSend; $mailersend = new MailerSend(['api_key' => 'key']); $mailersend->senderIdentity->find('identityId'); ``` [More examples](https://github.com/mailersend/mailersend-php) ```javascript import 'dotenv/config'; import { MailerSend } from "mailersend"; const mailerSend = new MailerSend({ apiKey: process.env.API_KEY, }); mailerSend.email.identity.single("identity_id") .then((response) => console.log(response.body)) .catch((error) => console.log(error.body)); ``` [More examples](https://github.com/mailersend/mailersend-nodejs) ```python from mailersend import MailerSendClient, IdentityBuilder ms = MailerSendClient() request = (IdentityBuilder() .identity_id("identity-id") .build_get_request()) response = ms.identities.get_identity(request) ``` [More examples](https://github.com/mailersend/mailersend-python) ```go package main import ( "context" "log" "time" "github.com/mailersend/mailersend-go" ) var APIKey = "Api Key Here" func main() { // Create an instance of the mailersend client ms := mailersend.NewMailersend(APIKey) ctx := context.Background() ctx, cancel := context.WithTimeout(ctx, 5*time.Second) defer cancel() identityID := "identity-id" _, _, err := ms.Identity.Get(ctx, identityID) if err != nil { log.Fatal(err) } } ``` [More examples](https://github.com/mailersend/mailersend-go) ```java import com.mailersend.sdk.MailerSend; import com.mailersend.sdk.identities.Identity; import com.mailersend.sdk.exceptions.MailerSendException; public void GetIdentity() { MailerSend ms = new MailerSend(); ms.setToken("api token"); try { Identity identity = ms.identities().getIdentity("identity-id"); System.out.println(identity.id); System.out.println(identity.email); System.out.println(identity.name); } catch (MailerSendException e) { e.printStackTrace(); } } ``` [More examples](https://github.com/mailersend/mailersend-java) ```ruby require "mailersend-ruby" ms_sender_identity = Mailersend::SenderIdentity.new ms_sender_identity.single(identity_id: 'idofidentity123') ``` [More examples](https://github.com/mailersend/mailersend-ruby) ### Responses [#responses-1] #### Valid [#valid-1] ```http Response Code: 200 OK Response Headers: content-type: application/json ``` ```json { "data": { "id": "7nxe3yjmeq28vp0k", "email": "john@test.com", "name": "John Doe", "reply_to_email": null, "reply_to_name": null, "is_verified": false, "resends": 0, "add_note": false, "personal_note": null, "domain": { "id": "7nxe3yjmeq28vp0k", "name": "test.com", "created_at": "2022-11-29T10:43:22.000000Z", "updated_at": "2022-11-29T10:43:32.000000Z" } } } ``` #### Error [#error-1] ```http Response Code: 404 Not Found ``` ## Get a single sender identity by email [#get-a-single-sender-identity-by-email] If you want to retrieve a single sender identity by email, use this `GET` request: ```http GET https://api.mailersend.com/v1/identities/email/{email} ``` #### Request parameters \[!toc] [#request-parameters-toc-2] | URL parameter | Type | Required | Limitations | Details | | ------------- | -------- | -------- | ----------- | ------- | | `email` | `string` | yes | | | ```php use MailerSend\MailerSend; $mailersend = new MailerSend(['api_key' => 'key']); $mailersend->senderIdentity->findByEmail('email'); ``` [More examples](https://github.com/mailersend/mailersend-php) ```javascript import 'dotenv/config'; import { MailerSend } from "mailersend"; const mailerSend = new MailerSend({ apiKey: process.env.API_KEY, }); mailerSend.email.identity.singleByEmail('email_address') .then((response) => console.log(response.body)) .catch((error) => console.log(error.body)); ``` [More examples](https://github.com/mailersend/mailersend-nodejs) ```go package main import ( "context" "os" "log" "time" "github.com/mailersend/mailersend-go" ) func main() { // Create an instance of the mailersend client ms := mailersend.NewMailersend(os.Getenv("MAILERSEND_API_KEY")) ctx := context.Background() ctx, cancel := context.WithTimeout(ctx, 5*time.Second) defer cancel() _, _, err := ms.Identity.GetByEmail(ctx, "identity-email") if err != nil { log.Fatal(err) } } ``` [More examples](https://github.com/mailersend/mailersend-go) ```ruby require "mailersend-ruby" ms_client = Mailersend::Client.new('your_mailersend_token') ms_sender_identity = Mailersend::SenderIdentity.new(ms_client) ms_sender_identity.single_by_email(email: 'example@email.com') ``` [More examples](https://github.com/mailersend/mailersend-ruby) ### Responses [#responses-2] #### Valid [#valid-2] ```http Response Code: 200 OK Response Headers: content-type: application/json ``` ```json { "data": { "id": "7nxe3yjmeq28vp0k", "email": "john@test.com", "name": "John Doe", "reply_to_email": null, "reply_to_name": null, "is_verified": false, "resends": 0, "add_note": false, "personal_note": null, "domain": { "id": "7nxe3yjmeq28vp0k", "name": "test.com", "created_at": "2022-11-29T10:43:22.000000Z", "updated_at": "2022-11-29T10:43:32.000000Z" } } } ``` #### Error [#error-2] ```http Response Code: 404 Not Found ``` ## Add a sender identity [#add-a-sender-identity] If you want to add a new sender identity from which you can send emails without having to verify a domain, use this `POST` request: ```http POST https://api.mailersend.com/v1/identities ``` ### Request body \[!toc] [#request-body-toc] ```json { "domain_id": "7nxe3yjmeq28vp0k", "email": "pedro@test.com", "name": "Pedro Doe", "personal_note": "Hi Pedro, please confirm this email by clicking on the link below.", "reply_to_name": "Test Doe", "reply_to_email": "test@test.com", "add_note": true } ``` ```php use MailerSend\MailerSend; use MailerSend\Helpers\Builder\SenderIdentity; $mailersend = new MailerSend(['api_key' => 'key']); $mailersend->senderIdentity->create( (new SenderIdentity('domainId', 'name', 'email')) ->setReplyToName("John Doe") ->setReplyToEmail("john@test.com")) ->setAddNote(true) ->setPersonalNote("Hi John, please use this token") ); ``` [More examples](https://github.com/mailersend/mailersend-php) ```javascript import 'dotenv/config'; import { MailerSend, Inbound, InboundFilterType } from "mailersend"; const mailerSend = new MailerSend({ apiKey: process.env.API_KEY, }); const identity = new Identity() .setDomainId('domain_id') .setEmail('identity@yourdomain.com') .setName('Name') .setReplyToEmail('reply_identity@yourdomain.com') .setReplyToName('Reply Name') .setAddNote(false); mailerSend.email.identity.create(identity) .then((response) => console.log(response.body)) .catch((error) => console.log(error.body)); ``` [More examples](https://github.com/mailersend/mailersend-nodejs) ```python from mailersend import MailerSendClient, IdentityBuilder ms = MailerSendClient() request = (IdentityBuilder() .domain_id("domain-id") .name("John Doe") .email("john@yourdomain.com") .reply_to_email("support@yourdomain.com") .reply_to_name("Support Team") .add_note(True) .build_create_request()) response = ms.identities.create_identity(request) ``` [More examples](https://github.com/mailersend/mailersend-python) ```go package main import ( "context" "log" "time" "github.com/mailersend/mailersend-go" ) var APIKey = "Api Key Here" func main() { // Create an instance of the mailersend client ms := mailersend.NewMailersend(APIKey) ctx := context.Background() ctx, cancel := context.WithTimeout(ctx, 5*time.Second) defer cancel() options := &mailersend.CreateIdentityOptions{ DomainID: "domain-id", Name: "John Doe", Email: "john@yourdomain.com", ReplyToEmail: mailersend.String("support@yourdomain.com"), ReplyToName: mailersend.String("Support Team"), AddNote: mailersend.Bool(true), } _, _, err := ms.Identity.Create(ctx, options) if err != nil { log.Fatal(err) } } ``` [More examples](https://github.com/mailersend/mailersend-go) ```java import com.mailersend.sdk.MailerSend; import com.mailersend.sdk.identities.Identity; import com.mailersend.sdk.exceptions.MailerSendException; public void CreateIdentity() { MailerSend ms = new MailerSend(); ms.setToken("api token"); try { Identity identity = ms.identities().builder() .domainId("domain-id") .name("John Doe") .email("john@yourdomain.com") .replyToEmail("support@yourdomain.com") .replyToName("Support Team") .addNote(true) .createIdentity(); System.out.println(identity.id); System.out.println(identity.email); } catch (MailerSendException e) { e.printStackTrace(); } } ``` [More examples](https://github.com/mailersend/mailersend-java) ```ruby require "mailersend-ruby" ms_sender_identity = Mailersend::SenderIdentity.new ms_sender_identity.add(domain_id: 'idofdomain12412', name: 'yourname', email: 'youremail') ``` [More examples](https://github.com/mailersend/mailersend-ruby) ### Request Parameters \[!toc] [#request-parameters-toc-3] *JSON parameters are provided in dot notation* | JSON Parameter | Type | Required | Limitations | Details | | ---------------- | --------- | -------- | ---------------------------- | ------------------------------------- | | `domain_id` | `string` | yes | | | | `name` | `string` | no | `Max` 191 characters. | | | `email` | `string` | yes | `Max` 320 characters, unique | | | `reply_to_email` | `string` | no | `Max` 320 characters. | Required when `reply_to_name` is set. | | `reply_to_name` | `string` | no | `Max` 191 characters. | | | `add_note` | `boolean` | no | | | | `personal_note` | `string` | no | `Max` 250 characters. | | ### Responses [#responses-3] | Response Key | Type | Details | | ------------ | ------ | ------------------------ | | data | object | Identity object created. | #### Valid [#valid-3] ```http Response Code: 201 CREATED Response Headers: content-type: application/json ``` ```json { "data": { "id": "7nxe3yjmeq28vp0k", "email": "pedro@test.com", "name": "Pedro Doe", "reply_to_email": "test@test.com", "reply_to_name": "Test Doe", "is_verified": false, "resends": 0, "add_note": true, "personal_note": "Hi Pedro, please confirm this email by clicking on the link below.", "domain": { "id": "7nxe3yjmeq28vp0k", "name": "test.com", "created_at": "2022-11-29T10:43:22.000000Z", "updated_at": "2022-11-29T10:43:32.000000Z" } } } ``` #### Invalid [#invalid] ```http Response Code: 422 Unprocessable Entity ``` *See - [Validation errors](/../../general#validation-errors)* ## Update a sender identity [#update-a-sender-identity] If you want to update the information of an existing sender identity, use this `PUT` request: ```http PUT https://api.mailersend.com/v1/identities/{identity_id} ``` ### Request body \[!toc] [#request-body-toc-1] ```json { "name": "Pedro Doe", "reply_to_name": "Test Doe", "reply_to_email": "test@test.com" } ``` ```php use MailerSend\MailerSend; use MailerSend\Helpers\Builder\SenderIdentity; $mailersend = new MailerSend(['api_key' => 'key']); $mailersend->senderIdentity->update( 'identityId', (new SenderIdentity('domainId', 'name', 'email')) ->setReplyToName("John Doe") ->setReplyToEmail("john@test.com")) ->setAddNote(true) ->setPersonalNote("Hi John, please use this token") ); ``` [More examples](https://github.com/mailersend/mailersend-php) ```javascript import 'dotenv/config'; import { MailerSend, Inbound, InboundFilterType } from "mailersend"; const mailerSend = new MailerSend({ apiKey: process.env.API_KEY, }); const data = { domain_id: 'string', email: 'email@yourdomain.com', name: 'name', personal_note: 'Personal note', reply_to_name: 'Reply Name', reply_to_email: 'repy@yourdomain.com', add_note: true, }; mailerSend.email.identity.update('identity_id', data) .then((response) => console.log(response.body)) .catch((error) => console.log(error.body)); ``` [More examples](https://github.com/mailersend/mailersend-nodejs) ```python from mailersend import MailerSendClient, IdentityBuilder ms = MailerSendClient() request = (IdentityBuilder() .identity_id("identity-id") .name("Jane Doe") .reply_to_email("support@yourdomain.com") .reply_to_name("Support Team") .add_note(True) .build_update_request()) response = ms.identities.update_identity(request) ``` [More examples](https://github.com/mailersend/mailersend-python) ```go package main import ( "context" "log" "time" "github.com/mailersend/mailersend-go" ) var APIKey = "Api Key Here" func main() { // Create an instance of the mailersend client ms := mailersend.NewMailersend(APIKey) ctx := context.Background() ctx, cancel := context.WithTimeout(ctx, 5*time.Second) defer cancel() identityID := "identity-id" options := &mailersend.UpdateIdentityOptions{ Name: mailersend.String("Jane Doe"), ReplyToEmail: mailersend.String("support@yourdomain.com"), ReplyToName: mailersend.String("Support Team"), AddNote: mailersend.Bool(true), } _, _, err := ms.Identity.Update(ctx, identityID, options) if err != nil { log.Fatal(err) } } ``` [More examples](https://github.com/mailersend/mailersend-go) ```java import com.mailersend.sdk.MailerSend; import com.mailersend.sdk.identities.Identity; import com.mailersend.sdk.exceptions.MailerSendException; public void UpdateIdentity() { MailerSend ms = new MailerSend(); ms.setToken("api token"); try { Identity identity = ms.identities().builder() .name("Jane Doe") .replyToEmail("support@yourdomain.com") .replyToName("Support Team") .addNote(true) .updateIdentity("identity-id"); System.out.println(identity.id); System.out.println(identity.name); } catch (MailerSendException e) { e.printStackTrace(); } } ``` [More examples](https://github.com/mailersend/mailersend-java) ```ruby require "mailersend-ruby" ms_sender_identity = Mailersend::SenderIdentity.new ms_sender_identity.update(identity_id: 'idofidentity123', reply_to_email: 'replyemail', reply_to_name: 'replyname') ``` [More examples](https://github.com/mailersend/mailersend-ruby) ### Request Parameters \[!toc] [#request-parameters-toc-4] | URL parameter | Type | Required | Limitations | Details | | ------------- | -------- | -------- | ----------- | ------- | | `identity_id` | `string` | yes | | | *JSON parameters are provided in dot notation* | JSON Parameter | Type | Required | Limitations | Details | | ---------------- | -------- | -------- | --------------------- | ------------------------------------- | | `name` | `string` | no | `Max` 191 characters. | | | `reply_to_email` | `string` | no | `Max` 320 characters. | Required when `reply_to_name` is set. | | `reply_to_name` | `string` | no | `Max` 191 characters. | | ### Responses [#responses-4] | Response Key | Type | Details | | ------------ | ------ | ------------------------ | | data | object | Identity object updated. | #### Valid [#valid-4] ```http Response Code: 200 OK Response Headers: content-type: application/json ``` ```json { "data": { "id": "7nxe3yjmeq28vp0k", "email": "pedro@test.com", "name": "Pedro Doe", "reply_to_email": "test@test.com", "reply_to_name": "Test Doe", "is_verified": false, "resends": 0, "add_note": true, "personal_note": "Hi Pedro, please confirm this email by clicking on the link below.", "domain": { "id": "7nxe3yjmeq28vp0k", "name": "test.com", "created_at": "2022-11-29T10:43:22.000000Z", "updated_at": "2022-11-29T10:43:32.000000Z" } } } ``` #### Invalid [#invalid-1] ```http Response Code: 422 Unprocessable Entity ``` *See - [Validation errors](/../../general#validation-errors)* ## Update a sender identity by email [#update-a-sender-identity-by-email] If you want to update the information of an existing sender identity by email, use this `PUT` request: ```http PUT https://api.mailersend.com/v1/identities/email/{email} ``` ### Request body \[!toc] [#request-body-toc-2] ```json { "name": "Pedro Doe", "reply_to_name": "Test Doe", "reply_to_email": "test@test.com" } ``` ```php use MailerSend\MailerSend; use MailerSend\Helpers\Builder\SenderIdentity; $mailersend = new MailerSend(['api_key' => 'key']); $mailersend->senderIdentity->updateByEmail( 'email', (new SenderIdentity('domainId', 'name', 'email')) ->setReplyToName("John Doe") ->setReplyToEmail("john@test.com")) ->setAddNote(true) ->setPersonalNote("Hi John, please use this token") ); ``` [More examples](https://github.com/mailersend/mailersend-php) ```javascript import 'dotenv/config'; import { MailerSend } from "mailersend"; const mailerSend = new MailerSend({ apiKey: process.env.API_KEY, }); const data = { name: 'Doe Jane', reply_to_email: 'support@yourdomain.com', reply_to_name: 'Support Team', add_note: true, }; mailerSend.email.identity.updateByEmail('support@yourdomain.com', data) .then((response) => console.log(response.body)) .catch((error) => console.log(error.body)); ``` [More examples](https://github.com/mailersend/mailersend-nodejs) ```python from mailersend import MailerSendClient, IdentityBuilder ms = MailerSendClient() request = (IdentityBuilder() .email("support@yourdomain.com") .name("Doe Jane") .reply_to_email("support@yourdomain.com") .reply_to_name("Support Team") .add_note(True) .build_update_by_email_request()) response = ms.identities.update_identity(request) ``` [More examples](https://github.com/mailersend/mailersend-python) ```go package main import ( "context" "log" "time" "github.com/mailersend/mailersend-go" ) var APIKey = "Api Key Here" func main() { // Create an instance of the mailersend client ms := mailersend.NewMailersend(APIKey) ctx := context.Background() ctx, cancel := context.WithTimeout(ctx, 5*time.Second) defer cancel() email := "support@yourdomain.com" options := &mailersend.UpdateIdentityOptions{ Name: mailersend.String("Doe Jane"), ReplyToEmail: mailersend.String("support@yourdomain.com"), ReplyToName: mailersend.String("Support Team"), AddNote: mailersend.Bool(true), } _, _, err := ms.Identity.UpdateByEmail(ctx, email, options) if err != nil { log.Fatal(err) } } ``` [More examples](https://github.com/mailersend/mailersend-go) ```java import com.mailersend.sdk.MailerSend; import com.mailersend.sdk.identities.Identity; import com.mailersend.sdk.exceptions.MailerSendException; public void UpdateIdentityByEmail() { MailerSend ms = new MailerSend(); ms.setToken("api token"); try { Identity identity = ms.identities().builder() .email("support@yourdomain.com") .name("Doe Jane") .replyToEmail("support@yourdomain.com") .replyToName("Support Team") .addNote(true) .updateIdentityByEmail(); System.out.println(identity.id); System.out.println(identity.name); } catch (MailerSendException e) { e.printStackTrace(); } } ``` [More examples](https://github.com/mailersend/mailersend-java) ```ruby require "mailersend-ruby" ms_sender_identity = Mailersend::SenderIdentity.new ms_sender_identity.update_by_email(email: 'support@yourdomain.com', name: 'Doe Jane', reply_to_email: 'support@yourdomain.com', reply_to_name: 'Support Team', add_note: true) ``` [More examples](https://github.com/mailersend/mailersend-ruby) ### Request Parameters \[!toc] [#request-parameters-toc-5] | URL parameter | Type | Required | Limitations | Details | | ------------- | -------- | -------- | ----------- | ------- | | `email` | `string` | yes | | | *JSON parameters are provided in dot notation* | JSON Parameter | Type | Required | Limitations | Details | | ---------------- | -------- | -------- | --------------------- | ------------------------------------- | | `name` | `string` | no | `Max` 191 characters. | | | `reply_to_email` | `string` | no | `Max` 320 characters. | Required when `reply_to_name` is set. | | `reply_to_name` | `string` | no | `Max` 191 characters. | | ### Responses [#responses-5] | Response Key | Type | Details | | ------------ | ------ | ------------------------ | | data | object | Identity object updated. | #### Valid [#valid-5] ```http Response Code: 200 OK Response Headers: content-type: application/json ``` ```json { "data": { "id": "7nxe3yjmeq28vp0k", "email": "pedro@test.com", "name": "Pedro Doe", "reply_to_email": "test@test.com", "reply_to_name": "Test Doe", "is_verified": false, "resends": 0, "add_note": true, "personal_note": "Hi Pedro, please confirm this email by clicking on the link below.", "domain": { "id": "7nxe3yjmeq28vp0k", "name": "test.com", "created_at": "2022-11-29T10:43:22.000000Z", "updated_at": "2022-11-29T10:43:32.000000Z" } } } ``` #### Invalid [#invalid-2] ```http Response Code: 422 Unprocessable Entity ``` *See - [Validation errors](/../../general#validation-errors)* ## Delete a sender identity [#delete-a-sender-identity] If you want to delete a sender identity, use this `DELETE` request: ```http DELETE https://api.mailersend.com/v1/identities/{identity_id} ``` ### Request parameters \[!toc] [#request-parameters-toc-6] | URL parameter | Type | Required | Limitations | Details | | ------------- | -------- | -------- | ----------- | ------- | | `identity_id` | `string` | yes | | | ```php use MailerSend\MailerSend; $mailersend = new MailerSend(['api_key' => 'key']); $mailersend->senderIdentity->delete('identityId'); ``` [More examples](https://github.com/mailersend/mailersend-php) ```javascript import 'dotenv/config'; import { MailerSend } from "mailersend"; const mailerSend = new MailerSend({ apiKey: process.env.API_KEY, }); mailerSend.email.identity.delete("identity_id") .then((response) => console.log(response.body)) .catch((error) => console.log(error.body)); ``` [More examples](https://github.com/mailersend/mailersend-nodejs) ```python from mailersend import MailerSendClient, IdentityBuilder ms = MailerSendClient() request = (IdentityBuilder() .identity_id("identity-id") .build_delete_request()) response = ms.identities.delete_identity(request) ``` [More examples](https://github.com/mailersend/mailersend-python) ```go package main import ( "context" "log" "time" "github.com/mailersend/mailersend-go" ) var APIKey = "Api Key Here" func main() { // Create an instance of the mailersend client ms := mailersend.NewMailersend(APIKey) ctx := context.Background() ctx, cancel := context.WithTimeout(ctx, 5*time.Second) defer cancel() identityID := "identity-id" _, _, err := ms.Identity.Delete(ctx, identityID) if err != nil { log.Fatal(err) } } ``` [More examples](https://github.com/mailersend/mailersend-go) ```java import com.mailersend.sdk.MailerSend; import com.mailersend.sdk.exceptions.MailerSendException; public void DeleteIdentity() { MailerSend ms = new MailerSend(); ms.setToken("api token"); try { ms.identities().deleteIdentity("identity-id"); System.out.println("Identity deleted successfully"); } catch (MailerSendException e) { e.printStackTrace(); } } ``` [More examples](https://github.com/mailersend/mailersend-java) ```ruby require "mailersend-ruby" ms_sender_identity = Mailersend::SenderIdentity.new ms_sender_identity.delete(identity_id: 'idofidentity123') ``` [More examples](https://github.com/mailersend/mailersend-ruby) ### Responses [#responses-6] #### Valid [#valid-6] ```http Response Code: 204 No Content ``` #### Error [#error-3] ```http Response Code: 404 Not Found ``` ## Delete a sender identity by email [#delete-a-sender-identity-by-email] If you want to delete a sender identity by email, use this `DELETE` request: ```http DELETE https://api.mailersend.com/v1/identities/email/{email} ``` ### Request parameters \[!toc] [#request-parameters-toc-7] | URL parameter | Type | Required | Limitations | Details | | ------------- | -------- | -------- | ----------- | ------- | | `email` | `string` | yes | | | ```php use MailerSend\MailerSend; $mailersend = new MailerSend(['api_key' => 'key']); $mailersend->senderIdentity->deleteByEmail('email'); ``` [More examples](https://github.com/mailersend/mailersend-php) ```javascript import 'dotenv/config'; import { MailerSend } from "mailersend"; const mailerSend = new MailerSend({ apiKey: process.env.API_KEY, }); mailerSend.email.identity.deleteByEmail('email_address') .then((response) => console.log(response.body)) .catch((error) => console.log(error.body)); ``` [More examples](https://github.com/mailersend/mailersend-nodejs) ```python from mailersend import MailerSendClient, IdentityBuilder ms = MailerSendClient() request = (IdentityBuilder() .email("support@yourdomain.com") .build_delete_by_email_request()) response = ms.identities.delete_identity_by_email(request) ``` [More examples](https://github.com/mailersend/mailersend-python) ```go package main import ( "context" "log" "time" "github.com/mailersend/mailersend-go" ) var APIKey = "Api Key Here" func main() { // Create an instance of the mailersend client ms := mailersend.NewMailersend(APIKey) ctx := context.Background() ctx, cancel := context.WithTimeout(ctx, 5*time.Second) defer cancel() email := "support@yourdomain.com" _, _, err := ms.Identity.DeleteByEmail(ctx, email) if err != nil { log.Fatal(err) } } ``` [More examples](https://github.com/mailersend/mailersend-go) ```java import com.mailersend.sdk.MailerSend; import com.mailersend.sdk.exceptions.MailerSendException; public void DeleteIdentityByEmail() { MailerSend ms = new MailerSend(); ms.setToken("api token"); try { ms.identities().deleteIdentityByEmail("support@yourdomain.com"); System.out.println("Identity deleted successfully"); } catch (MailerSendException e) { e.printStackTrace(); } } ``` [More examples](https://github.com/mailersend/mailersend-java) ```ruby require "mailersend-ruby" ms_client = Mailersend::Client.new('your_mailersend_token') ms_sender_identity = Mailersend::SenderIdentity.new(ms_client) ms_sender_identity.delete_by_email(email: 'example@email.com') ``` [More examples](https://github.com/mailersend/mailersend-ruby) ### Responses [#responses-7] #### Valid [#valid-7] ```http Response Code: 202 Accepted ``` #### Error [#error-4] ```http Response Code: 404 Not Found ``` ## Resend a sender identity verification [#resend-a-sender-identity-verification] If you want to resend the verification email for a sender identity, use this `POST` request: ```http POST https://api.mailersend.com/v1/identities/{identity_id}/resend ``` ### Request parameters \[!toc] [#request-parameters-toc-8] | URL parameter | Type | Required | Limitations | Details | | ------------- | -------- | -------- | ----------- | ------- | | `identity_id` | `string` | yes | | | ```php use MailerSend\MailerSend; $mailersend = new MailerSend(['api_key' => 'key']); $mailersend->senderIdentity->resend('identityId'); ``` [More examples](https://github.com/mailersend/mailersend-php) ```javascript import 'dotenv/config'; import { MailerSend } from "mailersend"; const mailerSend = new MailerSend({ apiKey: process.env.API_KEY, }); mailerSend.email.identity.resend("identity_id") .then((response) => console.log(response.body)) .catch((error) => console.log(error.body)); ``` [More examples](https://github.com/mailersend/mailersend-nodejs) ```python from mailersend import MailerSendClient, IdentityBuilder ms = MailerSendClient() request = (IdentityBuilder() .identity_id("identity-id") .build_resend_request()) response = ms.identities.resend_identity(request) ``` [More examples](https://github.com/mailersend/mailersend-python) ```go package main import ( "context" "log" "time" "github.com/mailersend/mailersend-go" ) var APIKey = "Api Key Here" func main() { // Create an instance of the mailersend client ms := mailersend.NewMailersend(APIKey) ctx := context.Background() ctx, cancel := context.WithTimeout(ctx, 5*time.Second) defer cancel() identityID := "identity-id" _, _, err := ms.Identity.Resend(ctx, identityID) if err != nil { log.Fatal(err) } } ``` [More examples](https://github.com/mailersend/mailersend-go) ```java import com.mailersend.sdk.MailerSend; import com.mailersend.sdk.exceptions.MailerSendException; public void ResendIdentity() { MailerSend ms = new MailerSend(); ms.setToken("api token"); try { ms.identities().resendIdentity("identity-id"); System.out.println("Identity verification resent successfully"); } catch (MailerSendException e) { e.printStackTrace(); } } ``` [More examples](https://github.com/mailersend/mailersend-java) ```ruby require "mailersend-ruby" ms_sender_identity = Mailersend::SenderIdentity.new ms_sender_identity.resend(identity_id: 'idofidentity123') ``` [More examples](https://github.com/mailersend/mailersend-ruby) ### Responses [#responses-8] #### Valid [#valid-8] ```http Response Code: 200 OK Response Headers: content-type: application/json ``` ```json { "data": { "id": "7nxe3yjmeq28vp0k", "email": "john@test.com", "name": "John Doe", "reply_to_email": null, "reply_to_name": null, "is_verified": false, "resends": 1, "domain": { "id": "7nxe3yjmeq28vp0k", "name": "test.com", "created_at": "2022-11-29T10:43:22.000000Z", "updated_at": "2022-11-29T10:43:32.000000Z" } } } ``` #### Error [#error-5] ```http Response Code: 404 Not Found ``` # SMTP relay (/api/v1/email/smtp-relay) Use Simple Mail Transfer Protocol (SMTP) when you want to quickly send emails using a reliable Internet standard. Our SMTP relay service takes care of your email delivery so you don’t have to manage an email server. ## Basic usage [#basic-usage] [Enable SMTP on your Domain screen](https://www.mailersend.com/help/smtp-relay) and input the details into your SMTP client. Please refer to the documentation of your SMTP client for instructions on the exact way to set it up. Your client must support TLS security via port `587`. ### Tracing back SMTP messages to use with the API [#tracing-back-smtp-messages-to-use-with-the-api] Whenever a message is successfully parsed and queued in our system, you will get a similar response to this: ``` 250 Message queued as 61eec2dc16ae8b627a4b87e7 ``` Where `61eec2dc16ae8b627a4b87e7` will be a unique ID and you can track it back this to our [Messages API](/api/v1/email/messages). For directions on how to collect this information, refer to your SMTP client documentation. ### Understanding error messages [#understanding-error-messages] We use the same validation mechanisms for SMTP relay, which returns a string of concatenated validation errors with a `450` SMTP code, similar to this: ``` 450 The given data was invalid. You must provide one of html, text or template_id.,You must provide one of html, text or template_id.,You must provide one of html, text or template_id. ``` You can refer to our [Email API](/api/v1/email) for the exact reasons behind errors that happen during validation. For other possible SMTP codes, you can consult a source like [Wikipedia](https://en.wikipedia.org/wiki/List_of_SMTP_server_return_codes) or our [Knowledge base](https://www.mailersend.com/help/smtp-relay). ## Additional features [#additional-features] ### Custom tags [#custom-tags] You can add a header to an SMTP message you send as follows: ``` X-MailerSend-Tags: "tag 1, tag 2, tag 3" ``` You can send a maximum of 5 tags. This header must reside in the main MIME header node and not in additional MIME nodes like `text/plain` or `text/html`. ## Limitations [#limitations] Most of the limitations that are in place for [Email API](/api/v1/email) endpoints are the same for SMTP relay. These are the limitations that our users should be aware of: * We only support `TLS` security via `587` port and do not have plans to support older/unsecure protocols for SMTP * `FROM` email domain must be [verified](https://www.mailersend.com/help/how-to-verify-and-authenticate-a-sending-domain) * A subject is required * All custom headers, apart from the ones mentioned in [Additional features](#additional-features), will be dropped * HTML source might be readjusted if [click or open tracking](https://www.mailersend.com/help/activity) is enabled * Additional features like [advanced personalization](/api/v1/email/features#advanced-personalization) or [templates](https://www.mailersend.com/help/how-to-create-a-template) are only supported via our [Email API](/api/v1/email) * We only support attachments of the file types as defined in [Email API](/api/v1/email#supported-file-types) * There are [Rate limits](/general#rate-limits) applied to SMTP relay based on IP address and these tend to be lower than available through our API * SMTP Relay has a single connection transaction limit set at 5. To send bulk emails use our [Bulk Email API](/api/v1/email#send-bulk-emails) * [Daily request quota](https://developers.mailersend.com/general.html#daily-request-quota) applies to each individual message sent through our SMTP relay service. Be aware that the actual number of requests may vary depending on your SMTP client's email sending method. * We do not support desktop email clients such as Apple Mail, Outlook, Thunderbird and similar applications. If you encounter any other problems, or have a feature request, [let us know](https://www.mailersend.com/contact-us). # Templates (/api/v1/email/templates) Create and manage email templates via the MailerSend API. ## Get templates [#get-templates] Retrieve the account templates using this `GET` request: ```http GET https://api.mailersend.com/v1/templates ``` #### Request parameters \[!toc] [#request-parameters-toc] | Query parameter | Type | Required | Limitations | Details | | --------------- | -------- | -------- | --------------------- | ------------- | | `domain_id` | `string` | no | | | | `page` | `int` | no | Min: `1` | | | `limit` | `int` | no | Min: `10`, Max: `100` | Default: `25` | ```php use MailerSend\MailerSend; $mailersend = new MailerSend(['api_key' => 'key']); // Get all templates of an account $mailersend->template->getAll(); // Get all templates of a domain $mailersend->template->getAll('domain_id'); // Get page 2 of templates with 20 records per page $mailersend->template->getAll('domain_id', 2, 20); ``` [More examples](https://github.com/mailersend/mailersend-php) ```javascript import 'dotenv/config'; import { MailerSend} from "mailersend"; const mailerSend = new MailerSend({ apiKey: process.env.API_KEY, }); mailerSend.email.template.list({ domain_id: "domain_id" }) .then((response) => console.log(response.body)) .catch((error) => console.log(error.body)); ``` [More examples](https://github.com/mailersend/mailersend-nodejs) ```python from mailersend import MailerSendClient, TemplatesBuilder ms = MailerSendClient() request = (TemplatesBuilder() .domain_id("domain-id") .page(1) .limit(25) .build_templates_list_request()) response = ms.templates.list_templates(request) ``` [More examples](https://github.com/mailersend/mailersend-python) ```go package main import ( "context" "log" "time" "github.com/mailersend/mailersend-go" ) var APIKey = "Api Key Here" func main() { // Create an instance of the mailersend client ms := mailersend.NewMailersend(APIKey) ctx := context.Background() ctx, cancel := context.WithTimeout(ctx, 5*time.Second) defer cancel() options := &mailersend.ListTemplateOptions{ Page: 1, Limit: 25, } _, _, err := ms.Template.List(ctx, options) if err != nil { log.Fatal(err) } } ``` [More examples](https://github.com/mailersend/mailersend-go) ```java import com.mailersend.sdk.MailerSend; import com.mailersend.sdk.exceptions.MailerSendException; import com.mailersend.sdk.templates.TemplateItem; import com.mailersend.sdk.templates.TemplatesList; public void getTemplatesList() { MailerSend ms = new MailerSend(); ms.setToken("mailersend token"); try { TemplatesList list = ms.templates().getTemplates(); for (TemplateItem item : list.templates) { System.out.println(item.id); System.out.println(item.name); } } catch (MailerSendException e) { e.printStackTrace(); } } ``` [More examples](https://github.com/mailersend/mailersend-java) ```ruby require "mailersend-ruby" ms_templates = Mailersend::Templates.new ms_templates.list(domain_id: "aax455lll", page: 1, limit: 10) ``` [More examples](https://github.com/mailersend/mailersend-ruby) ### Responses [#responses] #### Valid [#valid] ```http Response Code: 200 OK Response Headers: content-type: application/json ``` ```json { "data": [ { "id": "x8emy5o5world01w", "name": "Signup email", "description": null, "type": "html", "image_path": "https://link.com/images/image.jpg", "tags": ["transactional", "welcome"], "variables": { "name": "", "company": "" }, "created_at": "2020-06-10 10:09:56", "updated_at": "2020-06-10 10:09:56" }, { "id": "x8emy5o5world01x", "name": "Premium subscription", "description": null, "type": "html", "image_path": "https://link.com/images/image.jpg", "tags": [], "variables": null, "created_at": "2020-06-10 10:09:56", "updated_at": "2020-06-10 10:09:56" }, { "id": "x8emy5o5world01y", "name": "Newsletter", "description": null, "type": "html", "image_path": "https://link.com/images/image.jpg", "tags": [], "variables": null, "created_at": "2020-06-10 10:09:56", "updated_at": "2020-06-10 10:09:56" } ], "links": { "first": "https:\/\/www.mailersend.io\/api\/v1\/templates?page=1", "last": "https:\/\/www.mailersend.io\/api\/v1\/templates?page=1", "prev": null, "next": null }, "meta": { "current_page": 1, "from": 1, "last_page": 1, "path": "https:\/\/www.mailersend.io\/api\/v1\/templates", "per_page": 25, "to": 3, "total": 3 } } ``` ## Get a single template [#get-a-single-template] Retrieve the information of a single template, its category, domain, and stats using this `GET` request: ```http GET https://api.mailersend.com/v1/templates/{template_id} ``` #### Request parameters \[!toc] [#request-parameters-toc-1] | URL parameter | Type | Required | Limitations | Details | | ------------- | -------- | -------- | ----------- | ------- | | `template_id` | `string` | yes | | | ```php use MailerSend\MailerSend; $mailersend = new MailerSend(['api_key' => 'key']); $mailersend->template->find('template_id'); ``` [More examples](https://github.com/mailersend/mailersend-php) ```javascript import 'dotenv/config'; import { MailerSend} from "mailersend"; const mailerSend = new MailerSend({ apiKey: process.env.API_KEY, }); mailerSend.email.template.single("template_id") .then((response) => console.log(response.body)) .catch((error) => console.log(error.body)); ``` [More examples](https://github.com/mailersend/mailersend-nodejs) ```python from mailersend import MailerSendClient, TemplatesBuilder ms = MailerSendClient() request = (TemplatesBuilder() .template("template-id") .build_template_get_request()) response = ms.templates.get_template(request) ``` [More examples](https://github.com/mailersend/mailersend-python) ```go package main import ( "context" "log" "time" "github.com/mailersend/mailersend-go" ) var APIKey = "Api Key Here" func main() { // Create an instance of the mailersend client ms := mailersend.NewMailersend(APIKey) ctx := context.Background() ctx, cancel := context.WithTimeout(ctx, 5*time.Second) defer cancel() templateID := "template-id" _, _, err := ms.Template.Get(ctx, templateID) if err != nil { log.Fatal(err) } } ``` [More examples](https://github.com/mailersend/mailersend-go) ```java import com.mailersend.sdk.MailerSend; import com.mailersend.sdk.MailerSendResponse; import com.mailersend.sdk.exceptions.MailerSendException; import com.mailersend.sdk.templates.Template; import com.mailersend.sdk.templates.TemplateItem; import com.mailersend.sdk.templates.TemplatesList; public void getTemplate() { MailerSend ms = new MailerSend(); ms.setToken("mailersend token"); try { Template template = ms.templates().getTemplate("template id"); System.out.println(template.id); System.out.println(template.name); System.out.println(template.imagePath); } catch (MailerSendException e) { e.printStackTrace(); } } ``` [More examples](https://github.com/mailersend/mailersend-java) ```ruby require "mailersend-ruby" ms_templates = Mailersend::Templates.new ms_templates.single(template_id: "id124") ``` [More examples](https://github.com/mailersend/mailersend-ruby) ### Responses [#responses-1] #### Valid [#valid-1] ```json { "data": { "id": "x8emy5o5world01w", "name": "libero", "description": null, "type": "html", "image_path": "http://mailersend.com/images/templates/placeholder.png", "variables": { "name": "", "elements": [ { "name": "", "price": "" } ], "license_key": "", "account_name": "", "product_name": "", "renew_button": "", "expiration_date": "" }, "tags": ["transactional"], "created_at": "2021-06-22T15:38:51.000000Z", "updated_at": "2021-06-22T16:00:00.000000Z", "category": { "id": "5genxmqlgozlyvk7", "name": "aut" }, "domain": { "id": "1jreeo", "name": "domain.com", "...", "domain_settings": { "..." }, "totals": { "hard_bounced": 25, "soft_bounced": 40, "sent": 231, "delivered": 109 } }, "template_stats": { "total": 0, "queued": 0, "sent": 0, "rejected": 0, "delivered": 0, "last_email_sent_at": null } } } ``` #### Error [#error] ```http Response Code: 404 Not Found ``` ## Create a template [#create-a-template] Create a new template using this `POST` request: ```http POST https://api.mailersend.com/v1/templates ``` ```php use MailerSend\MailerSend; use MailerSend\Helpers\Builder\TemplateParams; $mailersend = new MailerSend(['api_key' => 'key']); $params = (new TemplateParams()) ->setName('My Template') ->setHtml('

Hello {{name}}

') ->setText('Hello {{name}}') ->setDomainId('domain_id') ->setCategories(['category_id']) ->setTags(['transactional', 'welcome']); $mailersend->template->create($params); ``` [More examples](https://github.com/mailersend/mailersend-php) ```javascript import 'dotenv/config'; import { MailerSend, EmailTemplate } from "mailersend"; const mailerSend = new MailerSend({ apiKey: process.env.API_KEY, }); const template = new EmailTemplate() .setName("My Template") .setHtml("

Hello {{name}}

") .setText("Hello {{name}}") .setDomainId("domain_id") .setCategories(["category_id"]) .setTags(["transactional", "welcome"]); mailerSend.email.template.create(template) .then((response) => console.log(response.body)) .catch((error) => console.log(error.body)); ``` [More examples](https://github.com/mailersend/mailersend-nodejs)
```python from mailersend import MailerSendClient, TemplatesBuilder ms = MailerSendClient() request = (TemplatesBuilder() .name("My Template") .html("

Hello {{name}}

") .text("Hello {{name}}") .domain_id("domain-id") .categories(["category-id"]) .tags(["transactional", "welcome"]) .build_template_create_request()) response = ms.templates.create_template(request) ``` [More examples](https://github.com/mailersend/mailersend-python)
```go package main import ( "context" "log" "time" "github.com/mailersend/mailersend-go" ) var APIKey = "Api Key Here" func main() { // Create an instance of the mailersend client ms := mailersend.NewMailersend(APIKey) ctx := context.Background() ctx, cancel := context.WithTimeout(ctx, 5*time.Second) defer cancel() createOptions := &mailersend.CreateTemplateOptions{ Name: "My Template", Html: "

Hello {{name}}

", Text: "Hello {{name}}", DomainID: "domain-id", Categories: []string{"category-id"}, Tags: []string{"transactional", "welcome"}, } _, _, err := ms.Template.Create(ctx, createOptions) if err != nil { log.Fatal(err) } } ``` [More examples](https://github.com/mailersend/mailersend-go)
```java import com.mailersend.sdk.MailerSend; import com.mailersend.sdk.exceptions.MailerSendException; import com.mailersend.sdk.templates.Template; public void createTemplate() { MailerSend ms = new MailerSend(); ms.setToken("mailersend token"); try { Template template = ms.templates().builder() .name("My Template") .html("

Hello {{name}}

") .text("Hello {{name}}") .domainId("domain-id") .addCategory("category-id") .addTag("transactional") .create(); System.out.println(template.id); System.out.println(template.name); } catch (MailerSendException e) { e.printStackTrace(); } } ``` [More examples](https://github.com/mailersend/mailersend-java)
```ruby require "mailersend-ruby" ms_templates = Mailersend::Templates.new ms_templates.create( name: "My Template", html: "

Hello {{name}}

", text: "Hello {{name}}", domain_id: "domain_id", categories: ["category_id"], tags: ["transactional", "welcome"] ) ``` [More examples](https://github.com/mailersend/mailersend-ruby)
#### Request parameters \[!toc] [#request-parameters-toc-2] *JSON parameters are provided in dot notation* | JSON Parameter | Type | Required | Limitations | Details | | --------------- | --------- | -------- | ------------------------------------ | -------------------------------------------------------------------------- | | `html` | `string` | yes | | The HTML body of the template. | | `text` | `string` | yes | | Plain text version. Auto-generated from HTML if `auto_generate` is `true`. | | `name` | `string` | no | Max: `50` | Defaults to `"Template"` if not provided. | | `domain_id` | `string` | no | | Existing hashed domain ID. Must belong to the account. | | `categories` | `array` | no | | Array of hashed category IDs. Each must belong to the account. | | `tags` | `array` | no | Max: `5` items, each max `191` chars | Array of tag strings to attach to the template. | | `auto_generate` | `boolean` | no | | If `true`, plain text is auto-generated from the HTML content. | ### Responses [#responses-2] #### Valid [#valid-2] ```http Response Code: 201 CREATED Response Headers: content-type: application/json ``` ```json { "data": { "id": "x8emy5o5world01w", "name": "My Template", "description": null, "type": "html", "image_path": "http://mailersend.com/images/templates/placeholder.png", "variables": null, "tags": ["transactional", "welcome"], "created_at": "2021-06-22T15:38:51.000000Z", "updated_at": "2021-06-22T15:38:51.000000Z", "category": null, "domain": null } } ``` #### Invalid [#invalid] ```http Response Code: 422 Unprocessable Entity ``` *See - [Validation errors](/../../general#validation-errors)* ## Update a template [#update-a-template] Update an existing template using this `PUT` request. Only templates created via API (`origin=api`) can be updated — templates created in the MailerSend app return `404`. ```http PUT https://api.mailersend.com/v1/templates/{template_id} ``` ```php use MailerSend\MailerSend; use MailerSend\Helpers\Builder\TemplateParams; $mailersend = new MailerSend(['api_key' => 'key']); $params = (new TemplateParams()) ->setName('Updated Template Name') ->setHtml('

Hello {{name}}, your updated content here.

') ->setText('Hello {{name}}, your updated content here.') ->setTags(['transactional']); $mailersend->template->update('template_id', $params); ``` [More examples](https://github.com/mailersend/mailersend-php)
```javascript import 'dotenv/config'; import { MailerSend, EmailTemplate } from "mailersend"; const mailerSend = new MailerSend({ apiKey: process.env.API_KEY, }); const template = new EmailTemplate() .setName("Updated Template Name") .setHtml("

Hello {{name}}, your updated content here.

") .setText("Hello {{name}}, your updated content here.") .setTags(["transactional"]); mailerSend.email.template.update("template_id", template) .then((response) => console.log(response.body)) .catch((error) => console.log(error.body)); ``` [More examples](https://github.com/mailersend/mailersend-nodejs)
```python from mailersend import MailerSendClient, TemplatesBuilder ms = MailerSendClient() request = (TemplatesBuilder() .template("template-id") .name("Updated Template Name") .html("

Hello {{name}}, your updated content here.

") .text("Hello {{name}}, your updated content here.") .tags(["transactional"]) .build_template_update_request()) response = ms.templates.update_template(request) ``` [More examples](https://github.com/mailersend/mailersend-python)
```go package main import ( "context" "log" "time" "github.com/mailersend/mailersend-go" ) var APIKey = "Api Key Here" func main() { // Create an instance of the mailersend client ms := mailersend.NewMailersend(APIKey) ctx := context.Background() ctx, cancel := context.WithTimeout(ctx, 5*time.Second) defer cancel() templateID := "template-id" updateOptions := &mailersend.UpdateTemplateOptions{ Name: "Updated Template Name", Html: "

Hello {{name}}, your updated content here.

", Text: "Hello {{name}}, your updated content here.", Tags: []string{"transactional"}, } _, _, err := ms.Template.Update(ctx, templateID, updateOptions) if err != nil { log.Fatal(err) } } ``` [More examples](https://github.com/mailersend/mailersend-go)
```java import com.mailersend.sdk.MailerSend; import com.mailersend.sdk.exceptions.MailerSendException; import com.mailersend.sdk.templates.Template; public void updateTemplate() { MailerSend ms = new MailerSend(); ms.setToken("mailersend token"); try { Template template = ms.templates().builder() .name("Updated Template Name") .html("

Hello {{name}}, your updated content here.

") .text("Hello {{name}}, your updated content here.") .addTag("transactional") .update("template-id"); System.out.println(template.id); System.out.println(template.name); } catch (MailerSendException e) { e.printStackTrace(); } } ``` [More examples](https://github.com/mailersend/mailersend-java)
```ruby require "mailersend-ruby" ms_templates = Mailersend::Templates.new ms_templates.update( template_id: "template_id", name: "Updated Template Name", html: "

Hello {{name}}, your updated content here.

", text: "Hello {{name}}, your updated content here.", tags: ["transactional"] ) ``` [More examples](https://github.com/mailersend/mailersend-ruby)
#### Request parameters \[!toc] [#request-parameters-toc-3] | URL parameter | Type | Required | Limitations | Details | | ------------- | -------- | -------- | ----------- | ------- | | `template_id` | `string` | yes | | | *JSON parameters are provided in dot notation* | JSON Parameter | Type | Required | Limitations | Details | | --------------- | --------- | -------- | ------------------------------------ | --------------------------------------------------------------------------- | | `html` | `string` | no | | The HTML body of the template. | | `text` | `string` | no | | Plain text version. Auto-generated from HTML if `auto_generate` is `true`. | | `name` | `string` | no | Max: `50` | | | `domain_id` | `string` | no | | Existing hashed domain ID. Must belong to the account. | | `categories` | `array` | no | | Array of hashed category IDs. Pass an empty array to remove all categories. | | `tags` | `array` | no | Max: `5` items, each max `191` chars | Array of tag strings to attach to the template. | | `auto_generate` | `boolean` | no | | If `true`, plain text is auto-generated from the HTML content. | ### Responses [#responses-3] #### Valid [#valid-3] ```http Response Code: 200 OK Response Headers: content-type: application/json ``` ```json { "data": { "id": "x8emy5o5world01w", "name": "Updated Template Name", "description": null, "type": "html", "image_path": "http://mailersend.com/images/templates/placeholder.png", "variables": null, "tags": ["transactional"], "created_at": "2021-06-22T15:38:51.000000Z", "updated_at": "2021-06-22T16:00:00.000000Z", "category": null, "domain": null } } ``` #### Invalid [#invalid-1] ```http Response Code: 422 Unprocessable Entity ``` *See - [Validation errors](/../../general#validation-errors)* #### Error [#error-1] ```http Response Code: 404 Not Found ``` ## Delete a template [#delete-a-template] Delete a template with this `DELETE` request: ```http DELETE https://api.mailersend.com/v1/templates/{template_id} ``` #### Request parameters \[!toc] [#request-parameters-toc-4] | URL parameter | Type | Required | Limitations | Details | | ------------- | ------ | -------- | ----------- | ------- | | `template_id` | string | yes | | | ```php use MailerSend\MailerSend; $mailersend = new MailerSend(['api_key' => 'key']); $mailersend->template->delete('template_id'); ``` [More examples](https://github.com/mailersend/mailersend-php) ```javascript import 'dotenv/config'; import { MailerSend} from "mailersend"; const mailerSend = new MailerSend({ apiKey: process.env.API_KEY, }); mailerSend.email.template.delete("template_id") .then((response) => console.log(response.body)) .catch((error) => console.log(error.body)); ``` [More examples](https://github.com/mailersend/mailersend-nodejs) ```python from mailersend import MailerSendClient, TemplatesBuilder ms = MailerSendClient() request = (TemplatesBuilder() .template("template-id") .build_delete_request()) response = ms.templates.delete_template(request) ``` [More examples](https://github.com/mailersend/mailersend-python) ```go package main import ( "context" "log" "time" "github.com/mailersend/mailersend-go" ) var APIKey = "Api Key Here" func main() { // Create an instance of the mailersend client ms := mailersend.NewMailersend(APIKey) ctx := context.Background() ctx, cancel := context.WithTimeout(ctx, 5*time.Second) defer cancel() templateID := "template-id" _, err := ms.Template.Delete(ctx, templateID) if err != nil { log.Fatal(err) } } ``` [More examples](https://github.com/mailersend/mailersend-go) ```java import com.mailersend.sdk.MailerSend; import com.mailersend.sdk.MailerSendResponse; import com.mailersend.sdk.exceptions.MailerSendException; import com.mailersend.sdk.templates.Template; import com.mailersend.sdk.templates.TemplateItem; import com.mailersend.sdk.templates.TemplatesList; public void deleteTemplate() { MailerSend ms = new MailerSend(); ms.setToken("mailersend token"); try { MailerSendResponse response = ms.templates().deleteTemplate("template id"); System.out.println(response.responseStatusCode); } catch (MailerSendException e) { e.printStackTrace(); } } ``` [More examples](https://github.com/mailersend/mailersend-java) ```ruby require "mailersend-ruby" ms_templates = Mailersend::Templates.new ms_templates.delete(template_id: "id124") ``` [More examples](https://github.com/mailersend/mailersend-ruby) ### Responses [#responses-4] #### Valid [#valid-4] ```http Response Code: 200 OK Response Body: [EMPTY] ``` #### Error [#error-2] ```http Response Code: 404 Not Found ``` ## Email Survey Templates [#email-survey-templates] Using our drag-and-drop email [builder](https://app.mailersend.com/templates/gallery/dd), you may create email templates with a survey block to ask questions and reviews to your recipients. When your recipient receives an email with a survey, they can preview the email and answer your survey questions. Then the responses are sent to your webhook if available.\ \ When a recipient answers all available survey questions the responses are immediately sent to your webhook(if available). However, when a recipient doesn't completely answer all available questions, after an idle time of `30` minutes, the responses would be sent.\ \ Rules and steps for sending an email with a survey include: * You cannot use the following variables `{{url}}`, `{{survey}}`, `{{survey_last_question}}`, as they are reserved. * You must enable `content_tracking` on your domain by selecting your domain and enabling the setting under tracking details. Content tracking is a feature available on Starter plans and above. * Add a webhook with the `activity.survey_submitted` event to receive the survey answers. * You can also include the `activity.survey_opened` event in your webhook to know when a recipient has opened an email containing a survey at least once. ### Payloads [#payloads] #### Example of `activity.survey_submitted` data sent to your webhook: [#example-of-activitysurvey_submitted-data-sent-to-your-webhook] ```json { "type": "activity.survey_submitted", "created_at": "2025-08-06T00:20:36.589903Z", "data": { "id": "68929fd47f916891ef12eba9", "domain_id": "7nxe3yjmeq28vp0k", "message_id": "68929fd402fd7079a02cf858", "email_id": "68929fd47f916891ef12eba9", "type": "survey_submitted", "subject": "Test email", "from": "test@domain.com", "tags": [ "test2", "test3" ], "meta": { "surveys": [ { "question_id": 1, "survey_id": 1, "answer": "test", "is_last_question": true } ] } } } ```