You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用Node.js发送草稿邮件?如何通过API、IMAP或SMTP存草稿到文件夹?

Node.js 处理草稿邮件:发送与存入草稿文件夹

一、使用Node.js发送草稿邮件

草稿邮件的发送分两种常见场景:

  • 如果草稿已经存入邮箱的草稿文件夹,可调用对应邮箱的API(比如Gmail API)触发发送。
  • 也可以先构造草稿内容,保存为草稿后再发送,或者在发送时同时留存草稿。

二、通过IMAP/SMTP/API将草稿存入草稿文件夹

1. IMAP协议存入草稿

IMAP支持直接操作邮箱文件夹,可将指定邮件移动到草稿目录。你提供的代码逻辑可行,但需要修正uid未定义的问题——要从邮件属性中获取唯一标识UID:

mails.on("message", (message, seq) => {
    console.log('message', message);
    // 从邮件属性中提取UID
    const uid = message.attributes.uid;
    message.on("body", stream => {
        console.log("results123456--------", uid);
        let buffer = "";
        stream.on("data", chunk => (buffer += chunk.toString("utf8")));
        stream.once("end", () => {
            // 移动到Gmail草稿文件夹(不同邮箱草稿目录名可能不同,比如Outlook是"Drafts")
            mailBox.move(uid, "[Gmail]/Draft", (err) => {
                if (err) {
                    console.error("移动到草稿箱失败:", err);
                    return;
                }
                console.log("邮件已成功存入草稿箱");
            });
        });
    });
});

注:不同邮箱的草稿文件夹名称有差异,需根据实际使用的邮箱调整路径。

2. SMTP协议存入草稿

SMTP主打邮件发送,但部分邮箱支持通过添加特定头信息,将邮件存入草稿箱而非直接发送给收件人。以Gmail为例:

const nodemailer = require('nodemailer');

async function saveDraftViaSMTP() {
    // 创建SMTP传输器
    let transporter = nodemailer.createTransport({
        service: 'Gmail',
        auth: {
            user: 'your-email@gmail.com',
            pass: 'your-app-specific-password' // Gmail需使用应用专用密码(开启两步验证后生成)
        }
    });

    // 配置邮件内容,添加草稿标记头
    let mailOptions = {
        from: 'your-email@gmail.com',
        to: 'target-recipient@example.com', // 收件人信息会保留在草稿中
        subject: '测试草稿邮件',
        text: '这是一封通过SMTP存入的草稿',
        headers: {
            'X-GM-Labels': 'Draft' // 告诉Gmail将邮件标记为草稿
        }
    };

    // 执行操作后,邮件会存入草稿箱而非发送给收件人
    let info = await transporter.sendMail(mailOptions);
    console.log("草稿已保存,消息ID:", info.messageId);
}

saveDraftViaSMTP();

3. 邮箱API存入草稿

以Gmail API为例,直接调用草稿创建接口存入草稿:

const { google } = require('googleapis');

// 假设已完成OAuth2认证,获取到auth对象(需提前配置OAuth2客户端信息)
const gmail = google.gmail({ version: 'v1', auth });

async function createDraftViaAPI() {
    // 构造邮件内容,需转换为base64编码(适配API要求)
    const emailContent = [
        'From: your-email@gmail.com',
        'To: recipient@example.com',
        'Subject: API创建的草稿',
        '',
        '这是通过Gmail API生成的草稿内容'
    ].join('\n');

    const encodedEmail = Buffer.from(emailContent)
        .toString('base64')
        .replace(/\+/g, '-')
        .replace(/\//g, '_')
        .replace(/=+$/, '');

    try {
        const response = await gmail.users.drafts.create({
            userId: 'me',
            resource: {
                message: {
                    raw: encodedEmail
                }
            }
        });
        console.log("草稿创建成功,草稿ID:", response.data.id);
    } catch (err) {
        console.error("创建草稿失败:", err);
    }
}

createDraftViaAPI();

三、发送已存入的草稿

如果要发送草稿文件夹中已有的邮件,以Gmail API为例:

async function sendExistingDraft(draftId) {
    try {
        const response = await gmail.users.drafts.send({
            userId: 'me',
            resource: {
                id: draftId
            }
        });
        console.log("草稿已发送,邮件ID:", response.data.id);
    } catch (err) {
        console.error("发送草稿失败:", err);
    }
}

// 传入目标草稿的ID即可发送
sendExistingDraft('your-draft-id');

内容的提问来源于stack exchange,提问作者nsubhadipta

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.15 12:15:48