@daidaitw/notification
v1.0.1
Published
可扩展的通知模块,支持邮箱、短信等多种通知方式
Maintainers
Readme
📧 Notification Module
一个灵活可扩展的 Node.js 通知模块,支持多种通知方式。目前已实现邮箱通知,后续将支持短信、微信、Webhook 等更多通知渠道。
使用原生 JavaScript + JSDoc 实现,提供完整的类型提示支持。
✨ 特性
- 🎯 可扩展架构 - 基于策略模式,轻松添加新的通知方式
- 📧 邮箱通知 - 基于 nodemailer 的完整邮件发送功能
- 💪 JSDoc 类型支持 - 完整的 JSDoc 注释,IDE 智能提示
- 🔄 批量发送 - 支持批量发送通知
- 📎 附件支持 - 支持发送邮件附件
- 🎨 HTML 邮件 - 支持富文本 HTML 格式邮件
- 🚀 零编译 - 纯 JavaScript 实现,无需构建步骤
📦 安装
npm install @daidaitw/notification
# 或
yarn add @daidaitw/notification🚀 快速开始
基础用法
const { createEmailNotifier } = require('@daidaitw/notification');
async function sendEmail() {
// 创建邮件通知实例
const emailNotifier = await createEmailNotifier({
host: 'smtp.example.com',
port: 587,
secure: false,
auth: {
user: '[email protected]',
pass: 'your-password',
},
});
// 发送邮件
const result = await emailNotifier.send({
to: '[email protected]',
subject: '测试邮件',
content: '这是一封测试邮件',
});
console.log(result);
// 关闭连接
await emailNotifier.close();
}
sendEmail();使用 JSDoc 获得类型提示
/**
* @typedef {import('@daidaitw/notification').EmailConfig} EmailConfig
* @typedef {import('@daidaitw/notification').EmailMessage} EmailMessage
*/
const { createEmailNotifier } = require('@daidaitw/notification');
/**
* 发送欢迎邮件
* @param {string} recipientEmail - 收件人邮箱
* @returns {Promise<void>}
*/
async function sendWelcomeEmail(recipientEmail) {
/** @type {EmailConfig} */
const config = {
host: 'smtp.example.com',
port: 587,
auth: {
user: '[email protected]',
pass: 'your-password',
},
};
const emailNotifier = await createEmailNotifier(config);
/** @type {EmailMessage} */
const message = {
to: recipientEmail,
subject: '欢迎加入',
content: '感谢您的注册!',
};
const result = await emailNotifier.send(message);
await emailNotifier.close();
}📖 使用示例
发送 HTML 邮件
const { EmailProvider } = require('@daidaitw/notification');
const emailProvider = new EmailProvider({
host: 'smtp.example.com',
port: 587,
auth: {
user: '[email protected]',
pass: 'your-password',
},
});
await emailProvider.initialize();
await emailProvider.sendHtml({
to: '[email protected]',
subject: '欢迎使用',
content: '纯文本备用内容',
html: `
<html>
<body>
<h1>欢迎!</h1>
<p>感谢您使用我们的服务。</p>
</body>
</html>
`,
});
await emailProvider.close();发送带附件的邮件
await emailNotifier.sendWithAttachments({
to: '[email protected]',
subject: '带附件的邮件',
content: '请查收附件',
attachments: [
{
filename: 'document.pdf',
path: './files/document.pdf',
},
{
filename: 'data.json',
content: JSON.stringify({ message: 'Hello' }),
},
],
});批量发送邮件
const messages = [
{
to: '[email protected]',
subject: '通知 1',
content: '内容 1',
},
{
to: '[email protected]',
subject: '通知 2',
content: '内容 2',
},
];
const results = await emailNotifier.sendBatch(messages);发送给多个收件人
await emailNotifier.send({
to: ['[email protected]', '[email protected]'],
cc: '[email protected]',
bcc: '[email protected]',
subject: '团队通知',
content: '这是发给团队的通知',
});🔧 API 文档
EmailProvider
构造函数
/**
* @param {EmailConfig} config - 邮箱配置
*/
new EmailProvider(config)方法
initialize(): Promise<void>- 初始化邮件服务send(message: EmailMessage): Promise<NotificationResult>- 发送邮件sendHtml(message: EmailMessage): Promise<NotificationResult>- 发送 HTML 邮件sendWithAttachments(message: EmailMessage): Promise<NotificationResult>- 发送带附件的邮件sendBatch(messages: EmailMessage[]): Promise<NotificationResult[]>- 批量发送邮件close(): Promise<void>- 关闭邮件传输器
JSDoc 类型定义
EmailConfig
/**
* @typedef {Object} EmailConfig
* @property {string} host - SMTP 服务器地址
* @property {number} port - SMTP 端口
* @property {boolean} [secure] - 是否使用 SSL/TLS
* @property {EmailAuth} auth - 认证信息
* @property {string} [from] - 默认发件人
*/
/**
* @typedef {Object} EmailAuth
* @property {string} user - 邮箱账号
* @property {string} pass - 邮箱密码或授权码
*/EmailMessage
/**
* @typedef {Object} EmailMessage
* @property {string|string[]} to - 收件人
* @property {string} subject - 主题
* @property {string} content - 纯文本内容
* @property {string} [html] - HTML 内容
* @property {string|string[]} [cc] - 抄送
* @property {string|string[]} [bcc] - 密送
* @property {EmailAttachment[]} [attachments] - 附件列表
*/
/**
* @typedef {Object} EmailAttachment
* @property {string} filename - 文件名
* @property {string} [path] - 文件路径
* @property {string|Buffer} [content] - 文件内容
*/NotificationResult
/**
* @typedef {Object} NotificationResult
* @property {boolean} success - 是否成功
* @property {string} message - 结果消息
* @property {NotificationData} [data] - 返回数据
* @property {Error} [error] - 错误信息
*/
/**
* @typedef {Object} NotificationData
* @property {string} [messageId] - 消息ID
* @property {string} [response] - 响应信息
* @property {string} [provider] - 提供者名称
*/🔮 未来规划
- [ ] 短信通知(SMS Provider)
- [ ] 微信通知(WeChat Provider)
- [ ] Webhook 通知
- [ ] 企业微信通知
- [ ] 钉钉通知
- [ ] Slack 通知
- [ ] 通知模板系统
- [ ] 重试机制
- [ ] 日志记录
🏗️ 扩展新的通知方式
如果你想添加新的通知方式,可以继承 NotificationProvider 基类:
const { NotificationProvider } = require('@daidaitw/notification');
/**
* @typedef {Object} SMSConfig
* @property {string} apiKey - API密钥
* @property {string} apiSecret - API密钥
*/
/**
* @typedef {Object} SMSMessage
* @property {string} phone - 手机号
* @property {string} content - 短信内容
*/
/**
* 短信通知提供者
* @extends {NotificationProvider<SMSConfig, SMSMessage>}
*/
class SMSProvider extends NotificationProvider {
/**
* @param {SMSConfig} config
*/
constructor(config) {
super(config);
}
/**
* @returns {Promise<void>}
*/
async initialize() {
// 初始化 SMS 服务
this.initialized = true;
}
/**
* @param {SMSMessage} message
* @returns {Promise<import('@daidaitw/notification').NotificationResult>}
*/
async send(message) {
// 实现短信发送逻辑
return {
success: true,
message: '短信发送成功',
};
}
/**
* @returns {boolean}
*/
validateConfig() {
return !!(this.config.apiKey && this.config.apiSecret);
}
/**
* @returns {string}
*/
getProviderName() {
return 'SMSProvider';
}
}📝 常见问题
1. 如何配置常见邮箱服务商?
Gmail
{
host: 'smtp.gmail.com',
port: 587,
secure: false,
auth: {
user: '[email protected]',
pass: 'your-app-password', // 使用应用专用密码
},
}QQ 邮箱
{
host: 'smtp.qq.com',
port: 587,
secure: false,
auth: {
user: '[email protected]',
pass: 'your-authorization-code', // 使用授权码
},
}163 邮箱
{
host: 'smtp.163.com',
port: 465,
secure: true,
auth: {
user: '[email protected]',
pass: 'your-authorization-code',
},
}2. 如何处理发送失败?
const result = await emailNotifier.send(message);
if (!result.success) {
console.error('发送失败:', result.message, result.error);
// 实现重试逻辑或错误处理
}3. 如何在 VSCode 中获得更好的类型提示?
在项目根目录创建 jsconfig.json:
{
"compilerOptions": {
"checkJs": true,
"module": "commonjs",
"target": "ES2020"
},
"include": ["src/**/*", "examples/**/*"]
}📄 许可证
MIT
🤝 贡献
欢迎提交 Issue 和 Pull Request!
📮 联系方式
如有问题或建议,请提交 Issue。
