All Products
Search
Document Center

Direct Mail:SMTP-Nodejs

Last Updated:Jun 03, 2026

Send email through Direct Mail's SMTP service using Node.js and nodemailer.

Prerequisites

Before you begin, ensure that you have:

  • Activated Direct Mail and created an SMTP account in the Direct Mail console

  • Verified your sender address — the from field in your code must match the verified sender address, or the message will be rejected

  • Your SMTP username and password from the console

Install nodemailer

npm install nodemailer --save

Send an email

The following example uses environment variables to store SMTP credentials.

Set your credentials as environment variables:

export SMTP_USER="username@userdomain"
export SMTP_PASS="your-smtp-password"
const nodemailer = require('nodemailer');

// Create a reusable transporter. You only need to create this once.
const transporter = nodemailer.createTransport({
    host: 'smtpdm.aliyun.com',
    port: 25,
    secure: true, // use SSL
    auth: {
        user: process.env.SMTP_USER, // your Direct Mail SMTP username
        pass: process.env.SMTP_PASS  // your Direct Mail SMTP password
    }
});

const mailOptions = {
    from: 'NickName<username@userdomain>', // sender address — must match your verified sender address
    to: 'x@x.com, xx@xx.com',             // recipients (comma-separated)
    cc: 'haha<xxx@xxx.com>',              // CC recipients
    bcc: 'haha<xxxx@xxxx.com>',           // BCC recipients
    subject: 'Hello',
    text: 'Hello world',                   // plain text body
    html: '<b>Hello world</b><img src="cid:01" style="width:200px;height:auto">', // HTML body
    attachments: [
        {
            filename: 'text0.txt',
            content: 'hello world!'
        },
        {
            filename: 'text1.txt',
            path: './app.js'
        },
        {
            filename: 'test.JPG',
            path: './Desert.jpg',
            cid: '01'              // content ID referenced in HTML body
        }
    ]
};

transporter.sendMail(mailOptions, (error, info) => {
    if (error) {
        return console.error(error);
    }
    console.log('Message sent:', info.response);
});
Important

The from field must match the sender address verified in your Direct Mail account. Mismatches cause authentication failures at send time.