What is mailcomposer?
The mailcomposer npm package is a tool for creating email messages with various features such as attachments, HTML content, and custom headers. It is useful for generating email content that can be sent using an SMTP client or other email transport methods.
What are mailcomposer's main functionalities?
Basic Email Composition
This feature allows you to compose a basic email with a sender, receiver, subject, and plain text content.
const MailComposer = require('mailcomposer');
const mail = new MailComposer({
from: 'sender@example.com',
to: 'receiver@example.com',
subject: 'Hello',
text: 'Hello world!'
});
mail.build((err, message) => {
if (err) {
console.error('Error:', err);
} else {
console.log('Email message:', message.toString());
}
});
HTML Email Composition
This feature allows you to compose an email with HTML content, which can include rich text formatting and images.
const MailComposer = require('mailcomposer');
const mail = new MailComposer({
from: 'sender@example.com',
to: 'receiver@example.com',
subject: 'Hello',
html: '<h1>Hello world!</h1>'
});
mail.build((err, message) => {
if (err) {
console.error('Error:', err);
} else {
console.log('Email message:', message.toString());
}
});
Attachments
This feature allows you to add attachments to your email, such as files or images.
const MailComposer = require('mailcomposer');
const mail = new MailComposer({
from: 'sender@example.com',
to: 'receiver@example.com',
subject: 'Hello',
text: 'Hello world!',
attachments: [
{
filename: 'text.txt',
content: 'Hello world!'
}
]
});
mail.build((err, message) => {
if (err) {
console.error('Error:', err);
} else {
console.log('Email message:', message.toString());
}
});
Custom Headers
This feature allows you to add custom headers to your email, which can be useful for various purposes such as tracking or custom processing.
const MailComposer = require('mailcomposer');
const mail = new MailComposer({
from: 'sender@example.com',
to: 'receiver@example.com',
subject: 'Hello',
text: 'Hello world!',
headers: {
'X-Custom-Header': 'Custom header value'
}
});
mail.build((err, message) => {
if (err) {
console.error('Error:', err);
} else {
console.log('Email message:', message.toString());
}
});
Other packages similar to mailcomposer
nodemailer
Nodemailer is a module for Node.js applications to allow easy email sending. It supports various transport methods, including SMTP, and provides a rich set of features for composing and sending emails. Compared to mailcomposer, Nodemailer is more comprehensive as it includes both email composition and transport functionalities.
emailjs
EmailJS is a library for sending emails from JavaScript applications. It supports SMTP and provides features for composing and sending emails. While it offers similar functionalities to mailcomposer, it also includes built-in transport methods, making it a more complete solution for email handling.
sendmail
Sendmail is a simple way to send emails from your Node.js application without needing a dedicated SMTP server. It is lightweight and easy to use, but it lacks some of the advanced composition features provided by mailcomposer.
mailcomposer
mailcomposer is a Node.JS module for generating e-mail messages that can be
streamed to SMTP or file.
This is a standalone module that only generates raw e-mail source, you need to
write your own or use an existing transport mechanism (SMTP client, Amazon SES,
SendGrid etc). mailcomposer frees you from the tedious task of generating
rfc822 compatible messages.
See autogenerated docs here.
mailcomposer supports:
- Unicode to use any characters ✔
- HTML content as well as plain text alternative
- Attachments and streaming for larger files (use strings, buffers, files or binary streams as attachments)
- Embedded images in HTML
- usage of your own transport mechanism
Installation
Install through NPM
npm install mailcomposer
Usage
Include mailcomposer module
var MailComposer = require("mailcomposer").MailComposer;
Create a new MailComposer
instance
var mailcomposer = new MailComposer([options]);
Where options
is an optional options object with the following possible properties:
- escapeSMTP - if set replaces dots in the beginning of a line with double dots
- encoding - sets transfer encoding for the textual parts (defaults to
"quoted-printable"
) - keepBcc - if set to true, includes
Bcc:
field in the message headers. Useful for sendmail command.
Simple example
The following example generates a simple e-mail message with plaintext and html
body.
var MailComposer = require("mailcomposer").MailComposer;
mailcomposer = new MailComposer(),
fs = require("fs");
// add additional header field
mailcomposer.addHeader("x-mailer", "Nodemailer 1.0");
// setup message data
mailcomposer.setMessageOption({
from: "andris@tr.ee",
to: "andris@node.ee",
body: "Hello world!",
html: "<b>Hello world!</b>"
});
mailcomposer.streamMessage();
// pipe the output to a file
mailcomposer.pipe(fs.createWriteStream("test.eml"));
The output for such a script (the contents for "test.eml") would look like:
MIME-Version: 1.0
X-Mailer: Nodemailer 1.0
From: andris@tr.ee
To: andris@node.ee
Content-Type: multipart/alternative;
boundary="----mailcomposer-?=_1-1328088797399"
------mailcomposer-?=_1-1328088797399
Content-Type: text/plain; charset=utf-8
Content-Transfer-Encoding: quoted-printable
Hello world!
------mailcomposer-?=_1-1328088797399
Content-Type: text/html; charset=utf-8
Content-Transfer-Encoding: quoted-printable
<b>Hello world!</b>
------mailcomposer-?=_1-1328088797399--
API
Headers can be added with mailcomposer.addHeader(key, value)
var mailcomposer = new MailComposer();
mailcomposer.addHeader("x-mailer", "Nodemailer 1.0");
If you add an header value with the same key several times, all of the values will be used
in the generated header. For example:
mailcomposer.addHeader("x-mailer", "Nodemailer 1.0");
mailcomposer.addHeader("x-mailer", "Nodemailer 2.0");
Will be generated into
...
X-Mailer: Nodemailer 1.0
X-Mailer: Nodemailer 2.0
...
The contents of the field value is not edited any way (except for the folding),
so if you want to use unicode symbols you need to escape these to mime words
by yourself.
Add message parts
You can set message sender, receiver, subject line, message body etc. with
mailcomposer.setMessageOption(options)
where options is an object with the
data to be set. This function overwrites any previously set values with the
same key
The following example creates a simple e-mail with sender being andris@tr.ee
,
receiver andris@node.ee
and plaintext part of the message as Hello world!
:
mailcomposer.setMessageOption({
from: "andris@tr.ee",
to: "andris@node.ee",
body: "Hello world!"
});
Possible options that can be used are (all fields accept unicode):
- from (alias
sender
) - the sender of the message. If several addresses are given, only the first one will be used - to - receivers for the
To:
field - cc - receivers for the
Cc:
field - bcc - receivers for the
Bcc:
field - replyTo (alias
reply_to
) - e-mail address for the Reply-To:
field - subject - the subject line of the message
- body (alias
text
) - the plaintext part of the message - html - the HTML part of the message
This method can be called several times
mailcomposer.setMessageOption({from: "andris@tr.ee"});
mailcomposer.setMessageOption({to: "andris@node.ee"});
mailcomposer.setMessageOption({body: "Hello world!"});
Trying to set the same key several times will yield in overwrite
mailcomposer.setMessageOption({body: "Hello world!"});
mailcomposer.setMessageOption({body: "Hello world?"});
// body contents will be "Hello world?"
Address format
All e-mail address fields take structured e-mail lists (comma separated)
as the input. Unicode is allowed for all the parts (receiver name, e-mail username
and domain) of the address. If the domain part contains unicode symbols, it is
automatically converted into punycode, user part will be converted into UTF-8
mime word.
E-mail addresses can be a plain e-mail addresses
username@example.com
or with a formatted name
'Ноде Майлер' <username@example.com>
Or in case of comma separated lists, the formatting can be mixed
username@example.com, 'Ноде Майлер' <username@example.com>, "Name, User" <username@example.com>
Add attachments
Attachments can be added with mailcomposer.addAttachment(attachment)
where
attachment
is an object with attachment (meta)data with the following possible
properties:
- fileName (alias
filename
) - filename to be reported as the name of the attached file, use of unicode is allowed - cid - content id for using inline images in HTML message source
- contents - String or a Buffer contents for the attachment
- filePath - path to a file if you want to stream the file instead of including it (better for larger attachments)
- streamSource - Stream object for arbitrary binary streams if you want to stream the contents (needs to support pause/resume)
- contentType - content type for the attachment, if not set will be derived from the
fileName
property
One of contents
, filePath
or streamSource
must be specified, if none is
present, the attachment will be discarded. Other fields are optional.
Attachments can be added as many as you want.
Using embedded images in HTML
Attachments can be used as embedded images in the HTML body. To use this
feature, you need to set additional property of the attachment - cid
(unique identifier of the file) which is a reference to the attachment file.
The same cid
value must be used as the image URL in HTML (using cid:
as
the URL protocol, see example below).
NB! the cid value should be as unique as possible!
var cid_value = Date.now() + '.image.jpg';
var html = 'Embedded image: <img src="cid:' + cid_value + '" />';
var attachment = {
fileName: "image.png",
filePath: "/static/images/image.png",
cid: cid_value
};
Start streaming
When the message data is setup, streaming can be started. After this it is not
possible to add headers, attachments or change body contents.
mailcomposer.streamMessage();
This generates 'data'
events for the message headers and body and final 'end'
event.
As MailComposer
objects are Stream instances, these can be piped
// save the output to a file
mailcomposer.streamMessage();
mailcomposer.pipe(fs.createWriteStream("out.txt"));
Envelope
Envelope can be generated with an getEnvelope()
which returns an object
that includes a from
address (string) and a list of to
addresses (array of
strings) suitable for forwarding to a SMTP server as MAIL FROM:
and RCPT TO:
.
console.log(mailcomposer.getEnvelope());
// {from:"sender@example.com", to:["receiver@example.com"]}
NB! both from
and to
properties might be missing from the envelope object
if corresponding addresses were not detected from the e-mail.
Running tests
Tests are run with nodeunit
Run
npm test
or alternatively
node run_tests.js
License
MIT