Skip to content

RFC 2822 compliant email message generator written in node.js

License

Notifications You must be signed in to change notification settings

jetbridge/MIMEText

ย 
ย 

Folders and files

NameName
Last commit message
Last commit date

Latest commit

ย 

History

32 Commits
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 

Repository files navigation

MIMEText

RFC 2822 compliant raw email message generator written in node.js

NPM npm version npm bundle size npm Join the chat at https://gitter.im/MIMEText/community

Install

npm i mimetext

Use

const {createMimeMessage} = require('mimetext')
// or
import {createMimeMessage} from 'mimetext'

Create a simple plain text email:

const msg = createMimeMessage()
msg.setSender({name: 'Lorem Ipsum', addr: '[email protected]'})
msg.setRecipient('[email protected]')
msg.setSubject('๐Ÿš€ Issue 49!')
msg.setMessage('text/plain', `Hi,
I'm a simple text.`)

That's it. Now get the raw email message:

const raw = msg.asRaw()

Output:

Date: Sun, 24 Oct 2021 04:50:32 +0000
From: "Lorem Ipsum" <[email protected]>
To: <[email protected]>
Message-ID: <[email protected]>
Subject: =?utf-8?B?8J+agCBJc3N1ZSA0OSE=?=
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8

Hi,
I'm a simple text.

More Sophisticated Example

Here is more complex email message which contains html with plaintext version and has an attachment.

const msg = createMimeMessage()
msg.setSender('Lorem Ipsum <[email protected]>')
msg.setTo({name: 'Foo Bar', addr: '[email protected]'})
msg.setCc('Abc Def <[email protected]>')
msg.setBcc(['[email protected]', '[email protected]', {name: 'Name', addr: '[email protected]'}])
msg.setSubject('๐Ÿš€ Issue 49!')
// add html version
msg.setMessage('text/html', `Hi,
I'm <strong>a bold</strong> text.`)
// add alternative plain text version
msg.setMessage('text/plain', `Hi,
I'm a simple text.`)
// set custom header
msg.setHeader('X-Abc', 'asdildffdiลŸfsdi')
// add an attachment
msg.setAttachment('test.jpg', 'image/jpg', msg.toBase64( fs.readFileSync('./tests/test.jpg') ))

Here is the output of the .asRaw:

Date: Sun, 24 Oct 2021 05:00:03 +0000
From: "Lorem Ipsum" <[email protected]>
To: "Foo Bar" <[email protected]>
Cc: "Abc Def" <[email protected]>
Bcc: <[email protected]>, <[email protected]>, "Name" <[email protected]>
Message-ID: <[email protected]>
Subject: =?utf-8?B?8J+agCBJc3N1ZSA0OSE=?=
MIME-Version: 1.0
X-Abc: asdildffdiลŸfsdi
Content-Type: multipart/mixed; boundary=tdplbi0e8pj

--tdplbi0e8pj
Content-Type: multipart/alternative; boundary=oagdypniyp

--oagdypniyp
Content-Type: text/plain; charset=UTF-8

Hi,
I'm a simple text.

--oagdypniyp
Content-Type: text/html; charset=UTF-8

Hi,
I'm <strong>a bold</strong> text.

--oagdypniyp--
--tdplbi0e8pj
Content-Type: image/jpg; charset=UTF-8
Content-Transfer-Encoding: base64
Content-Disposition: attachment;filename="test.jpg"

/9j/4AAQSkZJRgABAgAAZABkAAD/7AARR....................Oc2YO5LuFLMxUeBjH5//2Q==

--tdplbi0e8pj--

API

.setSender(value)

Sender can be specified in multiple ways:

message.setSender('[email protected]')
message.setSender('"Sender Fullname" <[email protected]>')
message.setSender({name: 'Sender Name', addr: '[email protected]'})
message.setSender(['[email protected]', '[email protected]'])

Returns Mailbox instance.

.getSender()

Returns Mailbox instance.

.setTo(value), .setCc(value), .setBcc(value), .setRecipient(value, opts)

All of the .setTo, .setCc and .setBcc methods maps their input to .setRecipient. Returns array of Mailbox instances.

message.setTo('[email protected]')
message.setTo('"Person Fullname" <[email protected]>')
message.setTo({name: 'Person Name', addr: '[email protected]'})
message.setTo([
  '[email protected]',
  {name: 'Person Name', addr: '[email protected]'}
])

message.setRecipient('[email protected]', {type: 'to'}) // to is default

