Coder Social home page Coder Social logo

blueimp / mailhog-node Goto Github PK

View Code? Open in Web Editor NEW
35.0 2.0 9.0 255 KB

A NodeJS library to interact with the MailHog API. MailHog is a stand-in SMTP server for Web and API based SMTP testing.

License: MIT License

JavaScript 93.14% Shell 6.08% Dockerfile 0.77%

mailhog-node's Introduction

mailhog

A NodeJS library to interact with the MailHog API.

Contents

Installation

npm install mailhog

Initialization

require('mailhog')(options) → Object

Description

The mailhog module returns an initialization function.
This function accepts an optional options object that is used for http.request calls to the MailHog API and returns the mailhog API object.

Parameters

Name Type Required Default Description
options.protocol String no http: API protocol
options.host String no localhost API host
options.port Number no 8025 API port
options.auth String no API basic authentication
options.basePath String no /api API base path

Returns

Returns the mailhog API object with the following properties:

{
  options: Object,
  messages: Function,
  search: Function,
  latestFrom: Function,
  latestTo: Function,
  latestContaining: Function,
  releaseMessage: Function,
  deleteMessage: Function,
  deleteAll: Function,
  encode: Function,
  decode: Function
}

Example

const mailhog = require('mailhog')({
  host: 'mailhog'
})

mailhog.messages().then(result => console.log(result))

API

The following API descriptions assume that the mailhog API object has been initialized.

messages

mailhog.messages(start, limit) → Promise

Description

Retrieves a list of mail objects, sorted from latest to earliest.

Parameters

Name Type Required Default Description
start Number no 0 defines the messages query offset
limit Number no 50 defines the max number of results

Returns

Returns a Promise that resolves with an Object.

The resolved result has the following properties:

{
  total: Number, // Number of results available
  count: Number, // Number of results returned
  start: Number, // Offset for the range of results returned
  items: Array   // List of mail object items
}

The individual mail object items have the following properties:

{
  ID: String,         // Mail ID
  text: String,       // Decoded mail text content
  html: String,       // Decoded mail HTML content
  subject: String,    // Decoded mail Subject header
  from: String,       // Decoded mail From header
  to: String,         // Decoded mail To header
  cc: String,         // Decoded mail Cc header
  bcc: String,        // Decoded mail Bcc header
  replyTo: String,    // Decoded mail Reply-To header
  date: Date,         // Mail Date header
  deliveryDate: Date, // Mail Delivery-Date header
  attachments: Array  // List of mail attachments
}

The individual attachments have the following properties:

{
  name: String,     // Filename
  type: String,     // Content-Type
  encoding: String, // Content-Transfer-Encoding
  Body: String      // Encoded content
}

Example

async function example() {
  // Retrieve the latest 10 messages:
  const result = await mailhog.messages(0, 10)

  // Log the details of each message to the console:
  for (let item of result.items) {
    console.log('From: ', item.from)
    console.log('To: ', item.to)
    console.log('Subject: ', item.subject)
    console.log('Content: ', item.text)
  }
}

search

mailhog.search(query, kind, start, limit) → Promise

Description

Retrieves a list of mail objects for the given query, sorted from latest to earliest.

Parameters

Name Type Required Default Description
query String yes search query
kind String no containing query kind (from/to/containing)
start Number no 0 defines the search query offset
limit Number no 50 defines the max number of results

Returns

Returns a Promise that resolves with an Object.

The resolved result has the following properties:

{
  total: Number, // Number of results available
  count: Number, // Number of results returned
  start: Number, // Offset for the range of results returned
  items: Array   // List of mail object items
}

The individual mail object items have the following properties:

{
  ID: String,         // Mail ID
  text: String,       // Decoded mail text content
  html: String,       // Decoded mail HTML content
  subject: String,    // Decoded mail Subject header
  from: String,       // Decoded mail From header
  to: String,         // Decoded mail To header
  cc: String,         // Decoded mail Cc header
  bcc: String,        // Decoded mail Bcc header
  replyTo: String,    // Decoded mail Reply-To header
  date: Date,         // Mail Date header
  deliveryDate: Date, // Mail Delivery-Date header
  attachments: Array  // List of mail attachments
}

The individual attachments have the following properties:

{
  name: String,     // Filename
  type: String,     // Content-Type
  encoding: String, // Content-Transfer-Encoding
  Body: String      // Encoded content
}

Example

