# nodemailer

***

**1. Sending HTML Emails**

```javascript
const nodemailer = require("nodemailer");

// create reusable transporter object using SMTP transport
const transporter = nodemailer.createTransport({
  host: "smtp.ethereal.email",
  port: 587,
  secure: false, // true for 465, false for other ports
  auth: {
    user: "hjembir.pagac@ethereal.email", // generated ethereal user
    pass: "KSMN5WY2989rK2gfnf", // generated ethereal password
  },
});

// setup email data with HTML content
const mailOptions = {
  from: '"John Doe" <john.doe@example.com>', // sender address
  to: "recipient@example.com", // list of receivers
  subject: "Hello from Nodemailer", // Subject line
  html: "<h1>Hello, world!</h1>", // html body
};

// send mail with defined transport object
transporter.sendMail(mailOptions, (error, info) => {
  if (error) {
    console.log(error);
  } else {
    console.log("Message sent: %s", info.messageId);
  }
});
```

**2. Sending Text-Only Emails**

```javascript
// Use the same setup as above, but change the 'html' option to 'text':

mailOptions.text = "Hello, world!";
```

**3. Sending Emails with Attachments**

```javascript
// Use the same setup as above, but add an 'attachments' array to the mailOptions:

mailOptions.attachments = [
  {
    filename: "attachment1.txt",
    path: "/path/to/attachment1.txt",
  },
  {
    filename: "attachment2.pdf",
    path: "/path/to/attachment2.pdf",
  },
];
```

**4. Sending Emails with Inline Images**

```javascript
// Use the same setup as above, but use the 'cid' attribute in the HTML content:

mailOptions.html = '<img src="cid:logo" />';

// Define the inline image in the 'attachments' array:

mailOptions.attachments = [
  {
    filename: "logo.png",
    path: "/path/to/logo.png",
    cid: "logo", // same as the 'cid' in the HTML
  },
];
```

**5. Sending Emails with Multiple Recipients**

```javascript
// Use the same setup as above, but use a comma-separated list for the 'to' option:

mailOptions.to = "recipient1@example.com, recipient2@example.com";
```

**6. Using a Custom SMTP Server**

```javascript
// Use the same setup as above, but specify a custom SMTP server:

const transporter = nodemailer.createTransport({
  host: "your-smtp-host",
  port: 587,
  secure: false,
  auth: {
    user: "your-smtp-username",
    pass: "your-smtp-password",
  },
});
```

**7. Using OAuth2**

```javascript
// Use the same setup as above, but use OAuth2 instead of SMTP authentication:

const transporter = nodemailer.createTransport({
  service: "gmail",
  auth: {
    type: "OAuth2",
    user: "your-gmail-username",
    clientId: "your-gmail-client-id",
    clientSecret: "your-gmail-client-secret",
    refreshToken: "your-gmail-refresh-token",
  },
});
```

**8. Sending Emails through Sendgrid**

```javascript
const nodemailer = require("nodemailer");
const sendgridTransport = require("nodemailer-sendgrid-transport");

// Use the same setup as above, but use the sendgridTransport:

const transporter = nodemailer.createTransport(
  sendgridTransport({
    auth: {
      api_key: "your-sendgrid-api-key",
    },
  })
);
```

**9. Sending Emails through Mailgun**

```javascript
const nodemailer = require("nodemailer");
const mailgunTransport = require("nodemailer-mailgun-transport");

// Use the same setup as above, but use the mailgunTransport:

const transporter = nodemailer.createTransport(
  mailgunTransport({
    auth: {
      api_key: "your-mailgun-api-key",
      domain: "your-mailgun-domain",
    },
  })
);
```

**10. Sending Emails through Amazon SES**

```javascript
const nodemailer = require("nodemailer");
const sesTransport = require("nodemailer-ses-transport");

// Use the same setup as above, but use the sesTransport:

const transporter = nodemailer.createTransport(
  sesTransport({
    auth: {
      accessKeyId: "your-aws-access-key-id",
      secretAccessKey: "your-aws-secret-access-key",
      region: "us-east-1", // your SES region
    },
  })
);
```

**11. Verifying SMTP Connection**

```javascript
const nodemailer = require("nodemailer");

// create transporter object using SMTP transport
const transporter = nodemailer.createTransport({
  host: "smtp.example.com",
  port: 587,
  secure: false, // true for 465, false for other ports
});

// verify SMTP connection
transporter.verify((error, success) => {
  if (error) {
    console.log(error);
  } else {
    console.log("SMTP connection verified:", success);
  }
});
```

**12. Sending Confirmation Emails**

