Skip to content

📧 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

ts
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',
})
ts
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

  • options EmailsSendOptions required: Send options EmailsSendOptions.
    • attachments EmailsSendAttachment[] optional: An array of attachments to be sent with the email.
      • content string required: The attachment data, encoded in Base64.
      • filename string required: The name of the attachment file.
      • type string required: The MIME type of the attachment.
    • campaignId string optional: 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.
    • bcc EmailsSendRecipient[] | EmailsSendRecipient | string[] | string optional: The BCC recipients of the email.
    • cc EmailsSendRecipient[] | EmailsSendRecipient | string[] | string optional: The CC recipients of the email.
    • dkim object optional: The DKIM settings for the email.
      • domain string required: The domain to sign the email with.
      • privateKey string optional: The private key to sign the email with. Can be undefined if the domain has an active DKIM key.
      • selector string required: The DKIM selector to use.
    • from EmailsSendRecipient | string required: The sender of the email.
    • headers Record<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.
    • to EmailsSendRecipient[] | EmailsSendRecipient | string[] | string required: The recipients of the email.
    • tracking EmailsSendTracking optional: 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 http or https.
      • The link does not have a clicktracking attribute set to off.
    • replyTo EmailsSendRecipient | string optional: The reply-to address of the email.
    • subject string required: The subject of the email.
    • html string optional: The HTML content of the email. Required if text is not set.
    • text string optional: The plain text content of the email. Required if html is not set.

      IMPORTANT

      Either html or text must 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-text package to convert your HTML content to plain text.

    • mustaches Record<string, unknown> optional: Data to be used if the email is a mustache template, key-value pairs of variables to set for template rendering.
    • transactional boolean optional: 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.
  • dryRun boolean optional: When set to true, the email will not be sent. Instead, the fully rendered message will be returned in the data.rendered property of the response.

    TIP

    Use dryRun to test your email message before sending it.

Response

  • success boolean guaranteed: Indicates if the email was successfully sent.
  • data object | null nullable
    • rendered string[] optional: Fully rendered message if dryRun was set to true. A string representation of a rendered message.
    • requestId string optional: 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.
    • results object optional:
      • index number optional: The index of the personalization in the request. Starts at 0.
      • messageId string guaranteed: The Message ID is a unique identifier generated by the service. Each personalization has a distinct Message ID, which is also used in the Message-Id header and included in webhooks.
      • reason string optional: 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.
  • error string | null nullable: 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

ts
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'
})
ts
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

  • options EmailsCheckDomainOptions required: Check domain options.
    • dkim EmailsCheckDomainDkim[] | EmailsCheckDomainDkim optional: The DKIM settings for the domain.
      • domain string optional: The DKIM domain to sign the email with.
      • privateKey string optional: The DKIM private key to sign the email with. Encoded in Base64.
      • selector string optional: The DKIM selector to use.

      TIP

      The absence or presence of these fields affects how DKIM settings are validated:

      1. If domain, selector, and privateKey are all present, verify using the provided domain, selector, and key.
      2. If domain and selector are present, use the stored private key for the given domain and selector.
      3. If only domain is present, use all stored keys for the given domain.
      4. If none are present, use all stored keys for the domain provided in the domain field of the request.
      5. If privateKey is present, selector must be present.
      6. If selector is present and domain is not, the domain will be taken from the domain field of the request.
    • domain string required: Domain used for sending emails. If dkim settings are not provided, or dkim settings are provided with no domain, the stored dkim settings for this domain will be used.
    • senderId string optional: 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 senderId is the X-MailChannels-Sender-Id header value in emails sent via MailChannels.

Response

  • data object | null nullable: The results of the domain checks.
    • dkim object[] guaranteed
      • domain string guaranteed
      • keyStatus "active" | "revoked" | "retired" | "provided" | "rotated" guaranteed: The human readable status of the DKIM key used for verification.
      • selector string guaranteed
      • reason string optional: A human-readable explanation of DKIM check.
      • verdict "passed" | "failed" guaranteed
    • domainLockdown object guaranteed
      • reason string optional: A human-readable explanation of Domain Lockdown check.
      • verdict "passed" | "failed" guaranteed
    • senderDomain object guaranteed: 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.
      • a object guaranteed
        • reason string optional: A human-readable explanation of A record check.
        • verdict "passed" | "failed" guaranteed
      • mx object guaranteed
        • reason string optional: A human-readable explanation of MX record check.
        • verdict "passed" | "failed" guaranteed
    • spf object guaranteed
      • reason string optional: A human-readable explanation of SPF check.
      • verdict "passed" | "failed" | "soft failed" | "temporary error" | "permanent error" | "neutral" | "none" | "unknown" guaranteed
    • references string[] optional
  • error string | null nullable: 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

