RFC 2822 compliant raw email message generator written in node.js
npm i mimetext
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.
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--
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.
Returns Mailbox
instance.
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
Returns array of Mailbox
instances.
Returns the value
.
const value = 'Weekly Newsletter 49 Ready ๐'
message.setSubject(value)
Returns the value
.
Inserts a header to the message.
message.setHeader('X-Custom-Header', 'value')
Returns the value of the header.
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)
Returns MIMEMessageContent
instance.
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'
})
Returns an array of MIMEMessageContent
instances.
Generates and returns the RFC-2822 compliant email message. This message can be used to send an email.
Generates and returns the base64 encoded RFC-2822 compliant email message. This message also can be used to send an email.
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.
// 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
})
// 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) {
})
})
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 ๐ฌ