更新记录

1.0.1(2025-06-27)

优化

1.0.0(2025-06-26)

初版


平台兼容性

云函数类插件通用教程

使用云函数类插件的前提是:使用HBuilderX 2.9+


邮件发送模块

uniCloud 邮件发送解决方案,支持多种邮件类型、批量发送、连接池管理和重试机制。

特性

  • 🚀 高性能: 使用连接池和批量发送优化性能
  • 🔄 自动重试: 内置重试机制,提高发送成功率
  • 📧 多种模板: 内置验证码、密码重置、通知等邮件模板
  • 🎨 美观界面: 精心设计的响应式HTML邮件模板
  • 📊 批量发送: 支持大量邮件的并发批量发送
  • 连接复用: 智能的传输器缓存和连接池管理
  • 🔒 安全验证: 邮件地址格式验证和SMTP连接验证
  • 📈 发送统计: 提供详细的发送结果和统计信息

安装

# 项目根目录下运行命令
cd ./uni_modules/x-mailer/uniCloud/cloudfunctions/common/x-mailer
npm install nodemailer

配置

首先需要配置SMTP服务器信息。在 x-config-center 中添加邮件配置:

// 文件路径 /uni_modules/x-config-center/uniCloud/cloudfunctions/common/x-config-center/index.js
module.exports = {
  mailer: {
    smtp: {
      host: 'smtp.example.com',
      port: 587,
      secure: false, // true for 465, false for other ports
      auth: {
        user: 'your-email@example.com',
        pass: 'your-password'
      }
    },
    from: {
      name: '系统通知',
      email: 'noreply@example.com'
    }
  }
};

基本使用

导入模块

const {
  sendEmail,
  sendVerificationCode,
  sendPasswordReset,
  sendNotification,
  sendBatchEmails
} = require('x-mailer');

发送基础邮件

// 发送简单邮件
const result = await sendEmail({
  to: 'user@example.com',
  subject: '测试邮件',
  text: '这是一封测试邮件',
  html: '<h1>这是一封测试邮件</h1>'
});

console.log(result);
// {
//   success: true,
//   messageId: '<message-id>',
//   response: '250 OK',
//   duration: '1234ms',
//   message: '邮件发送成功'
// }

发送给多个收件人

await sendEmail({
  to: ['user1@example.com', 'user2@example.com'],
  cc: 'manager@example.com',
  bcc: 'admin@example.com',
  subject: '群发邮件',
  html: '<p>这是一封群发邮件</p>'
});

发送带附件的邮件

await sendEmail({
  to: 'user@example.com',
  subject: '带附件的邮件',
  text: '请查看附件',
  attachments: [
    {
      filename: 'document.pdf',
      path: '/path/to/document.pdf'
    },
    {
      filename: 'image.jpg',
      content: Buffer.from('...') // 或者文件内容
    }
  ]
});

预设邮件模板

验证码邮件

// 发送验证码邮件
const result = await sendVerificationCode(
  'user@example.com',    // 收件人邮箱
  '123456',              // 验证码
  10,                    // 过期时间(分钟)
  {
    subject: '【自定义】邮箱验证码' // 可选:自定义主题
  }
);

密码重置邮件

// 发送密码重置邮件
const resetUrl = 'https://example.com/reset-password?token=abc123';
const result = await sendPasswordReset(
  'user@example.com',    // 收件人邮箱
  resetUrl,              // 重置链接
  24,                    // 过期时间(小时)
  {
    subject: '【自定义】密码重置' // 可选:自定义主题
  }
);

系统通知邮件

// 发送系统通知邮件
const result = await sendNotification(
  'user@example.com',           // 收件人邮箱
  '系统维护通知',               // 通知标题
  '系统将在今晚进行维护升级',   // 通知内容
  'warning',                    // 通知类型:info|warning|error|success
  {
    subject: '【系统维护】重要通知' // 可选:自定义主题
  }
);

发送给多个用户

// 群发通知
await sendNotification(
  ['user1@example.com', 'user2@example.com'],
  '重要通知',
  '这是一条重要的系统通知',
  'info'
);

批量发送

基础批量发送

const emailList = [
  {
    to: 'user1@example.com',
    subject: '个性化邮件1',
    html: '<h1>欢迎 用户1</h1>'
  },
  {
    to: 'user2@example.com',
    subject: '个性化邮件2',
    html: '<h1>欢迎 用户2</h1>'
  }
  // ... 更多邮件
];

const batchResult = await sendBatchEmails(emailList, {
  concurrent: 5,    // 并发数
  delay: 1000      // 批次间延迟(毫秒)
});