async function example() {
  // Search the latest 10 messages containing "banana":
  const result = await mailhog.search('banana', 'containing', 0, 10)

  // Log the details of each message to the console:
  for (let item of result.items) {
    console.log('From: ', item.from)
    console.log('To: ', item.to)
    console.log('Subject: ', item.subject)
    console.log('Content: ', item.text)
  }
}

latestFrom

mailhog.latestFrom(query) → Promise

Description

Retrieves the latest mail object sent from the given address.

Parameters

Name Type Required Description
query String yes from address

Returns

Returns a Promise that resolves with an Object.

The resolved mail object has the following properties:

{
  ID: String,         // Mail ID
  text: String,       // Decoded mail text content
  html: String,       // Decoded mail HTML content
  subject: String,    // Decoded mail Subject header
  from: String,       // Decoded mail From header
  to: String,         // Decoded mail To header
  cc: String,         // Decoded mail Cc header
  bcc: String,        // Decoded mail Bcc header
  replyTo: String,    // Decoded mail Reply-To header
  date: Date,         // Mail Date header
  deliveryDate: Date, // Mail Delivery-Date header
  attachments: Array  // List of mail attachments
}

The individual attachments have the following properties:

{
  name: String,     // Filename
  type: String,     // Content-Type
  encoding: String, // Content-Transfer-Encoding
  Body: String      // Encoded content
}

Example

async function example() {
  // Search the latest message from "[email protected]":
  const result = await mailhog.latestFrom('[email protected]')

  // Log the details of this message to the console:
  console.log('From: ', result.from)
  console.log('To: ', result.to)
  console.log('Subject: ', result.subject)
  console.log('Content: ', result.text)
}

latestTo

mailhog.latestTo(query) → Promise

Description

Retrieves the latest mail object sent to the given address.

Parameters

Name Type Required Description
query String yes to address

Returns

Returns a Promise that resolves with an Object.

The resolved mail object has the following properties:

{
  ID: String,         // Mail ID
  text: String,       // Decoded mail text content
  html: String,       // Decoded mail HTML content
  subject: String,    // Decoded mail Subject header
  from: String,       // Decoded mail From header
  to: String,         // Decoded mail To header
  cc: String,         // Decoded mail Cc header
  bcc: String,        // Decoded mail Bcc header
  replyTo: String,    // Decoded mail Reply-To header
  date: Date,         // Mail Date header
  deliveryDate: Date, // Mail Delivery-Date header
  attachments: Array  // List of mail attachments
}

The individual attachments have the following properties:

{
  name: String,     // Filename
  type: String,     // Content-Type
  encoding: String, // Content-Transfer-Encoding
  Body: String      // Encoded content
}

Example

async function example() {
  // Search the latest message to "[email protected]":
  const result = await mailhog.latestTo('[email protected]')

  // Log the details of this message to the console:
  console.log('From: ', result.from)
  console.log('To: ', result.to)
  console.log('Subject: ', result.subject)
  console.log('Content: ', result.text)
}

latestContaining

mailhog.latestContaining(query) → Promise

Description

Retrieves the latest mail object containing the given query.

Parameters

Name Type Required Description
query String yes search query

Returns

Returns a Promise that resolves with an Object.

The resolved mail object has the following properties:

{
  ID: String,         // Mail ID
  text: String,       // Decoded mail text content
  html: String,       // Decoded mail HTML content
  subject: String,    // Decoded mail Subject header
  from: String,       // Decoded mail From header
  to: String,         // Decoded mail To header
  cc: String,         // Decoded mail Cc header
  bcc: String,        // Decoded mail Bcc header
  replyTo: String,    // Decoded mail Reply-To header
  date: Date,         // Mail Date header
  deliveryDate: Date, // Mail Delivery-Date header
  attachments: Array  // List of mail attachments
}

The individual attachments have the following properties:

{
  name: String,     // Filename
  type: String,     // Content-Type
  encoding: String, // Content-Transfer-Encoding
  Body: String      // Encoded content
}

Example

async function example() {
  // Search the latest message containing "banana":
  const result = await mailhog.latestContaining('banana')

  // Log the details of this message to the console:
  console.log('From: ', result.from)
  console.log('To: ', result.to)
  console.log('Subject: ', result.subject)
  console.log('Content: ', result.text)
}

releaseMessage

mailhog.releaseMessage(id, config) → Promise

Description

Releases the mail with the given ID using the provided SMTP config.

