All Projects → mailslurp → mailslurp-client

mailslurp / mailslurp-client

Licence: MIT license
Official MailSlurp Client

Programming Languages

typescript
32286 projects

Projects that are alternatives of or similar to mailslurp-client

Vonage Ruby Sdk
Vonage REST API client for Ruby. API support for SMS, Voice, Text-to-Speech, Numbers, Verify (2FA) and more.
Stars: ✭ 203 (+515.15%)
Mutual labels:  sms
sms
Student Management System With Php
Stars: ✭ 26 (-21.21%)
Mutual labels:  sms
laravel-otp-login
Adds a customizable, translatable, configurable OTP verification step to Laravel Auth. You can add your own SMS provider too.
Stars: ✭ 16 (-51.52%)
Mutual labels:  sms
Nekosms
A pattern-based text message blocker for Android.
Stars: ✭ 206 (+524.24%)
Mutual labels:  sms
Nexmo Laravel
Add Nexmo functionality such as SMS and voice calling to your Laravel app with this Laravel Service Provider.
Stars: ✭ 250 (+657.58%)
Mutual labels:  sms
plivo
This package enables to send message or OTP to any mobile.This package uses external plivo api.
Stars: ✭ 20 (-39.39%)
Mutual labels:  sms
Pulse Sms Desktop
The official MacOS, Windows, and Linux clients for Pulse SMS - built on Electron.
Stars: ✭ 195 (+490.91%)
Mutual labels:  sms
MockSMS
Android application to create/craft fake sms.
Stars: ✭ 63 (+90.91%)
Mutual labels:  sms
advancedSmsManager
Advanced SmsManager is avery handy library for sending sms for single and two sim-card phones with many options.
Stars: ✭ 27 (-18.18%)
Mutual labels:  sms
hasura-auth
Authentication for Hasura.
Stars: ✭ 276 (+736.36%)
Mutual labels:  sms
Django Sendsms
A simple API to send SMS messages. It is modeled after the django email api.
Stars: ✭ 208 (+530.3%)
Mutual labels:  sms
Moriarty Project
This tool gives information about the phone number that you entered.
Stars: ✭ 223 (+575.76%)
Mutual labels:  sms
apostello
sms for your church
Stars: ✭ 62 (+87.88%)
Mutual labels:  sms
Ssm Env
Expand env variables from AWS Parameter Store
Stars: ✭ 205 (+521.21%)
Mutual labels:  sms
PySMS
Simple Python API that that allows you to send texts via SMTP with a best effort approach and process replies via IMAP
Stars: ✭ 19 (-42.42%)
Mutual labels:  sms
Wepush
专注批量推送的小而美的工具,目前支持:模板消息-公众号、模板消息-小程序、微信客服消息、微信企业号/企业微信消息、阿里云短信、阿里大于模板短信 、腾讯云短信、云片网短信、E-Mail、HTTP请求、钉钉、华为云短信、百度云短信、又拍云短信、七牛云短信
Stars: ✭ 2,597 (+7769.7%)
Mutual labels:  sms
SmsForwarder
短信转发器——监控Android手机短信、来电、APP通知,并根据指定规则转发到其他手机:钉钉群自定义机器人、钉钉企业内机器人、企业微信群机器人、飞书机器人、企业微信应用消息、邮箱、bark、webhook、Telegram机器人、Server酱、PushPlus、手机短信等。包括主动控制服务端与客户端,让你轻松远程发短信、查短信、查通话、查话簿、查电量等。(V3.0 新增)PS.这个APK主要是学习与自用,如有BUG请提ISSUE,同时欢迎大家提PR指正
Stars: ✭ 8,386 (+25312.12%)
Mutual labels:  sms
Kalkun
Open Source Web based SMS Manager
Stars: ✭ 186 (+463.64%)
Mutual labels:  sms
Andspoilt
Run interactive android exploits in linux.
Stars: ✭ 101 (+206.06%)
Mutual labels:  sms
BulkSMSSender
Bulk SMS Sender is a small and powerful open source android application that enables users to send generic and customized SMS messages through their carrier network to contacts that are listed in a Text input file.
Stars: ✭ 55 (+66.67%)
Mutual labels:  sms

MailSlurp Javascript Client

Create real email addresses on demand. Send and receive emails and attachments from code and tests using Javascript or Typescript. Use real phone numbers to process inbound TXT messages.

MailSlurp is an email and SMS API service that lets you create real email addresses in code. You can then send and receive emails and attachments in Javascript applications and tests. You can also create phone numbers and fetch inbound SMS.

