📧 Emails module Email API
This module allows you to send emails and check domain settings for secure email delivery.
Send method
Sends an email message to one or more recipients.
Usage
import { MailChannelsClient, Emails } from 'mailchannels-sdk'
const mailchannels = new MailChannelsClient('your-api-key')
const emails = new Emails(mailchannels)
const { success, data } = await emails.send({
from: 'from@example.com',
to: 'to@example.com',
subject: 'Your subject',
html: '<p>Your email content</p>',
text: 'Your email content',
})import { MailChannels } from 'mailchannels-sdk'
const mailchannels = new MailChannels('your-api-key')
const { success, data } = await mailchannels.emails.send({
from: 'from@example.com',
to: 'to@example.com',
subject: 'Your subject',
html: '<p>Your email content</p>',
text: 'Your email content',
})Params
optionsEmailsSendOptionsrequired: Send optionsEmailsSendOptions.attachmentsEmailsSendAttachment[]optional: An array of attachments to be sent with the email.contentstringrequired: The attachment data, encoded in Base64.filenamestringrequired: The name of the attachment file.typestringrequired: The MIME type of the attachment.
campaignIdstringoptional: The campaign identifier. If specified, this ID will be included in all relevant webhooks. It can be up to 48 UTF-8 characters long and must not contain spaces.bccEmailsSendRecipient[] | EmailsSendRecipient | string[] | stringoptional: The BCC recipients of the email.ccEmailsSendRecipient[] | EmailsSendRecipient | string[] | stringoptional: The CC recipients of the email.dkimobjectoptional: The DKIM settings for the email.domainstringrequired: The domain to sign the email with.privateKeystringoptional: The private key to sign the email with. Can be undefined if the domain has an active DKIM key.selectorstringrequired: The DKIM selector to use.
fromEmailsSendRecipient | stringrequired: The sender of the email.headersRecord<string, string>optional: An object containing key-value pairs, where both keys (header names) and values must be strings. These pairs represent custom headers to be substituted.IMPORTANT
Please note the following restrictions and behavior:
- Reserved headers: The following headers cannot be modified:
Authentication-Results,BCC,CC,Content-Transfer-Encoding,Content-Type,DKIM-Signature,From,Message-ID,Received,Reply-To,Subject,To. - Header precedence: If a header is defined in both the personalizations object and the root headers, the value from personalizations will be used.
- Case sensitivity: Headers are treated as case-insensitive. If multiple headers differ only by case, only one will be used, with no guarantee of which one.
- Reserved headers: The following headers cannot be modified:
toEmailsSendRecipient[] | EmailsSendRecipient | string[] | stringrequired: The recipients of the email.trackingEmailsSendTrackingoptional: Adjust open and click tracking for the message.INFO
Tracking for your messages requires a subscription that supports open and click tracking.
Only links (
<a>tags) meeting all of the following conditions are processed for click tracking:- The URL is non-empty.
- The URL starts with
httporhttps. - The link does not have a
clicktrackingattribute set tooff.
replyToEmailsSendRecipient | stringoptional: The reply-to address of the email.subjectstringrequired: The subject of the email.htmlstringoptional: The HTML content of the email. Required iftextis not set.textstringoptional: The plain text content of the email. Required ifhtmlis not set.IMPORTANT
Either
htmlortextmust be provided.TIP
Including a plain text version of your email ensures that all recipients can read your message, including those with email clients that lack HTML support.
You can use the
html-to-textpackage to convert your HTML content to plain text.mustachesRecord<string, unknown>optional: Data to be used if the email is a mustache template, key-value pairs of variables to set for template rendering.transactionalbooleanoptional: Mark these messages as transactional or non-transactional. In order for a message to be marked as non-transactional, it must have exactly one recipient per personalization, and it must be DKIM signed. 400 Bad Request will be returned if there are more than one recipient in any personalization for non-transactional messages. If a message is marked as non-transactional, it changes the sending process as follows: List-Unsubscribe headers will be added.
dryRunbooleanoptional: When set totrue, the email will not be sent. Instead, the fully rendered message will be returned in thedata.renderedproperty of the response.TIP
Use
dryRunto test your email message before sending it.
Response
successbooleanguaranteed: Indicates if the email was successfully sent.dataobject | nullnullablerenderedstring[]optional: Fully rendered message ifdryRunwas set totrue. A string representation of a rendered message.requestIdstringoptional: The Request ID is a unique identifier generated by the service to track the HTTP request. It will also be included in all webhooks for reference.resultsobjectoptional:indexnumberoptional: The index of the personalization in the request. Starts at 0.messageIdstringguaranteed: The Message ID is a unique identifier generated by the service. Each personalization has a distinct Message ID, which is also used in theMessage-Idheader and included in webhooks.reasonstringoptional: A human-readable explanation of the status.status"sent" | "failed"guaranteed: The status of the message. Note that 'sent' is a temporary status; the final status will be provided through webhooks, if configured.
errorstring | nullnullable: An error message if the email failed to send.
Check Domain method
DKIM, SPF & Domain Lockdown Check
Validates a domain's email authentication setup by retrieving its DKIM, SPF, and Domain Lockdown status. This method checks whether the domain is properly configured for secure email delivery.
Usage
import { MailChannelsClient, Emails } from 'mailchannels-sdk'
const mailchannels = new MailChannelsClient('your-api-key')
const emails = new Emails(mailchannels)
const { data, error } = await emails.checkDomain({
domain: 'example.com',
dkim: {
domain: 'example.com',
selector: 'your-dkim-selector',
privateKey: 'your-dkim-private-key'
},
senderId: 'your-sender-id'
})import { MailChannels } from 'mailchannels-sdk'
const mailchannels = new MailChannels('your-api-key')
const { data, error } = await mailchannels.emails.checkDomain({
domain: 'example.com',
dkim: {
domain: 'example.com',
selector: 'your-dkim-selector',
privateKey: 'your-dkim-private-key'
},
senderId: 'your-sender-id'
})Params
optionsEmailsCheckDomainOptionsrequired: Check domain options.dkimEmailsCheckDomainDkim[] | EmailsCheckDomainDkimoptional: The DKIM settings for the domain.domainstringoptional: The DKIM domain to sign the email with.privateKeystringoptional: The DKIM private key to sign the email with. Encoded in Base64.selectorstringoptional: The DKIM selector to use.
TIP
The absence or presence of these fields affects how DKIM settings are validated:
- If
domain,selector, andprivateKeyare all present, verify using the provided domain, selector, and key. - If
domainandselectorare present, use the stored private key for the given domain and selector. - If only
domainis present, use all stored keys for the given domain. - If none are present, use all stored keys for the
domainprovided in the domain field of the request. - If
privateKeyis present,selectormust be present. - If
selectoris present anddomainis not, the domain will be taken from the domain field of the request.
domainstringrequired: Domain used for sending emails. Ifdkimsettings are not provided, ordkimsettings are provided with nodomain, the stored dkim settings for this domain will be used.senderIdstringoptional: Used exclusively for Domain Lockdown verification. If you're not using senderid to associate your domain with your account, you can disregard this field.INFO
Your
senderIdis theX-MailChannels-Sender-Idheader value in emails sent via MailChannels.
Response
dataobject | nullnullable: The results of the domain checks.dkimobject[]guaranteeddomainstringguaranteedkeyStatus"active" | "revoked" | "retired" | "provided" | "rotated"guaranteed: The human readable status of the DKIM key used for verification.selectorstringguaranteedreasonstringoptional: A human-readable explanation of DKIM check.verdict"passed" | "failed"guaranteed
domainLockdownobjectguaranteedreasonstringoptional: A human-readable explanation of Domain Lockdown check.verdict"passed" | "failed"guaranteed
senderDomainobjectguaranteed: These results are here to help avoid SDNF (Sender Domain Not Found) blocks. For messages not to get blocked by SDNF, we require either an MX or A record to exist for the sender domain.aobjectguaranteedreasonstringoptional: A human-readable explanation of A record check.verdict"passed" | "failed"guaranteed
mxobjectguaranteedreasonstringoptional: A human-readable explanation of MX record check.verdict"passed" | "failed"guaranteed
spfobjectguaranteedreasonstringoptional: A human-readable explanation of SPF check.verdict"passed" | "failed" | "soft failed" | "temporary error" | "permanent error" | "neutral" | "none" | "unknown"guaranteed
referencesstring[]optional
errorstring | nullnullable: An error message if the operation failed. Link to SPF, Domain Lockdown or DKIM references, displayed if any verdict is not passed.
Create DKIM Key method
Create a DKIM key pair for a specified domain and selector using the specified algorithm and key length, for the current customer.
Usage
import { MailChannelsClient, Emails } from 'mailchannels-sdk'
const mailchannels = new MailChannelsClient('your-api-key')
const emails = new Emails(mailchannels)
const { data, error } = await emails.createDkimKey('example.com', {
selector: 'mailchannels'
})import { MailChannels } from 'mailchannels-sdk'
const mailchannels = new MailChannels('your-api-key')
const { data, error } = await mailchannels.emails.createDkimKey('example.com', {
selector: 'mailchannels'
})Params
domainstringrequired: The domain to create the DKIM key for.optionsEmailsCreateDkimKeyOptionsrequired: Create DKIM key options.algorithm"rsa"optional: Algorithm used for the new key pair Currently, only RSA is supported. Defaults torsa.length1024 | 2048 | 3072 | 4096optional: Key length in bits. For RSA, must be a multiple of1024.TIP
Defaults to
2048. Common values:1024or2048.selectorstringrequired: Selector for the new key pair. Must be a maximum of 63 characters.
Response
dataEmailsDkimKey | nullnullable: The created DKIM key information.algorithmstringguaranteed: Algorithm used for the key pair.createdAtstringoptional: Timestamp when the key pair was created.dnsRecordsobject[]guaranteed: Suggested DNS records for the DKIM key.namestringguaranteedtypestringguaranteedvaluestringguaranteed
domainstringguaranteed: Domain associated with the key pair.gracePeriodExpiresAtstringoptional: UTC timestamp after which you can no longer use the rotated key for signing.length1024 | 2048 | 3072 | 4096guaranteed: Key length in bits.publicKeystringguaranteedretiresAtstringoptional: UTC timestamp when a rotated key pair is retired.selectorstringguaranteed: Selector assigned to the key pair.status"active" | "revoked" | "retired" | "rotated"guaranteed: Status of the key.statusModifiedAtstringoptional: Timestamp when the key was last modified.
errorstring | nullnullable: An error message if the operation failed.
Get DKIM Keys method
Search for DKIM keys by domain, with optional filters. If selector is provided, at most one key will be returned.
Usage
import { MailChannelsClient, Emails } from 'mailchannels-sdk'
const mailchannels = new MailChannelsClient('your-api-key')
const emails = new Emails(mailchannels)
const { data, error } = await emails.getDkimKeys('example.com', {
includeDnsRecord: true
})import { MailChannels } from 'mailchannels-sdk'
const mailchannels = new MailChannels('your-api-key')
const { data, error } = await mailchannels.emails.getDkimKeys('example.com', {
includeDnsRecord: true
})Params
domainstringrequired: The domain to get the DKIM keys for.optionsEmailsGetDkimKeysOptionsoptional: Optional filter options.selectorstringoptional: Selector to filter keys by. Must be a maximum of 63 characters.status"active" | "revoked" | "retired" | "rotated"optional: Status to filter keys by.TIP
Possible values:
active,revoked,retired,rotated.offsetnumberoptional: Number of results to skip from the start. Must be a positive integer. Defaults to0.limitnumberoptional: Maximum number of keys to return. Maximum is100and minimum is1. Defaults to10.includeDnsRecordbooleanoptional: Iftrue, includes the suggested DKIM DNS record for each returned key. Defaults tofalse.
Response
dataOptional<EmailsDkimKey, "dnsRecords">[] | nullnullable: List of keys matching the filter. Empty if no keys match the filter.algorithmstringguaranteed: Algorithm used for the key pair.createdAtstringoptional: Timestamp when the key pair was created.dnsRecordsobject[]optional: Suggested DNS records for the DKIM key. Only included ifincludeDnsRecordistrue.namestringguaranteedtypestringguaranteedvaluestringguaranteed
domainstringguaranteed: Domain associated with the key pair.gracePeriodExpiresAtstringoptional: UTC timestamp after which you can no longer use the rotated key for signing.length1024 | 2048 | 3072 | 4096guaranteed: Key length in bits.publicKeystringguaranteedretiresAtstringoptional: UTC timestamp when a rotated key pair is retired.selectorstringguaranteed: Selector assigned to the key pair.status"active" | "revoked" | "retired" | "rotated"guaranteed: Status of the key.statusModifiedAtstringoptional: Timestamp when the key was last modified.
errorstring | nullnullable: An error message if the operation failed.
Update DKIM Key method
Update fields of an existing DKIM key pair for the specified domain and selector, for the current customer. Currently, only the status field can be updated.
Usage
import { MailChannelsClient, Emails } from 'mailchannels-sdk'
const mailchannels = new MailChannelsClient('your-api-key')
const emails = new Emails(mailchannels)
const { success, error } = await emails.updateDkimKey('example.com', {
selector: 'mailchannels',
status: 'retired'
})import { MailChannels } from 'mailchannels-sdk'
const mailchannels = new MailChannels('your-api-key')
const { success, error } = await mailchannels.emails.updateDkimKey('example.com', {
selector: 'mailchannels',
status: 'retired'
})Params
domainstringrequired: The domain of the DKIM key to update.optionsEmailsUpdateDkimKeyOptionsrequired: Update DKIM key options.selectorstringrequired: Selector of the DKIM key to update. Must be a maximum of 63 characters.status"revoked" | "retired" | "rotated"required: New status of the DKIM key pair.TIP
Possible values:
revoked,retired,rotated.revoked: Indicates that the key is compromised and should not be used.retired: Indicates that the key has been rotated and is no longer in use.rotated: Indicates that the key is going through the rotation process. Only active key pairs can be updated to this status, and no new key pair is created. The rotated key can be used to sign emails for 3 days after the status update, and will automatically change toretired2 weeks after update. For a smooth key transition, it is recommended to create and publish a new key pair before signing is disabled for the rotated key.
Response
successbooleanguaranteed: Whether the operation was successful.errorstring | nullnullable: An error message if the operation failed.
Rotate DKIM Key method
Rotate an active DKIM key pair. Mark the original key as rotated, and create a new key pair with the required new key selector, reusing the same algorithm and key length. The rotated key remains valid for signing for a 3-day grace period, and is automatically changed to retired 2 weeks after rotation. Publish the new key to its DNS TXT record before rotated key expires for signing as emails sent with an unpublished key will fail DKIM validation by receiving providers. After the grace period, only the new key is valid for signing if published.
Usage
import { MailChannelsClient, Emails } from 'mailchannels-sdk'
const mailchannels = new MailChannelsClient('your-api-key')
const emails = new Emails(mailchannels)
const { data, error } = await emails.rotateDkimKey('example.com', 'mailchannels', {
newKey: {
selector: 'new-selector'
}
})import { MailChannels } from 'mailchannels-sdk'
const mailchannels = new MailChannels('your-api-key')
const { data, error } = await mailchannels.emails.rotateDkimKey('example.com', 'mailchannels', {
newKey: {
selector: 'new-selector'
}
})Params
domainstringrequired: The domain the DKIM key belongs to.selectorstringrequired: The selector of the DKIM key to rotate. Must be a maximum of 63 characters.optionsobjectrequired: The options to rotate the DKIM key.newKeyobjectrequired: New DKIM key options.selectorstringrequired: The selector for the new key pair. Must be a maximum of 63 characters.
Response
dataobject | nullnullable: The rotated and new DKIM key information.newEmailsDkimKeyguaranteedalgorithmstringguaranteed: Algorithm used for the key pair.createdAtstringoptional: Timestamp when the key pair was created.dnsRecordsobject[]guaranteed: Suggested DNS records for the DKIM key.namestringguaranteedtypestringguaranteedvaluestringguaranteed
domainstringguaranteed: Domain associated with the key pair.gracePeriodExpiresAtstringoptional: UTC timestamp after which you can no longer use the rotated key for signing.length1024 | 2048 | 3072 | 4096guaranteed: Key length in bits.publicKeystringguaranteedretiresAtstringoptional: UTC timestamp when a rotated key pair is retired.selectorstringguaranteed: Selector assigned to the key pair.status"active" | "revoked" | "retired" | "rotated"guaranteed: Status of the key.statusModifiedAtstringoptional: Timestamp when the key was last modified.
rotatedEmailsDkimKeyguaranteedalgorithmstringguaranteed: Algorithm used for the key pair.createdAtstringoptional: Timestamp when the key pair was created.dnsRecordsobject[]guaranteed: Suggested DNS records for the DKIM key.namestringguaranteedtypestringguaranteedvaluestringguaranteed
domainstringguaranteed: Domain associated with the key pair.gracePeriodExpiresAtstringoptional: UTC timestamp after which you can no longer use the rotated key for signing.length1024 | 2048 | 3072 | 4096guaranteed: Key length in bits.publicKeystringguaranteedretiresAtstringoptional: UTC timestamp when a rotated key pair is retired.selectorstringguaranteed: Selector assigned to the key pair.status"active" | "revoked" | "retired" | "rotated"guaranteed: Status of the key.statusModifiedAtstringoptional: Timestamp when the key was last modified.
errorstring | nullnullable: An error message if the operation failed.
Type declarations
class Emails {
constructor (protected mailchannels: MailChannelsClient);
async send (options: EmailsSendOptions, dryRun?: boolean): Promise<EmailsSendResponse>;
async checkDomain (options: EmailsCheckDomainOptions): Promise<EmailsCheckDomainResponse>;
async createDkimKey (domain: string, options: EmailsCreateDkimKeyOptions): Promise<EmailsCreateDkimKeyResponse>;
async getDkimKeys (domain: string, options?: EmailsGetDkimKeysOptions): Promise<EmailsGetDkimKeysResponse>;
async updateDkimKey (domain: string, options: EmailsUpdateDkimKeyOptions): Promise<SuccessResponse>;
async rotateDkimKey (domain: string, selector: string, options: EmailsRotateDkimKeyOptions): Promise<EmailsRotateDkimKeyResponse>;
}All type declarations
Responses
interface DataResponse<T> {
data: T | null;
error: string | null;
}interface SuccessResponse {
success: boolean;
error: string | null;
}Send type declarations
type EmailsSendOptions = EmailsSendOptionsBase & (
| {
html: string;
text?: string;
}
| {
html?: string;
text: string;
}
);interface EmailsSendOptionsBase {
attachments?: EmailsSendAttachment[];
campaignId?: string;
bcc?: EmailsSendRecipient[] | EmailsSendRecipient | string[] | string;
cc?: EmailsSendRecipient[] | EmailsSendRecipient | string[] | string;
dkim?: {
domain: string;
privateKey?: string;
selector: string;
};
from: EmailsSendRecipient | string;
headers?: Record<string, string>;
to: EmailsSendRecipient[] | EmailsSendRecipient | string[] | string;
tracking?: EmailsSendTracking;
replyTo?: EmailsSendRecipient | string;
subject: string;
mustaches?: Record<string, unknown>;
transactional?: boolean;
}interface EmailsSendAttachment {
content: string;
filename: string;
type: string;
}interface EmailsSendRecipient {
email: string;
name?: string;
}interface EmailsSendTracking {
click?: boolean;
open?: boolean;
}interface EmailsSendResponse {
success: boolean;
data: {
rendered?: string[];
requestId?: string;
results?: {
index?: number;
messageId: string;
reason?: string;
status: "sent" | "failed";
}[];
} | null;
error: string | null;
}Check Domain type declarations
interface EmailsCheckDomainOptions {
dkim?: EmailsCheckDomainDkim[] | EmailsCheckDomainDkim;
domain: string;
senderId?: string;
}type EmailsCheckDomainResponse = DataResponse<{
dkim: {
domain: string;
keyStatus?: EmailsDkimKey["status"] | "provided";
selector: string;
reason?: string;
verdict: Extract<EmailsCheckDomainVerdict, "passed" | "failed">;
}[];
domainLockdown: {
reason?: string;
verdict: Extract<EmailsCheckDomainVerdict, "passed" | "failed">;
};
senderDomain: {
a: {
reason?: string;
verdict: Extract<EmailsCheckDomainVerdict, "passed" | "failed">;
};
mx: {
reason?: string;
verdict: Extract<EmailsCheckDomainVerdict, "passed" | "failed">;
};
verdict: Extract<EmailsCheckDomainVerdict, "passed" | "failed">;
};
spf: {
reason?: string;
verdict: EmailsCheckDomainVerdict;
};
references?: string[];
}>;type EmailsCheckDomainVerdict = "passed" | "failed" | "soft failed" | "temporary error" | "permanent error" | "neutral" | "none" | "unknown";interface EmailsCheckDomainDkim {
domain?: string;
privateKey?: string;
selector?: string;
}Create DKIM Key type declarations
interface EmailsCreateDkimKeyOptions {
algorithm?: "rsa";
length?: 1024 | 2048 | 3072 | 4096;
selector: string;
}type EmailsDkimKeyStatus = "active" | "retired" | "revoked" | "rotated";interface EmailsDkimKey {
algorithm: string;
createdAt?: string;
dnsRecords: {
name: string;
type: string;
value: string;
}[];
domain: string;
gracePeriodExpiresAt?: string;
length: 1024 | 2048 | 3072 | 4096;
publicKey: string;
retiresAt?: string;
selector: string;
status: EmailsDkimKeyStatus;
statusModifiedAt?: string;
}type EmailsCreateDkimKeyResponse = DataResponse<EmailsDkimKey>;Get DKIM Keys type declarations
interface EmailsGetDkimKeysOptions {
selector?: string;
status?: EmailsDkimKey["status"];
offset?: number;
limit?: number;
includeDnsRecord?: boolean;
}type Optional<T, K extends keyof T> = Omit<T, K> & Partial<Pick<T, K>>;type EmailsGetDkimKeysResponse = DataResponse<Optional<EmailsDkimKey, "dnsRecords">[]>;Update DKIM Key type declarations
interface EmailsUpdateDkimKeyOptions {
selector: string;
status: Exclude<EmailsDkimKey["status"], "active">;
}Rotate DKIM Key type declarations
interface EmailsRotateDkimKeyOptions {
newKey: {
selector: string;
};
}type EmailsRotateDkimKeyResponse = DataResponse<{
new: EmailsDkimKey;
rotated: EmailsDkimKey;
}>;Source
Source • Playground • Docs