.getRecipients(opts={type: 'to'})

Returns array of Mailbox instances.

.setSubject(value)

Returns the value.

const value = 'Weekly Newsletter 49 Ready ๐Ÿš€'
message.setSubject(value)

.getSubject()

Returns the value.

.setHeader()

Inserts a header to the message.

message.setHeader('X-Custom-Header', 'value')

.getHeader(name)

Returns the value of the header.

.setMessage(type, data, moreHeaders={})

Adds a content to the email. Valid values for type are text/plain and text/html. data is the content. Headers for this content can be specified with moreHeaders. Returns MIMEMessageContent instance.

// plain text
message.setMessage('text/plain', 'This is plain text.')

// or/and html
message.setMessage('text/html', 'This is <strong>html</strong>.')

// or in base64 encoded format
const encoded = message.toBase64('This is <strong>html</strong>.')
const headers = {'Content-Transfer-Encoding': 'base64'}
message.setMessage('text/html', encoded, headers)

.getMessageByType(type)

Returns MIMEMessageContent instance.

.setAttachment(filename, type, data, moreHeaders={})

Adds an attachment to the email. type is the mime type of the file. data should be base64 encoded content of the file. Headers for this attachment can be specified with moreHeaders. Returns MIMEMessageContent instance.

const encoded = message.toBase64( fs.readFileSync('./tests/test.jpg') )
message.setAttachment('test.jpg', 'image/jpg', encoded)

// add content id header to use the attachment inside email body
// <img src="cid:abc123">
message.setAttachment('test.jpg', 'image/jpg', encoded, {
  'Content-ID': 'abc123'
})

.getAttachments()

Returns an array of MIMEMessageContent instances.

.asRaw()

Generates and returns the RFC-2822 compliant email message. This message can be used to send an email.

.asEncoded()

Generates and returns the base64 encoded RFC-2822 compliant email message. This message also can be used to send an email.

Use Cases

Some of email services such as Amazon SES or Google Gmail may require you to create the mime message to send an email programmatically. This library built for those kind of services but mime messages already has a wide range of use cases in general.

Amazon SES with AWS-SDK

// init aws sdk
const AWS = require('aws-sdk')
const ses = new AWS.SES({region: ''})

// init mimetext
const {createMimeMessage} = require('mimetext')
const message = createMimeMessage()

// create email message
message.setSender('[email protected]')
message.setTo('[email protected]')
message.setSubject('Weekly Newsletter 49 Ready ๐Ÿš€')
message.setAttachment('bill.pdf', 'application/pdf', data)
message.setMessage('text/html', 'Hello <b>John</b>.')

// send email with aws sdk
const params = {
  Destinations: message.getRecipients({type: 'to'}).map(mailbox => mailbox.addr),
  RawMessage: {
    Data: message.asRaw() // aws-sdk does the base64 encoding
  },
  Source: message.getSender().addr
}

ses.sendRawEmail(params, function(err, result) {
  // err or result.MessageId
})

Google Gmail with googleapis-sdk

// init google api sdk
const {google} = require('googleapis')

// create email message
const {createMimeMessage} = require('mimetext')
const message = createMimeMessage()
message.setSender('[email protected]')
message.setTo('[email protected]')
message.setSubject('Weekly Newsletter 49 Ready ๐Ÿš€')
message.setAttachment('bill.pdf', 'application/pdf', data)
message.setMessage('text/html', 'Hello <b>John</b>.')

// send email
google.auth
  .getClient({scopes: ['https://www.googleapis.com/auth/gmail.send']})
  .then(function(client) {
    client.subject = '[email protected]'

    const gmail = google.gmail({ version: 'v1', auth: client })

    gmail.users.messages
      .send({
        userId: 'me',
        requestBody: {
          raw: message.asEncoded()
        }
      })
      .then(function(result) {
        // result.id
      })
      .catch(function(err) {

      })
  })

Error Handling

Setter methods raise an instance MIMETextError on bad input.

try {
  message.setTo({prop: 'invalid'})
} catch (e) {
  e instanceof MIMETextError === true
  e.name === 'MIMETextError'
  e.description === 'The input should have an "addr" property that specifies ...'
}

Version management of this repository done by releaser ๐Ÿš€


Thanks for watching ๐Ÿฌ

ko-fi

About

RFC 2822 compliant email message generator written in node.js

Resources

License

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published

Languages

  • JavaScript 100.0%