Author: saqibkhan

  • Using Environment Variables

    For security, store sensitive information like email credentials in environment variables:

    let transporter = nodemailer.createTransport({
    
    service: 'gmail',
    auth: {
        user: process.env.EMAIL_USER,
        pass: process.env.EMAIL_PASS
    }
    });

    In your .env file:

    [email protected]
    EMAIL_PASS=your-email-password
    
  • HTML Email with Inline Images

    For inline images, use the cid (Content-ID) in your HTML:

    <img src="cid:[email protected]" />
    
  • Attachments

    To send attachments, modify the mailOptions like so:

    let mailOptions = {
    
    from: '"Your Name" &lt;[email protected]>',
    to: '[email protected]',
    subject: 'Hello ✔',
    text: 'Hello world?',
    html: '&lt;b>Hello world?&lt;/b>',
    attachments: &#91;
        {
            filename: 'file.txt',
            path: '/path/to/file.txt'
        },
        {
            filename: 'image.png',
            path: '/path/to/image.png',
            cid: '[email protected]' // for inline images
        }
    ]
    };
  • Using SMTP

    If you need to use a custom SMTP server, configure it like this:

    let transporter = nodemailer.createTransport({
    
    host: 'smtp.example.com',
    port: 587, // or 465 for SSL
    secure: false, // true for 465, false for other ports
    auth: {
        user: 'your-username',
        pass: 'your-password'
    }
    });
  • Using Other Email Services

    You can configure Nodemailer to use other email services by adjusting the transport configuration. For example, to use SendGrid:

    let transporter = nodemailer.createTransport({
    
    service: 'SendGrid',
    auth: {
        user: 'apikey', // This is the default SendGrid username
        pass: 'your-sendgrid-api-key'
    }
    });
  • Basic Usage

    Here’s a simple example of sending an email:

    const nodemailer = require('nodemailer');
    
    // Create a transporter object using SMTP transport
    let transporter = nodemailer.createTransport({
    
    service: 'gmail', // You can use other services like 'hotmail', 'yahoo', etc.
    auth: {
        user: '[email protected]',
        pass: 'your-email-password'
    }
    }); // Set up email data let mailOptions = {
    from: '"Your Name" &lt;[email protected]>', // sender address
    to: '[email protected]', // list of receivers
    subject: 'Hello ✔', // Subject line
    text: 'Hello world?', // plain text body
    html: '&lt;b>Hello world?&lt;/b>' // html body
    }; // Send mail with defined transport object transporter.sendMail(mailOptions, (error, info) => {
    if (error) {
        return console.log(error);
    }
    console.log('Message sent: %s', info.messageId);
    });
  • Installation

    First, you need to install Nodemailer using npm:

    npm install nodemailer
    
  • CORS with OAuth and Authentication

    1. OAuth

    When using OAuth, you often deal with CORS because OAuth flows might involve multiple redirects and cross-origin requests:

    • Redirect URIs: Ensure that your authorization server allows the origin of your application in its CORS configuration.
    • State Parameter: Use the state parameter to maintain the security of the OAuth flow and prevent CSRF attacks.

    2. JWT

    When using JSON Web Tokens (JWT) for authentication, ensure the following:

    • Credentials Configuration: If using cookies for storing JWTs, configure CORS to support credentials. This ensures that cookies are included in requests.
    • Secure Headers: Verify that JWTs are sent in secure headers like Authorization and that CORS settings permit these headers.
  • Best Practices for CORS Configuration

    1. Least Privilege Principle

    • Restrict Origins: Only allow origins that are necessary for your application. Avoid using '*' to permit all origins, especially when handling sensitive data.
    • Limit Methods and Headers: Only allow the HTTP methods and headers that are needed. This minimizes potential security risks.

    2. Validate Preflight Requests

    • Proper Handling of OPTIONS Requests: Ensure that the server correctly handles OPTIONS requests and responds with appropriate CORS headers.
    • Check Request Headers: Validate that the headers sent in the preflight request are allowed by your CORS policy.

    3. Use HTTPS

    • Secure Connections: Always use HTTPS to prevent man-in-the-middle attacks. CORS configurations should be applied in a secure context to ensure that data is transmitted safely.
  • Using CORS Middleware in Other Frameworks

    • Koa: For Koa.js, use the @koa/cors package:
    const Koa = require('koa'); const cors = require('@koa/cors'); const app = new Koa(); app.use(cors());
    • Hapi: For Hapi.js, configure CORS in the server options:
    const Hapi = require('@hapi/hapi'); const server = Hapi.server({ port: 3000, host: 'localhost', routes: { cors: { origin: ['http://example.com'], headers: ['Accept', 'Authorization', 'Content-Type'], credentials: true, }, }, });