Skip to content

Send method 📧 Emails

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 { data, error } = 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 { data, error } = 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',
})

Send Attachments

To include attachments in your email, add an attachments array property to your send request.

send-attachments.ts
ts
import { MailChannels } from 'mailchannels-sdk'

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

const { data, error } = await mailchannels.emails.send({
  from: 'Name <from@example.com>',
  to: 'to@example.com',
  subject: 'Test email',
  html: '<p>Hello World</p>',
  attachments: [
    {
      type: "image/png",
      filename: "logo.png",
      content: "iVBORw0KGgoAAAANSUhEUgAAAKIAAA... (truncated for brevity)"
    }
  ]
})

Alternatively, the SDK provides Attachment helper methods to create attachments from various sources, such as byte arrays, buffers and blobs. This can be especially useful when dealing with file uploads or fetching files from remote URLs or storage services.

FunctionDescription
Attachment.fromBytesCreates an attachment from a byte array or buffer
Attachment.fromBlobCreates an attachment from a Blob

For example, to send an email with attachments from remote URLs:

ts
import { Attachment, MailChannels } from 'mailchannels-sdk'

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

const fileData = await fetch("https://picsum.photos/id/1/50/50").then(res => res.arrayBuffer());

const { data, error } = await mailchannels.emails.send({
  from: 'Name <from@example.com>',
  to: 'to@example.com',
  subject: 'Test email',
  html: '<p>Hello World</p>',
  attachments: [
    Attachment.fromBytes(fileData, { filename: "test-image-1.jpg" })
  ]
})
ts
import { Attachment, MailChannels } from 'mailchannels-sdk'

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

const fileBlob = await fetch("https://picsum.photos/id/1/50/50").then(res => res.blob());

const { data, error } = await mailchannels.emails.send({
  from: 'Name <from@example.com>',
  to: 'to@example.com',
  subject: 'Test email',
  html: '<p>Hello World</p>',
  attachments: [
    Attachment.fromBlob(fileBlob, { filename: "test-image-1.jpg" })
  ]
})

