Getting Started
Getting started with mailchannels-sdk
Overview
This library provides a simple way to interact with the MailChannels API. It is written in TypeScript and can be used in both JavaScript and TypeScript projects and in different runtimes.
IMPORTANT
Disclaimer: This library is not associated with MailChannels Corporation.
Requirements
Installation
Add mailchannels-sdk dependency to your project
npm i mailchannels-sdkyarn add mailchannels-sdkpnpm add mailchannels-sdkQuick Start
This library can be used in two ways:
- Importing the whole library
- Importing the client and only the modules you need
Importing the whole library
In this example, we import the whole library and use the MailChannels class to send an email.
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>'
})This approach is useful when building an application on top of MailChannels and you need to use all or multiple modules from the library.
Importing only the modules you need
In this example, we import the MailChannelsClient and the Emails module to send an email.
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: 'Name <from@example.com>',
to: 'to@example.com',
subject: 'Test email',
html: '<p>Hello World</p>'
})This approach is tree-shakable and is useful when you only need to use specific modules from the library and want to reduce the bundle size of your application.
Error handling
All methods in this SDK return an object with both data and error properties to avoid throwing exceptions, making error handling more predictable and easier to manage.
Success case:
data: Contains the response dataerror: Will benull
Error case:
data: Will benullerror: Contains anErrorResponseobject with the following properties:message: A human-readable description of the errorstatusCode: The HTTP status code from the API (e.g.,400,404), ornullif the error is not related to an HTTP request
import { MailChannels } from 'mailchannels-sdk'
const mailchannels = new MailChannels('your-api-key')
const { data, error } = await mailchannels.emails.send({
from: 'sender@example.com',
to: 'recipient@example.com',
subject: 'Test email',
html: '<p>Hello World</p>'
})
// handle the error as needed
if (error) {
throw new Error(error.message)
}
// data is guaranteed to be non-null here
console.log({ data })