ts
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'
})
ts
import { MailChannels } from 'mailchannels-sdk'

const mailchannels = new MailChannels('your-api-key')

const { data, error } = await mailchannels.emails.createDkimKey('example.com', {
  selector: 'mailchannels'
})

Params

  • domain string required: The domain to create the DKIM key for.
  • options EmailsCreateDkimKeyOptions required: Create DKIM key options.
    • algorithm "rsa" optional: Algorithm used for the new key pair Currently, only RSA is supported. Defaults to rsa.
    • length 1024 | 2048 | 3072 | 4096 optional: Key length in bits. For RSA, must be a multiple of 1024.

      TIP

      Defaults to 2048. Common values: 1024 or 2048.

    • selector string required: Selector for the new key pair. Must be a maximum of 63 characters.

Response

  • data EmailsDkimKey | null nullable: The created DKIM key information.
    • algorithm string guaranteed: Algorithm used for the key pair.
    • createdAt string optional: Timestamp when the key pair was created.
    • dnsRecords object[] guaranteed: Suggested DNS records for the DKIM key.
      • name string guaranteed
      • type string guaranteed
      • value string guaranteed
    • domain string guaranteed: Domain associated with the key pair.
    • gracePeriodExpiresAt string optional: UTC timestamp after which you can no longer use the rotated key for signing.
    • length 1024 | 2048 | 3072 | 4096 guaranteed: Key length in bits.
    • publicKey string guaranteed
    • retiresAt string optional: UTC timestamp when a rotated key pair is retired.
    • selector string guaranteed: Selector assigned to the key pair.
    • status "active" | "revoked" | "retired" | "rotated" guaranteed: Status of the key.
    • statusModifiedAt string optional: Timestamp when the key was last modified.
  • error string | null nullable: 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

ts
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
})
ts
import { MailChannels } from 'mailchannels-sdk'

const mailchannels = new MailChannels('your-api-key')

const { data, error } = await mailchannels.emails.getDkimKeys('example.com', {
  includeDnsRecord: true
})

Params

  • domain string required: The domain to get the DKIM keys for.
  • options EmailsGetDkimKeysOptions optional: Optional filter options.
    • selector string optional: 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.

    • offset number optional: Number of results to skip from the start. Must be a positive integer. Defaults to 0.
    • limit number optional: Maximum number of keys to return. Maximum is 100 and minimum is 1. Defaults to 10.
    • includeDnsRecord boolean optional: If true, includes the suggested DKIM DNS record for each returned key. Defaults to false.

Response

  • data Optional<EmailsDkimKey, "dnsRecords">[] | null nullable: List of keys matching the filter. Empty if no keys match the filter.
    • algorithm string guaranteed: Algorithm used for the key pair.
    • createdAt string optional: Timestamp when the key pair was created.
    • dnsRecords object[] optional: Suggested DNS records for the DKIM key. Only included if includeDnsRecord is true.
      • name string guaranteed
      • type string guaranteed
      • value string guaranteed
    • domain string guaranteed: Domain associated with the key pair.
    • gracePeriodExpiresAt string optional: UTC timestamp after which you can no longer use the rotated key for signing.
    • length 1024 | 2048 | 3072 | 4096 guaranteed: Key length in bits.
    • publicKey string guaranteed
    • retiresAt string optional: UTC timestamp when a rotated key pair is retired.
    • selector string guaranteed: Selector assigned to the key pair.
    • status "active" | "revoked" | "retired" | "rotated" guaranteed: Status of the key.
    • statusModifiedAt string optional: Timestamp when the key was last modified.
  • error string | null nullable: 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

ts
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'
})
ts
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

  • domain string required: The domain of the DKIM key to update.
  • options EmailsUpdateDkimKeyOptions required: Update DKIM key options.
    • selector string required: 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 to retired 2 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

  • success boolean guaranteed: Whether the operation was successful.
  • error string | null nullable: 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

ts
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'
  }
})
ts
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

  • domain string required: The domain the DKIM key belongs to.
  • selector string required: The selector of the DKIM key to rotate. Must be a maximum of 63 characters.
  • options object required: The options to rotate the DKIM key.
    • newKey object required: New DKIM key options.
      • selector string required: The selector for the new key pair. Must be a maximum of 63 characters.