Params

  • options EmailsSendOptions required: Send options EmailsSendOptions.
    • attachments (EmailsSendAttachment | Promise<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 optional: The MIME type of the attachment.
      • contentId string optional: The Content-ID header value for inline attachments, referenced from HTML with cid:.
      • disposition "attachment" | "inline" optional: The Content-Disposition header value for the attachment. Defaults to attachment.

      IMPORTANT

      Usage notes:

      • Multiple attachments can be included in a single email.
      • Maximum of 1000 attachments per email.
      • Combined size limit (attachments + email content) is 30MB.
      • Base64 encoding is required for all attachment content.
    • 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.
    • envelopeFrom EmailsSendRecipient | string optional: Optional envelope sender address. If not set, the envelope sender defaults to the from.email field. Can be overridden per-personalization. Only the email portion is used; the name field is ignored.
    • 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.
      • click object optional: Click tracking settings.
        • customDomainName string optional: The name of a configured active click tracking domain. When specified, click tracking links will use this domain instead of the default MailChannels domain. The domain must be registered in your account and have an active status.
        • enable boolean optional: Enable click tracking.
      • open object optional: Open tracking settings.
        • customDomainName string optional: The name of a configured active open tracking domain. When specified, the open tracking pixel will use this domain instead of the default MailChannels domain. The domain must be registered in your account and have an active status.
        • enable boolean optional: Enable open tracking.

      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.
    • text string optional: The plain text content of the email.

      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.

    • content EmailsSendContent[] optional: Send the body of your message in multiple different formats. The recipient's email client will render the message using the content type that best fits their environment.
      • type string required: The MIME type of the content you are including in your email.
      • value string required: The actual content of the specified MIME type that you are including in the message.

        WARNING

        Cannot contain a text/html entry when html is set, or a text/plain entry when text is set.

      NOTE

      For more information about sending emails with multiple content parts, see the MailChannels documentation.

      IMPORTANT

      Either html, text, or content must be provided.

    • template EmailsSendTemplate optional: Template configuration for rendering email content with a template engine.
      • type EmailsSendTemplateType required: The template type of the content
      • data Record<string, EmailsSendTemplateValue> optional: Template variables, overridable per-personalization. An object containing key-value pairs of variables to set for template rendering.

      IMPORTANT

      Keys must be strings, and values can be one of the following types:

      • string
      • number
      • boolean
      • list, whose values are all of permitted types
      • map, whose keys must be strings, and whose values are all of permitted types
    • personalizations EmailsSendPersonalization[] optional: Explicit personalization objects for advanced payloads with multiple recipient groups or per-personalization overrides.
    • 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 and List-Unsubscribe-Post headers will be added, unless you supply your own List-Unsubscribe header, in which case yours is used and neither is added.
    • unsubscribe object optional: Settings to customize the unsubscribe experience for the message.
      • customDomainName string optional: The name of a configured active unsubscribe tracking domain. When specified, unsubscribe links will use this domain instead of the default MailChannels domain. The domain must be registered in your account and have an active status.
  • 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

  • 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 ErrorResponse | null nullable: Error information if the operation failed.
    • message string guaranteed: A human-readable description of the error.
    • statusCode number | null nullable: The HTTP status code from the API, or null if the error is not related to an HTTP request. This field is intended for diagnostic use only and should not be relied upon.
    • type string guaranteed: A string identifier for the type of error. This field is intended for diagnostic use only and should not be relied upon.
    • response Record<string, unknown> | null nullable: An object containing the response, if available. This field may be null if no response is available or if the error is not related to an HTTP request or if the response is not a JSON object.

Type declarations

Signature

ts
async function send (options: EmailsSendOptions, dryRun?: boolean): Promise<EmailsSendResponse>

Response type declarations

ts
interface ErrorResponse {
  message: string;
  statusCode: number | null;
  type: ErrorType;
  response: Record<string, unknown> | null;
}
ts
type DataResponse<T> = {
  data: T;
  error: null;
} | {
  data: null;
  error: ErrorResponse;
};
ts
interface SuccessResponse {
  success: boolean;
  error: ErrorResponse | null;
}

Send type declarations

ts
interface EmailsSendRecipient {
  email: string;
  name?: string;
}
ts
type EmailsSendRecipientInput = EmailsSendRecipient[] | EmailsSendRecipient | string[] | string;
ts
interface EmailsSendDkim {
  domain?: string;
  privateKey?: string;
  selector?: string;
}
ts
interface EmailsSendPersonalization {
  bcc?: EmailsSendRecipientInput;
  cc?: EmailsSendRecipientInput;
  dkim?: EmailsSendDkim;
  envelopeFrom?: EmailsSendRecipient | string;
  from?: EmailsSendRecipient | string;
  headers?: Record<string, string>;
  replyTo?: EmailsSendRecipient | string;
  subject?: string;
  to: EmailsSendRecipientInput;
  template?: Required<Omit<EmailsSendTemplate, "type">>;
}
ts
interface EmailsSendAttachment {
  content: string;
  filename: string;
  type?: string;
  contentId?: string;
  disposition?: "attachment" | "inline";
}
ts
interface EmailsSendTracking {
  click?: {
    customDomainName?: string;
    enable?: boolean;
  };
  open?: {
    customDomainName?: string;
    enable?: boolean;
  };
}
ts
type EmailsSendTemplateType = "mustache";
ts
type EmailsSendTemplateValue = string | boolean | number | EmailsSendTemplateValue[] | { [key: string]: EmailsSendTemplateValue };
ts
interface EmailsSendTemplate {
  type: EmailsSendTemplateType;
  data?: Record<string, EmailsSendTemplateValue>;
}
ts
interface EmailsSendOptionsBase {
  attachments?: (EmailsSendAttachment | Promise<EmailsSendAttachment>)[];
  campaignId?: string;
  bcc?: EmailsSendRecipientInput;
  cc?: EmailsSendRecipientInput;
  dkim?: EmailsSendDkim;
  envelopeFrom?: EmailsSendRecipient | string;
  from: EmailsSendRecipient | string;
  headers?: Record<string, string>;
  personalizations?: EmailsSendPersonalization[];
  to?: EmailsSendRecipientInput;
  tracking?: EmailsSendTracking;
  replyTo?: EmailsSendRecipient | string;
  subject: string;
  template?: EmailsSendTemplate;
  transactional?: boolean;
  unsubscribe?: {
    customDomainName?: string;
  };
}
ts
type EmailsSendTargetOptions =
  | {
    personalizations: (Omit<EmailsSendPersonalization, "template"> & { template?: never })[];
    to?: never;
    cc?: never;
    bcc?: never;
  }
  | {
    template: EmailsSendTemplate;
    personalizations: EmailsSendPersonalization[];
    to?: never;
    cc?: never;
    bcc?: never;
  }
  | {
    personalizations?: never;
    to: EmailsSendRecipientInput;
    cc?: EmailsSendRecipientInput;
    bcc?: EmailsSendRecipientInput;
  };
ts
interface EmailsSendContent {
  type: string;
  value: string;
}
ts
type EmailsSendOptions = EmailsSendOptionsBase & EmailsSendTargetOptions & (
  | {
    html: string;
    text?: string;
    content?: EmailsSendContent[];
  }
  | {
    html?: string;
    text: string;
    content?: EmailsSendContent[];
  }
  | {
    html?: string;
    text?: string;
    content: EmailsSendContent[];
  }
);
ts
type EmailsSendResponse = DataResponse<{
  rendered?: string[];
  requestId?: string;
  results?: {
    index?: number;
    messageId: string;
    reason?: string;
    status: "sent" | "failed";
  }[];
}>;

Source

SourcePlaygroundDocsTests

Released under the MIT License.