`
- **to** - Comma separated list or an array of recipients e-mail addresses that will appear on the `To:` field
- **cc** - Comma separated list or an array of recipients e-mail addresses that will appear on the `Cc:` field
- **bcc** - Comma separated list or an array of recipients e-mail addresses that will appear on the `Bcc:` field
- **replyTo** - An e-mail address that will appear on the `Reply-To:` field
- **inReplyTo** - The message-id this message is replying
- **references** - Message-id list
- **subject** - The subject of the e-mail
- **text** - The plaintext version of the message
- **html** - The HTML version of the message
- **generateTextFromHTML** - if set to true uses HTML to generate plain text body part from the HTML if the text is not defined
- **headers** - An object of additional header fields `{"X-Key-Name": "key value"}` (NB! values are passed as is, you should do your own encoding to 7bit and folding if needed)
- **attachments** - An array of attachment objects.
- **alternatives** - An array of alternative text contents (in addition to text and html parts)
- **envelope** - optional SMTP envelope, if auto generated envelope is not suitable
- **messageId** - optional Message-Id value, random value will be generated if not set. Set to false to omit the Message-Id header
- **date** - optional Date value, current UTC string will be used if not set
- **encoding** - optional transfer encoding for the textual parts (defaults to "quoted-printable")
- **charset** - optional output character set for the textual parts (defaults to "utf-8")
- **dsn** - An object with methods `success`, `failure` and `delay`. If any of these are set to true, DSN will be used
All text fields (e-mail addresses, plaintext body, html body) use UTF-8 as the encoding.
Attachments are streamed as binary.
Example:
```javascript
var transport = nodemailer.createTransport("Sendmail");
var mailOptions = {
from: "me@tr.ee",
to: "me@tr.ee",
subject: "Hello world!",
text: "Plaintext body"
}
transport.sendMail(mailOptions);
```
### SendGrid support
Nodemailer supports SendGrid [SMTP API](http://docs.sendgrid.com/documentation/api/smtp-api/) out of the box - you can
use objects as header values and these are automatically JSONized (and mime encoded if needed).
```javascript
var mailOptions = {
...,
headers: {
'X-SMTPAPI': {
category : "newuser",
sub:{
"%name%": ["Žiguli Õllepruul"]
}
}
},
subject: "Hello, %name%"
}
```
This also applies to any other service that expects a JSON string as a header value for specified key.
### Generate Text from HTML
If `generateTextFromHTML` option is set to true, then HTML contents of the mail is automatically converted
to plaintext format when plaintext content is empty or missing.
For example
```javascript
mailOptions = {
...,
generateTextFromHTML: true,
html: 'Hello world
How are you?',
// text: '' // no text part
}
```
is automatically converted in the backround by Nodemailer to:
```javascript
mailOptions = {
...,
// source html:
html: '
Hello world
How are you?',
// automatically generated plaintext message:
text: "Hello world\n"+
"===========\n"+
"\n"+
"**How** are you?"
}
```
As you can see the output syntax for `generateTextFromHTML` looks similar to markdown, and that
is exactly the case here - Nodemailer includes a simple HTML to markdown converter. But don't
expect too much from it, it's not full featured or perfect, just some regexes here and there.
### Attachment fields
Attachment object consists of the following properties:
* **fileName** - filename to be reported as the name of the attached file, use of unicode is allowed (except when using Amazon SES which doesn't like it)
* **cid** - optional content id for using inline images in HTML message source
* **contents** - String or a Buffer contents for the attachment
* **filePath** - path to a file or an URL 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** - optional content type for the attachment, if not set will be derived from the `fileName` property
* **contentDisposition** - optional content disposition type for the attachment, defaults to "attachment"
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.
```javascript
var mailOptions = {
...
attachments: [
{ // utf-8 string as an attachment
fileName: "text1.txt",
contents: "hello world!"
},
{ // binary buffer as an attachment
fileName: "text2.txt",
contents: new Buffer("hello world!","utf-8")
},
{ // file on disk as an attachment
fileName: "text3.txt",
filePath: "/path/to/file.txt" // stream this file
},
{ // fileName and content type is derived from filePath
filePath: "/path/to/file.txt"
},
{ // stream as an attachment
fileName: "text4.txt",
streamSource: fs.createReadStream("file.txt")
},
{ // define custom content type for the attachment
fileName: "text.bin",
contents: "hello world!",
contentType: "text/plain"
},
{ // use URL as an attachment
fileName: "license.txt",
filePath: "https://raw.github.com/andris9/Nodemailer/master/LICENSE"
}
]
}
```
### Alternative fields
In addition to text and HTML, any kind of data can be inserted as an alternative content of the main body - for example a word processing document with the same text as in the HTML field. It is the job of the e-mail client to select and show the best fitting alternative to the reader.
Attahcment object consists of the following properties:
* **contents** - String or a Buffer contents for the attachment
* **contentType** - optional content type for the attachment, if not set will be set to "application/octet-stream"
* **contentEncoding** - optional value of how the data is encoded, defaults to "base64"
If `contents` is empty, the alternative will be discarded. Other fields are optional.
**Usage example:**
```javascript
var mailOptions = {
...
html: "Hello world!",
alternatives: [
{
contentType: "text/x-web-markdown",
contents: "**Hello world!**"
}
]
}
```
If the receiving e-mail client can render messages in Markdown syntax as well, it could prefer
to display this alternative as the main content of the message instead of the html part.
Alternatives can be added as many as you want.
### Address Formatting
All the e-mail addresses can be plain e-mail address
```
foobar@blurdybloop.com
```
or with formatted name (includes unicode support)
```
"Ноде Майлер"
```
To, Cc and Bcc fields accept comma separated list of e-mails or an array of
emails or an array of comma separated list of e-mails - use it as you like.
Formatting can be mixed.
```
...,
to: 'foobar@blurdybloop.com, "Ноде Майлер" , "Name, User" ',
cc: ['foobar@blurdybloop.com', '"Ноде Майлер" , "Name, User" ']
...
```
You can even use unicode domain and user names, these are automatically converted
to the supported form
```
"Unicode Domain"
```
### SMTP envelope
SMTP envelope is usually auto generated from `from`, `to`, `cc` and `bcc` fields but
if for some reason you want to specify it yourself, you can do it with `envelope` property.
`envelope` is an object with the following params: `from`, `to`, `cc` and `bcc` just like
with regular mail options. You can also use the regular address format, unicode domains etc.
```javascript
mailOptions = {
...,
from: "mailer@kreata.ee",
to: "daemon@kreata.ee",
envelope: {
from: "Daemon ",
to: "mailer@kreata.ee, Mailer "
}
}
```
The envelope only applies when using SMTP or sendmail, setting envelope has no effect with SES.
### Using Embedded Images
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!
```javascript
var mailOptions = {
...
html: "Embedded image: ",
attachments: [{
filename: "image.png",
filePath: "/path/to/file",
cid: "unique@kreata.ee" //same cid value as in the html img src
}]
}
```
**Automatic embedding images**
If you want to convert images in the HTML to embedded images automatically, you can
set mail option `forceEmbeddedImages` to true. In this case all images in
the HTML that are either using an absolute URL (http://...) or absolute file path
(/path/to/file) are replaced with embedded attachments.
For example when using this code
```javascript
var mailOptions = {
forceEmbeddedImages: true
html: 'Embedded image: '
};
```
The image linked is fetched and added automatically as an attachment and the url
in the HTML is replaced automatically with a proper `cid:` string.
## Return callback
Return callback gets two parameters
* **error** - an error object if the message failed
* **responseStatus** - an object with some information about the status on success
* **responseStatus.messageId** - message ID used with the message
> Different transport methods may expose additional properties to the `responseStatus` object, eg. *direct* transport exposes `statusHandler`, see the docs for the particular transport type for more info.
Example:
```javascript
nodemailer.sendMail(mailOptions, function(error, responseStatus){
if(!error){
console.log(responseStatus.message); // response from the server
console.log(responseStatus.messageId); // Message-ID value used
}
});
```
**NB!** Message-ID used might not be the same that reaches recipients inbox since some providers (like **SES**) may change the value.
## Custom Transport Methods
If you want to use a custom transport method you need to define a constructor function with the following API
```javascript
function MyCustomHandler(options){}
MyCustomHandler.prototype.sendMail = function(emailMessage, callback){};
MyCustomHandler.prototype.close = function(closeCallback){};
```
Where
* `options` is the optional options object passed to `createTransport`
* `sendMail()` is the function that is going to deliver the message
* `emailMessage` is a paused [MailComposer](https://github.com/andris9/mailcomposer#create-a-new-mailcomposer-instance) object. You should call `emailMessage.streamMessage()` once you have everything set up for streaming the message
* `callback` is the function to run once the message has been sent or an error occurred. The response object *should* include `messageId` property (you can get the value from `emailMessage._messageId`)
* `close()` is an optional method (no need to define it) to close the transport method
* `closeCallback` is the function to run once the transport method is closed
### Example usage
```javascript
var nodemailer = require("nodemailer");
// Pipes all messages to stdout
function MyTransport(options){
this.options = options;
}
MyTransport.prototype.sendMail = function(emailMessage, callback) {
console.log("Envelope: ", emailMessage.getEnvelope());
emailMessage.pipe(process.stdout);
emailMessage.on("error", function(err){
callback(err);
});
emailMessage.on("end", function(){
callback(null, {
messageId: emailMessage._messageId
});
});
// everything set up, start streaming
emailMessage.streamMessage();
};
// Use MyTransport as the transport method
var transport = nodemailer.createTransport(MyTransport, {
name: "my.host" // hostname for generating Message-ID values
});
transport.sendMail({
from: "sender@example.com",
to: "receiver@example.com",
subject: "hello",
text: "world"
}, function(err, response){
console.log(err || response);
});
```
## Command line usage
**NB!** Command line usage was removed from v0.4
## Tests
Run the tests with npm in Nodemailer's directory
```
npm test
```
There aren't currently many tests for Nodemailer but there are a lot of tests
in the modules that are used to generate the raw e-mail body and to use the
SMTP client connection.
## Tweaking
Nodemailer in itself is actually more like a wrapper for my other modules
[mailcomposer](https://github.com/andris9/mailcomposer) for composing the raw message stream
and [simplesmtp](https://github.com/andris9/simplesmtp) for delivering it, by providing an
unified API. If there's some problems with particular parts of the
message composing/sending process you should look at the appropriate module.
## License
**Nodemailer** is licensed under [MIT license](https://github.com/andris9/Nodemailer/blob/master/LICENSE). Basically you can do whatever you want to with it.
----
The Nodemailer logo was designed by [Sven Kristjansen](https://www.behance.net/kristjansen).
[![Bitdeli Badge](https://d2weczhvl823v0.cloudfront.net/andris9/nodemailer/trend.png)](https://bitdeli.com/free "Bitdeli Badge")