MailSlurp is free for personal use but requires an API KEY. Please see the getting started guide for an introduction on key MailSlurp concepts or continue reading.


email testing

Quick start

Install with npm npm install --save mailslurp-client or yarn add mailslurp-client

// import mailslurp-client
const MailSlurp = require('mailslurp-client').default;
// OR import { MailSlurp } from "mailslurp-client"

// create a client
const apiKey = process.env.API_KEY ?? 'your-api-key';
const mailslurp = new MailSlurp({ apiKey });

// create an inbox
const inbox = await mailslurp.inboxController.createInbox({});
expect(inbox.emailAddress).toContain('@mailslurp');

More usage examples are included below.

Links

Here are some links to get started (or see below for code examples).

Get started

This section describes how to get up and running with the Javascript client.

See the guides page for more examples and use with common frameworks. For use with CypressJS see the official Cypress MailSlurp plugin.

See the method documentation for a list of all functions.

See the test/integration.spec.ts in this package for usage examples of this client.

Create API Key

First you'll need an API Key. Create a free account and copy the key from your dashboard.

Install NPM dependency

Install MailSlurp using NPM (NodeJS) or by including the source code in your project.

npm install --save mailslurp-client

Using in code

Here is how to use MailSlurp in your project.

Import MailSlurp library

const MailSlurp = require("mailslurp-client").default;
// or
import { MailSlurp } from "mailslurp-client";

Instantiate a MailSlurp client

Create a MailSlurp instance by instantiating a class with your API Key.

const mailslurp = new MailSlurp({ apiKey: "your_api_key" });

Timeouts

MailSlurp API endpoints are built to hold a connection open if the query is told to wait for certain conditions - like a new email arriving. For this reason it is important to use appropriate timeouts in tests or when settings up a fetch client.

MailSlurp recommends a 60_000 ms timeout to ensure emails arrive consistently. SMTP is a slow protocol so you may need to allow time for emails to arrive.

Fetch settings

MailSlurp is built on Javascript fetch. If you want to override the default fetch client you can do so when configuring MailSlurp.

const { MailSlurp } = require('mailslurp-client');
const crossFetch = require('cross-fetch');
const mailslurp = new MailSlurp({
  fetchApi: crossFetch,
  apiKey: apiKey,
});

Fetch handling exceptions

Any method that returns non-2xx response throws an exception by default (unless you use methods with the Raw suffix). There are valid 404 responses that you should handle, these include the 408 returned from waitFor methods when the required matching emails could not be found.

  • 4xx (400, 404...) response codes indicate a client error. Access the error message on the response body
  • 5xx (500, 501...) response codes indicate a server error. If encountered please contact support.
try {
  await mailslurp.waitController.waitForLatestEmail({
    inboxId: inboxId,
    timeout: timeout,
    unreadOnly: true,
  });
} catch (e) {
  // handle the error and status code in your code
  const statusCode = e.status;
  const errorMessage = await e.text();

  expect(errorMessage).toContain('Failed to satisfy email query for inbox');
  expect(statusCode).toEqual(408);
}

Fetch without exceptions (using ApiResponse)

If you prefer not to use try/catch you can use methods with the Raw suffix. These methods return an ApiResponse<T> that includes a status and result instead of throwing exceptions.

// use methods with `Raw` suffix to access a wrapped response
// that contains the status instead of throwing an exception
const inboxRaw: ApiResponse<InboxDto> =
  await mailslurp.inboxController.createInboxRaw({});
expect(inboxRaw.raw.ok).toBeTruthy();
const inbox = await inboxRaw.value();
expect(inbox.id).toBeTruthy();

API Controllers

Note the MailSlurp object is a class with many common methods. It does not contain all MailSlurp API methods. The full API is available as individually exported controllers.

See the MailSlurp class documentation for all methods or see the test/integration.spec.ts file for usage examples. You can also instantiate controllers directly. See the API controllers for method details.

// controllers are available on a MailSlurp instance
const { MailSlurp } = require('mailslurp-client');
const mailslurp = new MailSlurp({ apiKey });
await mailslurp.inboxController.createInbox({});
// or by import controllers and instantiating with a configuration
const { InboxControllerApi } = require('mailslurp-client');
const inboxController = new InboxControllerApi(new Configuration({ apiKey }));
await inboxController.createInbox({});

Email usage examples

Here are some snippets of common usage.

Create an email address