```javascript
// Use the same setup as above, and send a confirmation email after signup:

transporter.sendMail({
  from: '"Your App Name" <info@yourapp.com>',
  to: user.email,
  subject: "Welcome to Your App!",
  html: `<h1>Welcome to Your App, ${user.name}!</h1><p>Thank you for signing up.</p><p>Please click the link below to confirm your email address:</p><a href="https://yourapp.com/confirm-email/${user._id}">Confirm Email</a><p>Sincerely,</p><p>The Your App Team</p>`,
});
```

**13. Sending Reset Password Emails**

```javascript
// Use the same setup as above, and send a reset password email:

transporter.sendMail({
  from: '"Your App Name" <info@yourapp.com>',
  to: user.email,
  subject: "Reset your Password",
  html: `<h1>Reset your Password</h1><p>You requested a password reset for your account, please click the link below to reset your password.</p><a href="https://yourapp.com/reset-password/${user._id}">Reset Password</a><p>Sincerely,</p><p>The Your App Team</p>`,
});
```

**14. Sending Transactional Emails**

```javascript
// Use the same setup as above, and send a transactional email for an order confirmation:

transporter.sendMail({
  from: '"Your App Name" <info@yourapp.com>',
  to: user.email,
  subject: "Order Confirmed",
  html: `<h1>Order Confirmed</h1><p>Thank you for your order!</p><p>Your order details are as follows:</p><ul><li><b>Order Number:</b> ${order.number}</li><li><b>Order Date:</b> ${order.date}</li><li><b>Total Amount:</b> ${order.amount}</li></ul><p>Sincerely,</p><p>The Your App Team</p>`,
});
```

**15. Sending Email Campaigns**

```javascript
// Use the same setup as above, but use a mailing list for sending email campaigns:

const transporter = nodemailer.createTransport({
  host: "smtp.example.com",
  port: 587,
  secure: false, // true for 465, false for other ports
  auth: {
    user: "your-smtp-username",
    pass: "your-smtp-password",
  },
});

const mailingList = ["recipient1@example.com", "recipient2@example.com"];

// Define the email campaign
const mailOptions = {
  from: '"Your App Name" <info@yourapp.com>',
  subject: "Your Awesome Email Campaign",
  html: `<h1>Your Awesome Email Campaign Content</h1><p>This is the content of your email campaign.</p><a href="https://yourapp.com">Visit Your App</a><p>Sincerely,</p><p>The Your App Team</p>`,
};

// Send the email campaign to the mailing list
mailingList.forEach((recipient) => {
  mailOptions.to = recipient;
  transporter.sendMail(mailOptions);
});
```

**16. Using Custom Transporters**

```javascript
// Create a custom transporter using a custom transport class:

class MyCustomTransport {
  constructor(options) {
    this.options = options;
  }
  sendMail(mailOptions, callback) {
    // Implement your custom sendMail logic here
    // ...

    callback(null, { messageId: "custom-message-id" });
  }
}

const transporter = nodemailer.createTransport(new MyCustomTransport({
  // Custom transport options
}));

// Then use the transporter as usual
transporter.sendMail({
  // ...
});
```

**17. Using a Queue**

```javascript
// Create a queue to send emails asynchronously:

const queue = new Queue({
  name: "email-queue",
  redis: {
    host: "localhost",
    port: 6379,
  },
});

// Add a task to the queue
queue.add({
  to: "recipient@example.com",
  subject: "Hello from Nodemailer",
  html: "<h1>Hello, world!</h1>",
}, (error) => {
  if (error) {
    console.log(error);
  } else {
    console.log("Email added to queue.");
  }
});

// Start the queue worker
queue.start();
```

**18. Using a Scheduler**

```javascript
// Create a scheduler to send emails at specific intervals:

const scheduler = new Scheduler({
  name: "email-scheduler",
  redis: {
    host: "localhost",
    port: 6379,
  },
});

// Add a job to the scheduler
scheduler.add({
  name: "send-daily-emails",
  cronTime: "0 0 * * *", // Every day at midnight
  task: (params, callback) => {
    // Send emails here
    // ...

    callback();
  },
});

// Start the scheduler
scheduler.start();
```

**19. Sending Emails with Multiple Transports**

```javascript
// Create multiple transporters and use a custom transport picker:

const gmailTransport = nodemailer.createTransport({
  service: "gmail",
  auth: {
    user: "your-gmail-username",
    pass: "your-gmail-password",
  },
});

const sendgridTransport = nodemailer.createTransport({
  service: "sendgrid",
  auth: {
    api_key: "your-sendgrid-api-key",
  },
});

const transporterPicker = {
  ["gmail.com"]: gmailTransport,
  ["sendgrid.com"]: sendgridTransport,
};

const transporter = nodemailer.createTransport({
  transportPicker,
});

// Determine the transport based on the recipient's domain
const recipient = "recipient@gmail.com";
const domain = recipient.split("@")[1];
const transport = transporterPicker[domain];

// Send the email
transporter.sendMail({
  // ...
}, transport);
```

