send.js

5.3 KB v1.0
// SMTP 发信,并在本地「已发送」中留存副本
import fs from 'node:fs';
import nodemailer from 'nodemailer';
import { db } from '../db.js';
import { decrypt } from '../crypto.js';
import {
  saveAttachmentBuffer,
  safeFilename,
  resolveStoragePath,
  removeAttachmentDir,
} from './attachments.js';

export function buildTransport(account, password) {
  return nodemailer.createTransport({
    host: account.smtp_host,
    port: account.smtp_port,
    secure: Boolean(account.smtp_secure),
    auth: { user: account.username, pass: password },
    connectionTimeout: 20000,
    greetingTimeout: 15000,
    socketTimeout: 60000,
  });
}

export async function testSmtp(account, password) {
  const transport = buildTransport(account, password);
  try {
    await transport.verify();
  } finally {
    transport.close();
  }
}

function textToHtml(text) {
  return String(text || '')
    .replace(/&/g, '&')
    .replace(/</g, '&lt;')
    .replace(/>/g, '&gt;')
    .replace(/\n/g, '<br>');
}

/** 读取草稿附件(用于草稿发送或保存时保留) */
export function loadDraftAttachments(userId, draftId, keepIds) {
  const rows = db
    .prepare(
      `SELECT a.* FROM attachments a
       JOIN messages m ON m.id = a.message_id
       WHERE m.id = ? AND m.user_id = ? AND m.folder = 'drafts'`
    )
    .all(draftId, userId);
  return rows
    .filter((row) => !keepIds || keepIds.map(Number).includes(row.id))
    .map((row) => {
      const abs = resolveStoragePath(row.storage_path);
      const buffer = abs && fs.existsSync(abs) ? fs.readFileSync(abs) : null;
      return { ...row, buffer };
    })
    .filter((row) => row.buffer);
}

function normalizeRecipients(value) {
  if (Array.isArray(value)) return value.map((v) => String(v).trim()).filter(Boolean).join(', ');
  return String(value || '')
    .split(/[,;]/)
    .map((v) => v.trim())
    .filter(Boolean)
    .join(', ');
}

/**
 * 发送邮件
 * @param {number} userId
 * @param {object} payload { accountId, to, cc, bcc, subject, text, html, attachments, draftId, keepAttachmentIds }
 */
export async function sendMail(userId, payload) {
  const account = db
    .prepare('SELECT * FROM accounts WHERE id = ? AND user_id = ?')
    .get(Number(payload.accountId), userId);
  if (!account) throw new Error('请选择有效的发件账号');
  const password = decrypt(account.password_enc);
  if (!password) throw new Error('邮箱密码解密失败,请编辑账号重新填写密码');

  const to = normalizeRecipients(payload.to);
  const cc = normalizeRecipients(payload.cc);
  const bcc = normalizeRecipients(payload.bcc);
  if (!to) throw new Error('请填写收件人');

  const text = String(payload.text || '');
  const html = payload.html ? String(payload.html) : textToHtml(text);
  const subject = String(payload.subject || '');

  // 新添加的附件(来自浏览器 base64)
  const newAttachments = (payload.attachments || []).map((att) => {
    const buffer = Buffer.from(String(att.data || ''), 'base64');
    return { filename: safeFilename(att.filename), mime: att.mime, buffer };
  });

  // 草稿中已保存的附件
  const draftAttachments =
    payload.draftId && Array.isArray(payload.keepAttachmentIds)
      ? loadDraftAttachments(userId, Number(payload.draftId), payload.keepAttachmentIds)
      : payload.draftId
        ? loadDraftAttachments(userId, Number(payload.draftId))
        : [];

  const allAttachments = [
    ...newAttachments,
    ...draftAttachments.map((a) => ({ filename: a.filename, mime: a.mime, buffer: a.buffer })),
  ];

  const transport = buildTransport(account, password);
  let info;
  try {
    info = await transport.sendMail({
      from: { name: account.name || account.email, address: account.email },
      to,
      cc: cc || undefined,
      bcc: bcc || undefined,
      subject,
      text,
      html,
      attachments: allAttachments.map((a) => ({
        filename: a.filename,
        content: a.buffer,
        contentType: a.mime || undefined,
      })),
    });
  } finally {
    transport.close();
  }

  // 本地保存已发送副本
  const result = db
    .prepare(
      `INSERT INTO messages
        (user_id, account_id, folder, prev_folder, uid, message_id, subject, from_name, from_addr,
         to_addrs, cc_addrs, bcc_addrs, date, snippet, body_text, body_html, seen, size, has_attachments, created_at)
       VALUES (?, ?, 'sent', NULL, NULL, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 1, 0, ?, ?)`
    )
    .run(
      userId,
      account.id,
      info.messageId || '',
      subject || '(无主题)',
      account.name || '',
      account.email,
      to,
      cc,
      bcc,
      Date.now(),
      text.replace(/\s+/g, ' ').trim().slice(0, 200),
      text,
      html,
      allAttachments.length ? 1 : 0,
      Date.now()
    );

  const sentId = Number(result.lastInsertRowid);
  for (const att of allAttachments) {
    saveAttachmentBuffer(userId, sentId, att.filename, att.mime, att.buffer);
  }

  // 发送成功后删除草稿
  if (payload.draftId) {
    const draft = db
      .prepare(`SELECT id FROM messages WHERE id = ? AND user_id = ? AND folder = 'drafts'`)
      .get(Number(payload.draftId), userId);
    if (draft) {
      removeAttachmentDir(userId, draft.id);
      db.prepare('DELETE FROM messages WHERE id = ?').run(draft.id);
    }
  }

  return { id: sentId, messageId: info.messageId };
}