Send method 📧 Emails
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 { 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',
})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.
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.
| Function | Description |
|---|---|
Attachment.fromBytes | Creates an attachment from a byte array or buffer |
Attachment.fromBlob | Creates an attachment from a Blob |
For example, to send an email with attachments from remote URLs:
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" })
]
})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
optionsEmailsSendOptionsrequired: Send optionsEmailsSendOptions.attachments(EmailsSendAttachment | Promise<EmailsSendAttachment>)[]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.typestringoptional: The MIME type of the attachment.contentIdstringoptional: TheContent-IDheader value for inline attachments, referenced from HTML withcid:.disposition"attachment" | "inline"optional: TheContent-Dispositionheader value for the attachment. Defaults toattachment.
IMPORTANT
Usage notes:
- Multiple attachments can be included in a single email.
- Maximum of
1000attachments per email. - Combined size limit (attachments + email content) is
30MB. - Base64 encoding is required for all attachment content.
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.
envelopeFromEmailsSendRecipient | stringoptional: Optional envelope sender address. If not set, the envelope sender defaults to thefrom.emailfield. Can be overridden per-personalization. Only the email portion is used; the name field is ignored.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.clickobjectoptional: Click tracking settings.customDomainNamestringoptional: 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.enablebooleanoptional: Enable click tracking.
openobjectoptional: Open tracking settings.customDomainNamestringoptional: 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.enablebooleanoptional: 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
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.textstringoptional: 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-textpackage to convert your HTML content to plain text.contentEmailsSendContent[]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.typestringrequired: The MIME type of the content you are including in your email.valuestringrequired: The actual content of the specified MIME type that you are including in the message.WARNING
Cannot contain a
text/htmlentry whenhtmlis set, or atext/plainentry whentextis set.
NOTE
For more information about sending emails with multiple content parts, see the MailChannels documentation.
IMPORTANT
Either
html,text, orcontentmust be provided.templateEmailsSendTemplateoptional: Template configuration for rendering email content with a template engine.typeEmailsSendTemplateTyperequired: The template type of the contentdataRecord<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
personalizationsEmailsSendPersonalization[]optional: Explicit personalization objects for advanced payloads with multiple recipient groups or per-personalization overrides.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 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.unsubscribeobjectoptional: Settings to customize the unsubscribe experience for the message.customDomainNamestringoptional: 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.
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
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.
errorErrorResponse | nullnullable: Error information if the operation failed.messagestringguaranteed: A human-readable description of the error.statusCodenumber | nullnullable: The HTTP status code from the API, ornullif the error is not related to an HTTP request. This field is intended for diagnostic use only and should not be relied upon.typestringguaranteed: A string identifier for the type of error. This field is intended for diagnostic use only and should not be relied upon.responseRecord<string, unknown> | nullnullable: An object containing the response, if available. This field may benullif 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
async function send (options: EmailsSendOptions, dryRun?: boolean): Promise<EmailsSendResponse>Response type declarations
interface ErrorResponse {
message: string;
statusCode: number | null;
type: ErrorType;
response: Record<string, unknown> | null;
}type DataResponse<T> = {
data: T;
error: null;
} | {
data: null;
error: ErrorResponse;
};interface SuccessResponse {
success: boolean;
error: ErrorResponse | null;
}Send type declarations
interface EmailsSendRecipient {
email: string;
name?: string;
}type EmailsSendRecipientInput = EmailsSendRecipient[] | EmailsSendRecipient | string[] | string;interface EmailsSendDkim {
domain?: string;
privateKey?: string;
selector?: string;
}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">>;
}interface EmailsSendAttachment {
content: string;
filename: string;
type?: string;
contentId?: string;
disposition?: "attachment" | "inline";
}interface EmailsSendTracking {
click?: {
customDomainName?: string;
enable?: boolean;
};
open?: {
customDomainName?: string;
enable?: boolean;
};
}type EmailsSendTemplateType = "mustache";type EmailsSendTemplateValue = string | boolean | number | EmailsSendTemplateValue[] | { [key: string]: EmailsSendTemplateValue };interface EmailsSendTemplate {
type: EmailsSendTemplateType;
data?: Record<string, EmailsSendTemplateValue>;
}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;
};
}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;
};interface EmailsSendContent {
type: string;
value: string;
}type EmailsSendOptions = EmailsSendOptionsBase & EmailsSendTargetOptions & (
| {
html: string;
text?: string;
content?: EmailsSendContent[];
}
| {
html?: string;
text: string;
content?: EmailsSendContent[];
}
| {
html?: string;
text?: string;
content: EmailsSendContent[];
}
);type EmailsSendResponse = DataResponse<{
rendered?: string[];
requestId?: string;
results?: {
index?: number;
messageId: string;
reason?: string;
status: "sent" | "failed";
}[];
}>;Source
Source • Playground • Docs • Tests