MailSlurp inboxes have real email addresses. There are several ways to create them. See the docs for full inbox object reference. Inboxes can be either SMTP or HTTP type mailboxes. HTTP inboxes are powered by AWS SES and are great for most use cases. SMTP inboxes use a custom mail server running at mx.mailslurp.com to support older email clients. SMTP inboxes are more suitable for public facing usage.

Simple usage

You can create an inbox with a randomly assigned email address ending in @mailslurp.com like so:

const inbox = await mailslurp.createInbox();
// { id: '123', emailAddress: '[email protected]' }

Create inbox options

Use the createInboxWithOptions or methods on the inboxController property to create email addresses using more options.

await mailslurp.inboxController.createInbox({});

To use custom domains see the domain verification guide

Get an inbox

Inboxes have real email addresses. See the inbox reference for all properties.

const mailslurp = new MailSlurp(config);
const { id: inboxId } = await mailslurp.createInbox();
const inbox = await mailslurp.getInbox(inboxId);
expect(inbox.id).toEqual(inboxId);

Access mailbox and emails using SMTP client

You can access SMTP_INBOX type inboxes using an SMTP client like nodemailer. First create an inbox then call the getImapSmtpAccessDetails function to obtain SMTP username and password:

const {MailSlurp} = require('mailslurp-client');
const nodemailer = require("nodemailer");
const apiKey = process.env.API_KEY;
const mailslurp = new MailSlurp({ apiKey });

// get access details for smpt server
const server = await mailslurp.getImapSmtpAccessDetails();

// use details to configure SMTP client like NodeMailer
const opts = {
    host: server.smtpServerHost,
    port: server.smtpServerPort,
    secure: false, // Disable tls recommended
    auth: {
        user: server.smtpUsername,
        pass: server.smtpPassword,
        type: "PLAIN" // Note the use of PLAIN AUTH
    },
}
const transport = nodemailer.createTransport(opts)

List inboxes

Inbox lists are paginated and sortable. List methods return a projection of an inbox. See the inbox projection reference for properties.

const mailslurp = new MailSlurp(config);

// get paginated inboxes
const [index, size] = [0, 20];
const pageInboxes = await mailslurp.getAllInboxes(0, 20);

expect(pageInboxes.size).toEqual(size);
expect(pageInboxes.number).toEqual(index);

Fetch emails from inbox

To read emails that already exist in an inbox use the EmailController getEmail method. To wait for expected emails that may not have arrived yet use the WaitForController.

There are many ways to receive and fetch emails in MailSlurp. Emails have many properties including body, subject, attachments and more. See the API docs for full email reference.

const inbox = await mailslurp.createInbox();
await mailslurp.sendEmail(inbox.id, {
  to: [inbox.emailAddress],
  subject: 'test',
});

// wait for first email
const latestEmail = await mailslurp.waitForLatestEmail(inbox.id, timeoutMs);
expect(latestEmail.subject).toContain('test');

// send another
await mailslurp.sendEmail(inbox.id, {
  to: [inbox.emailAddress],
  subject: 'second',
});

// wait for second using controller instead
const secondEmail = await mailslurp.waitController.waitForLatestEmail({
  inboxId: inbox.id,
  unreadOnly: true,
});
expect(secondEmail.subject).toContain('second');

const allEmails = await mailslurp.getEmails(inbox.id);
expect(allEmails).toHaveLength(2);

For more fetching methods see the WaitForController and the EmailController

Send emails

To send emails use the SendEmailOptions arguments with the InboxController or MailSlurp instance methods.

const inbox = await mailslurp.createInbox();
const options = {
  to: [emailAddress],
  subject: 'Hello',
  body: 'Welcome',
};
const sent = await mailslurp.sendEmail(inbox.id, options);
expect(sent.subject).toContain('Hello');

Sending with queues

If your plan permits you can send emails using a queue. This allows you to safely recover emails that failed to send and retry them. Use queue to ensure that emails are always delivered regardless of your account status, bounce limit, or payment failures.

await mailslurp.inboxController.sendEmailWithQueue({
  inboxId: inboxId,
  sendEmailOptions: {
    to: [recipient],
    subject: 'Sent with a queue',
    body:
      'Use queues to allow recovery of failed email ' +
      'sending when account reaches limits or has payment issues',
  },
  // validate before adding to queue to fail early
  validateBeforeEnqueue: false,
});

Verify email addresses

Validate an email address to find out if it exists and can receive email. This can help reduce your bounce rate and improve your sending reputation.

