AirScript脚本进阶玩法:定制你的专属早安邮件(含天气/纪念日提醒)
AirScript脚本进阶玩法定制你的专属早安邮件含天气/纪念日提醒清晨的第一缕阳光透过窗帘手机震动提示音响起。你期待的不仅是新的一天还有那封专属于你的早安邮件——它不只是简单的问候更包含今日天气预警、重要纪念日倒计时甚至是你最爱的每日一句。这种高度个性化的体验完全可以通过AirScript脚本实现。本文将带你超越基础版打造真正懂你的智能邮件系统。1. 环境准备与基础架构优化在开始高级功能前我们需要建立一个更健壮的代码架构。基础版中直接将配置硬编码在脚本里的做法虽然简单但缺乏灵活性。进阶方案应采用模块化设计// 配置文件 config.js const config { smtp: { host: smtp.163.com, port: 465, username: your_email163.com, password: your_auth_code, secure: true }, dataSource: { type: airtable, // 可扩展为google sheets等 baseId: appxxxxxxxx, tableName: Subscribers }, features: { weather: true, anniversary: true, quote: false // 可按需开启 } }; module.exports config;提示将敏感信息存储在环境变量中更安全可通过process.env访问邮件发送模块应当独立封装便于复用// mailer.js const nodemailer require(nodemailer); const config require(./config); class MailService { constructor() { this.transporter nodemailer.createTransport({ host: config.smtp.host, port: config.smtp.port, secure: config.smtp.secure, auth: { user: config.smtp.username, pass: config.smtp.password } }); } async send(to, subject, html) { try { await this.transporter.sendMail({ from: Morning Bot ${config.smtp.username}, to, subject, html }); return true; } catch (error) { console.error(Mail send failed:, error); return false; } } } module.exports new MailService();2. 天气信息集成实战精准的天气信息能让收件人提前做好出行准备。我们通过和风天气API获取数据// weather.js const axios require(axios); class WeatherService { constructor(apiKey) { this.apiKey apiKey; this.baseUrl https://devapi.qweather.com/v7/weather/now; } async getWeather(locationId) { const params { location: locationId, key: this.apiKey }; try { const response await axios.get(this.baseUrl, { params }); return { temp: response.data.now.temp, text: response.data.now.text, wind: response.data.now.windDir, humidity: response.data.now.humidity }; } catch (error) { console.error(Weather API error:, error); return null; } } } module.exports WeatherService;在邮件模板中优雅展示天气信息!-- weather-template.html -- div classweather-card h3今日天气/h3 div classweather-info span classtemp{{temp}}°C/span span classcondition{{text}}/span /div ul classweather-details li风向: {{wind}}/li li湿度: {{humidity}}%/li /ul /div style .weather-card { border: 1px solid #e0e0e0; border-radius: 8px; padding: 15px; margin: 10px 0; background: #f9f9f9; } .weather-info { display: flex; align-items: center; gap: 15px; } .temp { font-size: 24px; font-weight: bold; } /style注意天气API通常有免费额度限制建议缓存结果避免频繁调用3. 智能纪念日提醒系统纪念日功能需要设计一个灵活的事件管理系统// anniversary.js const moment require(moment); class AnniversaryService { constructor(events []) { this.events events.map(event ({ ...event, date: moment(event.date), repeat: event.repeat || yearly })); } getUpcomingEvents() { const today moment().startOf(day); return this.events.filter(event { const eventDate this.adjustForRepeat(event, today); const diffDays eventDate.diff(today, days); return diffDays 0 diffDays 7; // 一周内的纪念日 }); } adjustForRepeat(event, referenceDate) { if (event.repeat yearly) { let eventDate event.date.clone() .year(referenceDate.year()); if (eventDate.isBefore(referenceDate)) { eventDate event.date.clone() .year(referenceDate.year() 1); } return eventDate; } return event.date; } } // 示例事件数据 const sampleEvents [ { name: 相识纪念日, date: 2020-05-20, repeat: yearly }, { name: 生日, date: 1990-08-15, repeat: yearly } ]; module.exports new AnniversaryService(sampleEvents);在邮件中展示纪念日信息时可以采用倒计时方式function generateAnniversaryHTML(events) { if (!events.length) return ; let html div classanniversary-section h3即将到来的纪念日/h3 ul; events.forEach(event { const daysLeft event.date.diff(moment(), days); html li strong${event.name}/strong: 还有${daysLeft}天 (${event.date.format(MM月DD日)}) /li; }); html /ul/div; return html; }4. 高级个性化功能扩展基础功能实现后可以进一步增加这些提升体验的功能4.1 动态内容推荐系统根据用户行为和偏好推荐内容// recommendation.js const userPreferences { user1example.com: { quoteCategories: [motivational, humor], newsTopics: [technology, science] } }; class RecommendationEngine { static getDailyQuote(email) { const prefs userPreferences[email]?.quoteCategories || [general]; const quotes { motivational: [ 行动是治愈恐惧的良药。, 成功不是将来才有的而是从决定去做的那一刻起持续累积而成。 ], humor: [ 早起的鸟儿有虫吃早起的虫儿被鸟吃。, 程序员最讨厌的两件事写文档和别人的代码没有文档。 ] }; const availableQuotes prefs.flatMap(cat quotes[cat] || []); if (availableQuotes.length 0) { availableQuotes.push(今天又是美好的一天); } return availableQuotes[Math.floor(Math.random() * availableQuotes.length)]; } }4.2 邮件模板引擎使用模板引擎实现更复杂的邮件布局// template-engine.js const handlebars require(handlebars); const mainTemplate handlebars.compile( !DOCTYPE html html head meta charsetUTF-8 title{{subject}}/title style body { font-family: Helvetica Neue, Arial, sans-serif; line-height: 1.6; } .container { max-width: 600px; margin: 0 auto; padding: 20px; } .header { background-color: #f8f9fa; padding: 15px; border-radius: 5px; } .section { margin: 20px 0; padding: 15px; background: white; border-radius: 5px; box-shadow: 0 2px 4px rgba(0,0,0,0.1); } /style /head body div classcontainer div classheader h1{{greeting}}/h1 p今天是{{date}}/p /div {{#if weather}} div classsection {{{weather}}} /div {{/if}} {{#if anniversaries}} div classsection {{{anniversaries}}} /div {{/if}} {{#if quote}} div classsection quote blockquote{{quote}}/blockquote /div {{/if}} /div /body /html ); module.exports { mainTemplate };4.3 用户行为分析记录邮件打开情况以优化发送策略// analytics.js const fs require(fs); const path require(path); class EmailAnalytics { constructor() { this.logFile path.join(__dirname, email_logs.json); this.loadData(); } loadData() { try { this.data JSON.parse(fs.readFileSync(this.logFile)); } catch { this.data {}; } } saveData() { fs.writeFileSync(this.logFile, JSON.stringify(this.data, null, 2)); } recordOpen(email, date new Date()) { if (!this.data[email]) { this.data[email] []; } this.data[email].push(date.toISOString()); this.saveData(); } getOpenRate(email) { const records this.data[email] || []; return records.length; } } module.exports new EmailAnalytics();5. 系统集成与定时任务将所有模块整合到主流程中// main.js const config require(./config); const MailService require(./mailer); const WeatherService require(./weather); const anniversaryService require(./anniversary); const { mainTemplate } require(./template-engine); const RecommendationEngine require(./recommendation); const weatherService new WeatherService(config.weatherApiKey); const mailService new MailService(); async function sendMorningEmail(user) { // 获取天气数据 const weather config.features.weather ? await weatherService.getWeather(user.locationId) : null; // 获取纪念日信息 const anniversaries config.features.anniversary ? anniversaryService.getUpcomingEvents() : []; // 生成邮件内容 const emailData { greeting: 早安${user.name}, date: new Date().toLocaleDateString(zh-CN, { year: numeric, month: long, day: numeric, weekday: long }), weather: weather ? generateWeatherHTML(weather) : null, anniversaries: anniversaries.length ? generateAnniversaryHTML(anniversaries) : null, quote: config.features.quote ? RecommendationEngine.getDailyQuote(user.email) : null }; // 渲染邮件模板 const html mainTemplate(emailData); // 发送邮件 await mailService.send( user.email, 你的专属早安简报 - ${emailData.date}, html ); }设置定时任务的最佳实践# 使用crontab设置每天早晨7点执行 0 7 * * * /usr/bin/node /path/to/your/script/main.js对于更复杂的调度需求可以考虑以下方案方案优点缺点系统cron简单可靠修改需要服务器权限AirScript内置定时无需额外配置功能有限第三方调度服务功能强大可能有额外成本6. 错误处理与监控健壮的错误处理系统必不可少// error-handler.js const fs require(fs); const path require(path); class ErrorHandler { constructor() { this.logFile path.join(__dirname, error_logs.log); } log(error, context {}) { const timestamp new Date().toISOString(); const message [${timestamp}] ERROR: ${error.message}\n Context: ${JSON.stringify(context)}\n Stack: ${error.stack}\n\n; fs.appendFileSync(this.logFile, message, utf8); } notifyAdmin(error) { // 实现邮件或短信通知管理员的逻辑 } } module.exports new ErrorHandler();在关键位置添加错误处理async function main() { try { const users await getUserList(); for (const user of users) { try { await sendMorningEmail(user); } catch (error) { errorHandler.log(error, { userId: user.id }); } } } catch (error) { errorHandler.log(error); errorHandler.notifyAdmin(error); } }监控系统健康状态的简单实现// health-check.js const os require(os); const disk require(diskusage); class HealthMonitor { static async check() { return { timestamp: new Date(), memory: { free: os.freemem(), total: os.totalmem(), usage: (1 - os.freemem() / os.totalmem()) * 100 }, disk: await this.checkDiskUsage(), cpu: os.loadavg() }; } static async checkDiskUsage() { try { const { free, total } await disk.check(/); return { free, total, usage: (1 - free / total) * 100 }; } catch (error) { return { error: error.message }; } } } // 定时运行健康检查 setInterval(async () { const health await HealthMonitor.check(); if (health.memory.usage 90 || health.disk.usage 90) { errorHandler.log(new Error(System resource running low), { health }); } }, 3600000); // 每小时检查一次
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.coloradmin.cn/o/2438404.html
如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!