**20. Using a Proxy**

```javascript
// Create a proxy to send emails through a proxy server:

const proxy = "http://localhost:8080";
const transporter = nodemailer.createTransport({
  proxy,
  // Other transport options
});
```

**21. Using a VPN**

```javascript
// Create a transport that uses a VPN connection:

const tunnel = require("tunneler");
const { createClient } = require("openvpn-api");

const vpn = createClient({
  host: "vpn-host",
  port: 1194,
  auth: {
    username: "username",
    password: "password",
  },
});

const server = tunnel.createServer({
  socket: await vpn.connect(),
});

const transporter = nodemailer.createTransport({
  socket: server,
  // Other transport options
});
```

**22. Sending Emails from a Docker Container**

```javascript
// Create a transport that uses a Docker container:

const docker = require("dockerode");
const { promisify } = require("util");
const { createClient } = require("openvpn-api");

const vpn = createClient({
  host: "vpn-host",
  port: 1194,
  auth: {
    username: "username",
    password: "password",
  },
});

const dockerCompose = `
version: "3.3"
services:
  smtp:
    image: "smtp:latest"
    ports:
      - "25:25"
    volumes:
      - "./mail:/var/mail"
    networks:
      - default
networks:
  default:
    driver: "bridge"
`;

const compose = docker.compose(dockerCompose);
await compose.up({ detach: true });

const transporter = nodemailer.createTransport({
  host: "localhost",
  port: 25,
  // Other transport options
});
```

**23. Using a Command-Line Interface (CLI)**

```javascript
// Create a CLI script to send emails:

const nodemailer = require("nodemailer");
const { program } = require("commander");

program
  .option("-s, --sender [sender]", "The email address of the sender")
  .option("-r, --recipient [recipient]", "The email address of the recipient")
  .option("-t, --subject [subject]", "The subject of the email")
  .option("-c, --content [content]", "The content of the email")
  .parse(process.argv);

const options = program.opts();

const transporter = nodemailer.createTransport({
  host: "smtp.ethereal.email",
  port: 587,
  secure: false, // true for 465, false for other ports
  auth: {
    user: "hjembir.pagac@ethereal.email", // generated ethereal user
    pass: "KSMN5WY2989rK2gfnf", // generated ethereal password
  },
});

const mailOptions = {
  from: options.sender,
  to: options.recipient,
  subject: options.subject,
  text: options.content, // plain text body
  html: options.content, // html body
};

transporter.sendMail(mailOptions, (error, info) => {
  if (error) {
    console.log(error);
  } else {
    console.log("Message sent: %s", info.messageId);
  }
});
```

**24. Sending Emails with DKIM**

```javascript
// Create a transport that uses DKIM signing:

const nodemailer = require("nodemailer");
const dkim = require("nodemailer-dkim");

const transporter = nodemailer.createTransport({
  host: "smtp.ethereal.email",
  port: 587,
  secure: false, // true for 465, false for other ports
  auth: {
    user: "hjembir.pagac@ethereal.email", // generated ethereal user
    pass: "KSMN5WY2989rK2gfnf", // generated ethereal password
  },
  dkim: {
    domainName: "example.com", // your domain name
    keySelector: "20210225_test", // your key selector
    privateKey: fs.readFileSync("private.pem"), // your private key
  },
});

const mailOptions = {
  from: "sender@example.com",
  to: "recipient@example.com",
  subject: "Hello from Nodemailer",
  text: "Hello, world!", // plain text body
  html: "<h1>Hello, world!</h1>", // html body
};

transporter.sendMail(mailOptions, (error, info) => {
  if (error) {
    console.log(error);
  } else {
    console.log("Message sent: %s", info.messageId);
  }
});
```

**25. Sending Emails with SPF**

```javascript
// Create a transport that uses SPF:

const nodemailer = require("nodemailer");
const spf = require("nodemailer-spf");

const transporter = nodemailer.createTransport({
  host: "smtp.ethereal.email",
  port: 587,
  secure: false, // true for 465, false for other ports
  auth: {
    user: "hjembir.pagac@ethereal.email", // generated ethereal user
    pass: "KSMN5WY2989rK2gfnf", // generated ethereal password
  },
  spf: {
    domain: "example.com", // your domain name
    lookup: true, // perform SPF lookup on the recipient's domain
    softfail: false, // throw an error if SPF fails
  },
});

const mailOptions = {
  from: "sender@example.com",
  to: "recipient@example.com",
  subject: "Hello from Nodemailer",
  text: "Hello, world!", // plain text body
  html: "<h1>Hello, world!</h1>", // html body
};

transporter.sendMail(mailOptions, (error, info) => {
  if (error) {
    console.log(error);
  } else {
    console.log("Message sent: %s", info.messageId);
  }
});
```