Parameters

Name Type Required Description
id String yes message ID
config Object yes SMTP configuration
config.host String yes SMTP host
config.port String yes SMTP port
config.email String yes recipient email
config.username String no SMTP username
config.password String no SMTP password
config.mechanism String no SMTP auth type (PLAIN or CRAM-MD5)

Returns

Returns a Promise that resolves with an http.IncomingMessage object.

Example

async function example() {
  const result = await mailhog.latestTo('[email protected]')

  const response = await mailhog.releaseMessage(result.ID, {
    host: 'localhost',
    port: '1025',
    email: '[email protected]'
  })
}

deleteMessage

mailhog.deleteMessage(id) → Promise

Description

Deletes the mail with the given ID from MailHog.

Parameters

Name Type Required Description
id String yes message ID

Returns

Returns a Promise that resolves with an http.IncomingMessage object.

Example

async function example() {
  const result = await mailhog.latestTo('[email protected]')

  const response = await mailhog.deleteMessage(result.ID)

  console.log('Status code: ', response.statusCode)
}

deleteAll

mailhog.deleteAll() → Promise

Description

Deletes all mails stored in MailHog.

Parameters

None

Returns

Returns a Promise that resolves with an http.IncomingMessage object.

Example

async function example() {
  const response = await mailhog.deleteAll()

  console.log('Status code: ', response.statusCode)
}

encode

mailhog.encode(str, encoding, charset, lineLength) → String

Description

Encodes a String in the given charset to base64 or quoted-printable encoding.

Parameters

Name Type Required Default Description
str String yes String to encode
encoding String yes utf8 base64/quoted-printable
charset String no utf8 Charset of the input string
lineLength Number no 76 Soft line break limit

Returns

Returns a String in the target encoding.

Example

const query = mailhog.encode('üäö', 'quoted-printable')
// =C3=BC=C3=A4=C3=B6

async function example() {
  // Search for "üäö" in quoted-printable encoding:
  const result = await mailhog.search(query)
}

decode

mailhog.decode(str, encoding, charset) → String

Description

Decodes a String from the given encoding and outputs it in the given charset.

Parameters

Name Type Required Default Description
str String yes String to decode
encoding String yes base64/quoted-printable
charset String no utf8 Charset to use for the output

Returns

Returns a String in the target charset.

Example

const output = mailhog.decode('5pel5pys', 'base64')
// 日本

Testing

  1. Start Docker.
  2. Install development dependencies:
    npm install
  3. Run the tests:
    npm test

License

Released under the MIT license.

Author

Sebastian Tschan

mailhog-node's People

Contributors

aeris avatar blueimp avatar n0v1 avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar

mailhog-node's Issues

TypeError: Cannot read property '1' of null

While using the function getHTML or getText as described in the README.md I get the following error. I can only use the unformated ouput of the query.

TypeError: Cannot read property '1' of null
    at getContentPart (/home/norbert/tools/calponia/acceptance-tests/node_modules/mailhog/mailhog.js:72:50)
    at Object.getText (/home/norbert/tools/calponia/acceptance-tests/node_modules/mailhog/mailhog.js:100:14)
....

getText/getHTML should be able to parse multipart messages

It would be fantastic for testing emails if getHTML and getText would be able to parse multipart/mixed messages by actually checking the body and extracting the right part. Currently they can't find a matching header and thus abort.

Example:

Content-Type: multipart/mixed; boundary="===============7426108140616550474=="
Date: Tue, 17 May 2022 11:12:22 +0000
From: [email protected]
MIME-Version: 1.0
Message-ID: <165278594245.265.1843128869165443175@09814d7d4841>
Received: from [123.4.5.6] by mailhog.example (MailHog)
          id [email protected]; Tue, 17 May 2022 11:12:22 +0000
Return-Path: <[email protected]>
Subject: Some Test Subject
To: [email protected]

--===============7426108140616550474==
Content-Type: multipart/alternative;
 boundary="===============1607218409922029753=="
MIME-Version: 1.0

--===============1607218409922029753==
Content-Type: text/plain; charset="utf-8"
MIME-Version: 1.0
Content-Transfer-Encoding: 7bit


--===============1607218409922029753==
Content-Type: text/html; charset="utf-8"
MIME-Version: 1.0
Content-Transfer-Encoding: 8bit

Some Test MEssage
    
--===============1607218409922029753==--

--===============7426108140616550474==--

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.