const mailslurp = new MailSlurp(config);
const res =
  await mailslurp.emailVerificationController.validateEmailAddressList({
    validateEmailAddressListOptions: {
      emailAddressList: ['[email protected]', '[email protected]'],
    },
  });
expect(res.resultMapEmailAddressIsValid['[email protected]']).toEqual(
  true
);
expect(res.resultMapEmailAddressIsValid['[email protected]']).toEqual(
  false
);

Upload attachment

Upload attachment using the AttachmentController.

Attachments can be uploaded as base64 strings. The ids returned can be used with SendEmailOptions send functions. See the upload attachment options for more information.

const mailslurp = new MailSlurp(config);

// read a file as a base64 encoded string
const pathToAttachment = path.join(__dirname + '/attachment.txt');
const fileBase64Encoded = await fs.promises.readFile(pathToAttachment, {
  encoding: 'base64',
});

// upload the attachment as base64 string and get atttachment id
const [attachmentId] =
  await mailslurp.attachmentController.uploadAttachment({
    uploadAttachmentOptions: {
      base64Contents: fileBase64Encoded,
      contentType: 'text/plain',
      filename: path.basename(pathToAttachment),
    },
  });

Send attachment

To send an attachment first upload the file using the AttachmentController then send an email containing the attachment ID with the InboxController.

You can send attachments by including their IDs in the attachments options when sending.

const inbox1 = await mailslurp.createInbox();
const inbox2 = await mailslurp.createInbox();

// send email and get saved result
const sentEmail = await mailslurp.inboxController.sendEmailAndConfirm({
  inboxId: inbox1.id,
  sendEmailOptions: {
    to: [inbox2.emailAddress],
    attachments: [attachmentId],
    subject: 'Send attachments',
    body: 'Here are your files',
  },
});

expect(sentEmail.attachments.length).toEqual(1);

Receive attachments

To wait for expected emails to arrive and read their contents use the WaitFor controller endpoints.

// first wait for an email
const email = await mailslurp.waitController.waitForLatestEmail({
  inboxId: inboxId,
  timeout: 30000,
  unreadOnly: true,
});

// check has attachments
expect(email.attachments.length).toEqual(1);

// download with email controller as base64 string
const attachmentDto =
  await mailslurp.emailController.downloadAttachmentBase64({
    attachmentId: email.attachments[0]!!,
    emailId: email.id,
  });

// can access content
expect(attachmentDto.base64FileContents).toBeTruthy();
const fileContent = new Buffer(
  attachmentDto.base64FileContents,
  'base64'
).toString();
expect(fileContent).toContain('test');

// can access size etc
expect(attachmentDto.sizeBytes).toBeTruthy();
expect(attachmentDto.contentType).toBeTruthy();

Wait for multiple emails

The WaitForController contains many methods for waiting for emails to arrive in an inbox. See the waitFor controller reference for more information.

it('can wait for multiple emails', async () => {
  const mailslurp = new MailSlurp(config);

  // example of creating inboxes simultaneously
  const inbox1 = await mailslurp.createInbox();
  const inbox2 = await mailslurp.createInbox();

  // send two emails
  await mailslurp.sendEmail(inbox1.id, {
    to: [inbox2.emailAddress],
    subject: 'Hello Dogs',
  });
  await mailslurp.sendEmail(inbox1.id, {
    to: [inbox2.emailAddress],
    subject: 'Hello Cats',
  });

  // wait for 2 emails
  const emails = await mailslurp.waitController.waitForEmailCount({
    count: 2,
    inboxId: inbox2.id,
    sort: WaitForEmailCountSortEnum.DESC,
  });

  const subjects = emails.map((e) => e.subject);
  expect(subjects).toContain('Hello Dogs');
  expect(subjects).toContain('Hello Cats');
});

Wait for matching emails

MailSlurp allows one to wait for emails that match certain parameters. Here is an example:

const inbox1 = await mailslurp.createInbox();
const inbox2 = await mailslurp.createInbox();

// specify recipient (must be array)
const to = [inbox2.emailAddress];

// send two emails
await mailslurp.sendEmail(inbox1.id, { to, subject: 'Apples' });
await mailslurp.sendEmail(inbox1.id, { to, subject: 'Oranges' });