Response

  • data object | null nullable: The rotated and new DKIM key information.
    • new EmailsDkimKey guaranteed
      • algorithm string guaranteed: Algorithm used for the key pair.
      • createdAt string optional: Timestamp when the key pair was created.
      • dnsRecords object[] guaranteed: Suggested DNS records for the DKIM key.
        • name string guaranteed
        • type string guaranteed
        • value string guaranteed
      • domain string guaranteed: Domain associated with the key pair.
      • gracePeriodExpiresAt string optional: UTC timestamp after which you can no longer use the rotated key for signing.
      • length 1024 | 2048 | 3072 | 4096 guaranteed: Key length in bits.
      • publicKey string guaranteed
      • retiresAt string optional: UTC timestamp when a rotated key pair is retired.
      • selector string guaranteed: Selector assigned to the key pair.
      • status "active" | "revoked" | "retired" | "rotated" guaranteed: Status of the key.
      • statusModifiedAt string optional: Timestamp when the key was last modified.
    • rotated EmailsDkimKey guaranteed
      • algorithm string guaranteed: Algorithm used for the key pair.
      • createdAt string optional: Timestamp when the key pair was created.
      • dnsRecords object[] guaranteed: Suggested DNS records for the DKIM key.
        • name string guaranteed
        • type string guaranteed
        • value string guaranteed
      • domain string guaranteed: Domain associated with the key pair.
      • gracePeriodExpiresAt string optional: UTC timestamp after which you can no longer use the rotated key for signing.
      • length 1024 | 2048 | 3072 | 4096 guaranteed: Key length in bits.
      • publicKey string guaranteed
      • retiresAt string optional: UTC timestamp when a rotated key pair is retired.
      • selector string guaranteed: Selector assigned to the key pair.
      • status "active" | "revoked" | "retired" | "rotated" guaranteed: Status of the key.
      • statusModifiedAt string optional: Timestamp when the key was last modified.
  • error string | null nullable: An error message if the operation failed.

Type declarations

ts
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

ts
interface DataResponse<T> {
  data: T | null;
  error: string | null;
}
ts
interface SuccessResponse {
  success: boolean;
  error: string | null;
}

Send type declarations

ts
type EmailsSendOptions = EmailsSendOptionsBase & (
  | {
    html: string;
    text?: string;
  }
  | {
    html?: string;
    text: string;
  }
);
ts
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;
}
ts
interface EmailsSendAttachment {
  content: string;
  filename: string;
  type: string;
}
ts
interface EmailsSendRecipient {
  email: string;
  name?: string;
}
ts
interface EmailsSendTracking {
  click?: boolean;
  open?: boolean;
}
ts
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

ts
interface EmailsCheckDomainOptions {
  dkim?: EmailsCheckDomainDkim[] | EmailsCheckDomainDkim;
  domain: string;
  senderId?: string;
}
ts
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[];
}>;
ts
type EmailsCheckDomainVerdict = "passed" | "failed" | "soft failed" | "temporary error" | "permanent error" | "neutral" | "none" | "unknown";
ts
interface EmailsCheckDomainDkim {
  domain?: string;
  privateKey?: string;
  selector?: string;
}

Create DKIM Key type declarations

ts
interface EmailsCreateDkimKeyOptions {
  algorithm?: "rsa";
  length?: 1024 | 2048 | 3072 | 4096;
  selector: string;
}
ts
type EmailsDkimKeyStatus = "active" | "retired" | "revoked" | "rotated";
ts
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;
}
ts
type EmailsCreateDkimKeyResponse = DataResponse<EmailsDkimKey>;

Get DKIM Keys type declarations

ts
interface EmailsGetDkimKeysOptions {
  selector?: string;
  status?: EmailsDkimKey["status"];
  offset?: number;
  limit?: number;
  includeDnsRecord?: boolean;
}
ts
type Optional<T, K extends keyof T> = Omit<T, K> & Partial<Pick<T, K>>;
ts
type EmailsGetDkimKeysResponse = DataResponse<Optional<EmailsDkimKey, "dnsRecords">[]>;

Update DKIM Key type declarations

ts
interface EmailsUpdateDkimKeyOptions {
  selector: string;
  status: Exclude<EmailsDkimKey["status"], "active">;
}

Rotate DKIM Key type declarations

ts
interface EmailsRotateDkimKeyOptions {
  newKey: {
    selector: string;
  };
}
ts
type EmailsRotateDkimKeyResponse = DataResponse<{
  new: EmailsDkimKey;
  rotated: EmailsDkimKey;
}>;

Source

SourcePlaygroundDocs

Released under the MIT License.