console.log(batchResult);
// {
//   total: 2,
//   success: 2,
//   failed: 0,
//   details: [...],
//   startTime: '2023-...',
//   endTime: '2023-...',
//   duration: '2345ms'
// }

高级批量发送配置

// 大量邮件发送优化配置
const result = await sendBatchEmails(emailList, {
  concurrent: 10,   // 提高并发数
  delay: 500,       // 减少延迟
  retry: 2          // 每封邮件的重试次数
});

// 检查发送结果
result.details.forEach(detail => {
  if (!detail.success) {
    console.error(`发送失败: ${detail.to}, 错误: ${detail.error}`);
  }
});

高级配置

自定义SMTP配置

// 使用自定义SMTP配置发送邮件
await sendEmail({
  to: 'user@example.com',
  subject: '使用自定义SMTP',
  text: '这封邮件使用自定义SMTP服务器发送',
  smtpConfig: {
    host: 'custom-smtp.example.com',
    port: 465,
    secure: true,
    auth: {
      user: 'custom@example.com',
      pass: 'custom-password'
    }
  }
});

邮件优先级和自定义头部

await sendEmail({
  to: 'urgent@example.com',
  subject: '紧急邮件',
  text: '这是一封紧急邮件',
  priority: 'high',           // 邮件优先级:high|normal|low
  headers: {
    'X-Custom-Header': 'custom-value',
    'X-Priority': '1'
  },
  replyTo: 'support@example.com'  // 回复地址
});

重试配置

// 自定义重试次数
const result = await sendEmail({
  to: 'user@example.com',
  subject: '重要邮件',
  text: '这封邮件会在失败时重试5次',
  retry: 5  // 重试次数
});

工具函数

邮件地址验证

const { validateEmail, validateEmailArray } = require('x-mailer');

// 验证单个邮件地址
const isValid = validateEmail('user@example.com');
console.log(isValid); // true

// 验证邮件地址数组
try {
  const emails = validateEmailArray(['valid@example.com', 'invalid-email']);
} catch (error) {
  console.error(error.message); // 无效的邮件地址: invalid-email
}

获取发送统计

const { getEmailStats } = require('x-mailer');

const stats = getEmailStats();
console.log(stats);
// {
//   transporterPoolSize: 2,
//   activeTransporters: 2
// }

清理连接池

const { clearTransporterPool } = require('x-mailer');

// 手动清理连接池
clearTransporterPool();

错误处理

基础错误处理

try {
  const result = await sendEmail({
    to: 'user@example.com',
    subject: '测试邮件',
    text: '测试内容'
  });

  if (result.success) {
    console.log('邮件发送成功:', result.messageId);
  } else {
    console.error('邮件发送失败:', result.error);
  }
} catch (error) {
  console.error('发送过程中出错:', error.message);
}

批量发送错误处理

const batchResult = await sendBatchEmails(emailList);

// 统计发送结果
console.log(`总计: ${batchResult.total}`);
console.log(`成功: ${batchResult.success}`);
console.log(`失败: ${batchResult.failed}`);

// 处理失败的邮件
const failedEmails = batchResult.details.filter(detail => !detail.success);
if (failedEmails.length > 0) {
  console.log('失败的邮件:', failedEmails);

  // 可以选择重新发送失败的邮件
  const retryList = failedEmails.map(failed => ({
    to: failed.to,
    subject: failed.subject,
    // ... 其他邮件内容
  }));

  // 重新发送
  await sendBatchEmails(retryList);
}

常见问题

Q: 如何提高大量邮件的发送速度?

A: 可以通过以下方式优化:

  • 增加并发数:concurrent: 20
  • 减少批次延迟:delay: 200
  • 使用连接池(已内置)
  • 优化SMTP服务器配置

Q: 邮件发送失败如何处理?

A: 模块内置了重试机制,同时返回详细的错误信息:

const result = await sendEmail(options);
if (!result.success) {
  console.log('失败原因:', result.error);
  console.log('重试次数:', result.attempts);
}

Q: 如何自定义邮件模板?

A: 创建自己的模板:

function customTemplate(data) {
  return `
    <div style="...">
      <h1>${data.title}</h1>
      <p>${data.content}</p>
    </div>
  `;
}

await sendEmail({
  to: 'user@example.com',
  subject: '自定义模板',
  html: customTemplate({ title: '标题', content: '内容' })
});

隐私、权限声明

1. 本插件需要申请的系统权限列表:

2. 本插件采集的数据、发送的服务器地址、以及数据用途说明:

插件不采集任何数据

3. 本插件是否包含广告,如包含需详细说明广告表达方式、展示频率:

暂无用户评论。

使用中有什么不明白的地方,就向插件作者提问吧~ 我要提问