Attach document for mail in nodejs
In Node.js, you can attach a document to an email using the nodemailer
library. Here's an example:
const nodemailer = require('nodemailer');
// create a transporter object
let transporter = nodemailer.createTransport({
host: 'smtp.example.com',
port: 587,
secure: false, // or 'STARTTLS'
auth: {
user: '[email protected]',
pass: 'your_password'
}
});
// define the email options
let mailOptions = {
from: '[email protected]',
to: '[email protected]',
subject: 'Test email with attachment',
text: 'Hello',
attachments: [
{
filename: 'example.txt',
content: 'Hello World!'
}
]
};
// send the email
transporter.sendMail(mailOptions, (error, info) => {
if (error) {
return console.log(error);
}
console.log('Email sent: ' + info.response);
});
In this example, we create a nodemailer
transporter object and define the email options using the mailOptions
object. We set the attachments
property to an array of objects, where each object represents an attachment. In this case, we're attaching a text file named example.txt
with the contents Hello World!
.
You can also attach binary files, such as images or PDFs, by using the Buffer
class to convert the file contents to a binary string. Here's an example:
const fs = require('fs');
const path = require('path');
// read the file contents
const fileBuffer = fs.readFileSync(path.join(__dirname, 'example.pdf'));
// define the email options
let mailOptions = {
from: '[email protected]',
to: '[email protected]',
subject: 'Test email with attachment',
text: 'Hello',
attachments: [
{
filename: 'example.pdf',
content: fileBuffer,
contentType: 'application/pdf'
}
]
};
In this example, we read the contents of a PDF file using the fs
module and convert it to a binary string using the Buffer
class. We then set the attachments
property to an array of objects, where each object represents an attachment. In this case, we're attaching the PDF file with the name example.pdf
and the MIME type application/pdf
.
You can also use the nodemailer
library to attach files from a URL or a stream. Here's an example:
const url = 'https://example.com/example.pdf';
// define the email options
let mailOptions = {
from: '[email protected]',
to: '[email protected]',
subject: 'Test email with attachment',
text: 'Hello',
attachments: [
{
filename: 'example.pdf',
url: url
}
]
};
In this example, we define the email options and set the attachments
property to an array of objects, where each object represents an attachment. In this case, we're attaching a file from a URL with the name example.pdf
.
Note that you'll need to install the nodemailer
library using npm or yarn before you can use it in your Node.js application. You can install it using the following command:
npm install nodemailer
Or:
yarn add nodemailer