// wait for matching email based on subject (see MatchOptions for all options)
const matchOptions: MatchOptions = {
  matches: [
    {
      field: MatchOptionFieldEnum.SUBJECT,
      should: MatchOptionShouldEnum.CONTAIN,
      value: 'Apples',
    },
  ],
};
const expectCount = 1;
const matchingEmails = await mailslurp.waitController.waitForMatchingEmails(
  {
    inboxId: inbox2.id,
    matchOptions: matchOptions,
    count: expectCount,
    timeout: timeoutMillis,
    unreadOnly: true,
  }
);
expect(matchingEmails.length).toEqual(1);
expect(matchingEmails[0].subject).toEqual('Apples');

See the MatchOptions documentation for reference.

Extract email content

You can extract useful information from emails using regular expressions. See the EmailController for more information:

const inbox1 = await mailslurp.createInbox();
const inbox2 = await mailslurp.createInbox();

const to = [inbox2.emailAddress];
const body = 'Hi there. Your code is: 123456';
await mailslurp.sendEmail(inbox1.id, { to, body });

// wait for email
const email = await mailslurp.waitController.waitForLatestEmail({
  inboxId: inbox2.id,
  timeout: timeoutMillis,
  unreadOnly: true,
});
const pattern = 'code is: ([0-9]{6})';
expect(email.body).toContain('Your code is');

// pass the pattern to mailslurp to match for emails
const result = await mailslurp.emailController.getEmailContentMatch({
  contentMatchOptions: { pattern },
  emailId: email.id,
});

// access the match groups
expect(result.matches).toHaveLength(2);
expect(result.matches[0]).toEqual('code is: 123456');
expect(result.matches[1]).toEqual('123456');

Phone SMS/TXT usage

MailSlurp supports inbound SMS using real phone numbers. See the SMS guide or the developer documentation to get started.

Create phone numbers

Phone numbers must be created in the MailSlurp dashboard. Once you create a number you can use it in code.

List numbers

Fetch phone numbers with the phone controller.

const {
  content: [phone],
} = await mailslurp.phoneController.getPhoneNumbers({
  phoneCountry: GetPhoneNumbersPhoneCountryEnum.US,
});
expect(phone.phoneNumber).toContain('+1');

Receive SMS

Use the wait for controller to wait for inbound SMS messages:

const sms = await mailslurp.waitController.waitForLatestSms({
  waitForSingleSmsOptions: {
    phoneNumberId: phone.id,
    timeout: 30_000,
    unreadOnly: true,
  },
});
expect(sms.body).toContain('Here is your code');
expect(sms.fromNumber).toEqual('+13252527014');

You can also use webhooks with the NEW_SMS event to receive text messages.

Webhooks

To have received emails sent to your server using HTTP webhook push create a webhook using the WebhookController or see the webhook email guide.

Create webhooks

You can create webhooks in code or using the MailSlurp dashboard.

await mailslurp.webhookController.createWebhook({
    inboxId,
    webhookOptions: {
        url: "https://my-server.com/webhook",
        eventName: CreateWebhookOptionsEventNameEnum.NEW_EMAIL
    }
})

Listen to webhooks

To consume webhooks first create a webhook for an inbox and a given webhook event. Set the webhook URL to an endpoint on your server. Your server must be publicly accessible and return a 200 or 201 status code in 30 seconds. To test locally use a service like ngrok.io to tunnel your local machine to a public URL. The payload posted to your end point will depend on the event type. Here is a listen example using express

Note: you can use any framework or language you like with webhooks.

// example express server that you control
const app = express();
app.use(bodyParser.json());
// receive new email webhook payload via post
app.post('/new-email-endpoint', async (request, response) => {
  // can use typescript types
  const payload = request.body as WebhookNewEmailPayload;

  // do something with with email id
  expect(payload.emailId).toBeTruthy();

  // return a 2xx status code so MailSlurp knows you received it
  return response.sendStatus(200);
});
const server = app.listen(port);

Testing webhook server

// get a test payload for NEW_EMAIL event
const testPayload =
  await mailslurp.webhookController.getTestWebhookPayloadNewEmail();
// post payload to your server to test it
const testResponse = await fetch(
  `http://localhost:${port}/new-email-endpoint`,
  {
    method: 'POST',
    headers: {
      'content-type': 'application/json',
    },
    body: JSON.stringify(testPayload),
  }
);
// expect 200
expect(testResponse.status).toEqual(200);

More Documentation

Resources

Feedback, support, and feature requests

The MailSlurp team welcomes any feedback and feature requests. Please use the support portal to report any bugs or speak with support.

Note that the project description data, including the texts, logos, images, and/or trademarks, for each open source project belongs to its rightful owner. If you wish to add or remove any projects, please contact us at [email protected].