-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathemail-report.js
More file actions
449 lines (396 loc) · 16.9 KB
/
Copy pathemail-report.js
File metadata and controls
449 lines (396 loc) · 16.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
'use strict';
/**
* email-report.js — 周报邮件发送模块
*
* 将 Markdown 格式的周报转换为 HTML 邮件,发送给领导层。
*
* 所需环境变量:
* SMTP_HOST — SMTP 服务器地址(如 smtp.exmail.qq.com)
* SMTP_PORT — SMTP 端口(默认 465)
* SMTP_USER — 发件人邮箱
* SMTP_PASS — 邮箱密码或授权码
* WEEKLY_EMAIL_TO — 收件人列表,逗号分隔(如 boss@company.com,cto@company.com)
* 未配置时回退到 EMAIL_TO
*/
const nodemailer = require('nodemailer');
// ── Markdown → HTML 转换(内联实现,无额外依赖)────────────────────────────────
function markdownToHtml(md) {
const lines = md.split('\n');
const htmlLines = [];
let inBlockquote = false;
for (let i = 0; i < lines.length; i++) {
let line = lines[i];
// 水平分割线
if (/^---+$/.test(line.trim())) {
if (inBlockquote) { htmlLines.push('</blockquote>'); inBlockquote = false; }
htmlLines.push('<hr style="border:none;border-top:1px solid #e0e0e0;margin:16px 0;">');
continue;
}
// 引用块 > 开头
if (line.startsWith('> ')) {
if (!inBlockquote) {
htmlLines.push('<blockquote style="margin:4px 0 4px 8px;padding:6px 12px;border-left:3px solid #00A7E1;background:#f0f9ff;color:#555;font-size:13px;">');
inBlockquote = true;
}
line = inlineFormat(line.slice(2));
htmlLines.push(`<div>${line}</div>`);
continue;
} else if (inBlockquote) {
htmlLines.push('</blockquote>');
inBlockquote = false;
}
// 空行
if (line.trim() === '') {
htmlLines.push('<div style="height:8px;"></div>');
continue;
}
// 行内格式处理
line = inlineFormat(line);
htmlLines.push(`<div style="margin:3px 0;line-height:1.7;">${line}</div>`);
}
if (inBlockquote) htmlLines.push('</blockquote>');
return htmlLines.join('\n');
}
function inlineFormat(text) {
// **粗体**
text = text.replace(/\*\*(.+?)\*\*/g, '<strong>$1</strong>');
// `代码`
text = text.replace(/`([^`]+)`/g, '<code style="background:#f4f4f4;padding:1px 4px;border-radius:3px;font-size:12px;color:#c7254e;">$1</code>');
// [链接](url)
text = text.replace(/\[([^\]]+)\]\(([^)]+)\)/g, '<a href="$2" style="color:#00A7E1;text-decoration:none;">$1</a>');
// • 转义为可见符号
text = text.replace(/^(•\s*)/, '<span style="color:#00A7E1;">•</span> ');
return text;
}
// ── 生成完整 HTML 邮件 ────────────────────────────────────────────────────────
function buildEmailHtml(reportContent, dateRange) {
const body = markdownToHtml(reportContent);
return `<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width,initial-scale=1.0">
<title>Web3Watch HK 行业周报</title>
</head>
<body style="margin:0;padding:0;background:#f5f5f5;font-family:-apple-system,BlinkMacSystemFont,'Segoe UI','PingFang SC','Microsoft YaHei',sans-serif;">
<table width="100%" cellpadding="0" cellspacing="0" style="background:#f5f5f5;padding:24px 0;">
<tr><td align="center">
<table width="680" cellpadding="0" cellspacing="0" style="background:#ffffff;border-radius:8px;overflow:hidden;box-shadow:0 1px 4px rgba(0,0,0,0.08);">
<!-- Header -->
<tr>
<td style="background:#00A7E1;padding:24px 32px;">
<div style="color:#ffffff;font-size:20px;font-weight:700;letter-spacing:0.5px;">
Web3Watch HK 行业周报
</div>
<div style="color:rgba(255,255,255,0.8);font-size:13px;margin-top:6px;">
${dateRange} · 自动生成
</div>
</td>
</tr>
<!-- Body -->
<tr>
<td style="padding:28px 32px;color:#333;font-size:14px;line-height:1.8;">
${body}
</td>
</tr>
<!-- Footer -->
<tr>
<td style="background:#fafafa;border-top:1px solid #eee;padding:16px 32px;">
<div style="color:#999;font-size:12px;">
本邮件由 Web3Watch HK 自动发送 · 每周五 18:00 · 如需调整请联系 ZHAO
</div>
</td>
</tr>
</table>
</td></tr>
</table>
</body>
</html>`;
}
// ── 主入口 ────────────────────────────────────────────────────────────────────
/**
* 发送周报邮件给领导层
* @param {string} reportContent - 周报 Markdown 内容
* @param {string} startDate - 周报起始日期(如 "03/17")
* @param {string} endDate - 周报结束日期(如 "03/21")
*/
async function sendWeeklyReportEmail(reportContent, startDate, endDate) {
const smtpHost = process.env.SMTP_HOST;
const smtpUser = process.env.SMTP_USER;
const smtpPass = process.env.SMTP_PASS;
const smtpPort = parseInt(process.env.SMTP_PORT || '465', 10);
const recipients = (process.env.WEEKLY_EMAIL_TO || process.env.EMAIL_TO || '').trim();
const cc = (process.env.WEEKLY_EMAIL_CC || '').trim() || undefined;
if (!smtpHost || !smtpUser || !smtpPass) {
console.log('[Email] SMTP not configured, skipping weekly email.');
return false;
}
if (!recipients) {
console.warn('[Email] No recipients configured (WEEKLY_EMAIL_TO / EMAIL_TO), skipping.');
return false;
}
const dateRange = `${startDate} ~ ${endDate}`;
const subject = `Web3Watch HK 行业周报 | ${dateRange}`;
const html = buildEmailHtml(reportContent, dateRange);
const transporter = nodemailer.createTransport({
host: smtpHost,
port: smtpPort,
secure: smtpPort === 465,
auth: { user: smtpUser, pass: smtpPass },
});
try {
const info = await transporter.sendMail({
from: `"Web3Watch HK" <${smtpUser}>`,
to: recipients,
cc,
subject,
text: reportContent,
html,
});
console.log(`[Email] Weekly report sent → ${recipients}${cc ? ` CC: ${cc}` : ''} (messageId: ${info.messageId})`);
return true;
} catch (err) {
console.error('[Email] Failed to send weekly report:', err.message);
return false;
}
}
// ── 人工周报邮件(自定义标题 + 结论 + 图片)─────────────────────────────────────
/**
* 构建人工周报 HTML 邮件正文
* @param {string} summary - 本周结论/正文文字(支持空行分段、**粗体**标记)
* @param {string[]} imagePaths - 图片路径数组(按顺序内嵌),可为空数组
* @param {string} dateRange - 周期字符串,如 "0327 ~ 0409",用于落款日期
* @param {string} [logoSrc] - Logo 的 src(CID 引用如 "cid:logo",或 base64 data URI,可选)
*/
function buildManualEmailHtml(summary, imagePaths, dateRange, logoSrc) {
const paragraphs = summary.split('\n');
const summaryHtml = paragraphs.map(line => {
const trimmed = line.trim();
if (!trimmed) return '<div style="height:12px;"></div>';
const formatted = trimmed.replace(/\*\*(.+?)\*\*/g, '<strong style="color:#0d1b2a;">$1</strong>');
return `<div style="margin:5px 0;line-height:1.95;color:#374151;font-size:14px;">${formatted}</div>`;
}).join('\n');
const imageSection = imagePaths.length > 0
? imagePaths.map((_, i) =>
`<tr><td style="padding:0 36px ${i === imagePaths.length - 1 ? '32' : '16'}px;font-size:0;line-height:0;">
<img src="cid:weekly_report_image_${i}" alt="行业动态图表 ${i + 1}"
style="width:100%;max-width:588px;display:block;border-radius:3px;border:1px solid #e5e7eb;">
</td></tr>`
).join('\n')
: '';
const today = new Date().toLocaleDateString('zh-CN', {
timeZone: 'Asia/Shanghai', year: 'numeric', month: 'long', day: 'numeric',
});
const logoHtml = logoSrc
? `<img src="${logoSrc}" alt="HighBlock" width="36" height="36" style="display:inline-block;vertical-align:middle;border-radius:4px;margin-right:12px;">`
: '';
return `<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width,initial-scale=1.0">
</head>
<body style="margin:0;padding:0;background:#eef0f3;font-family:-apple-system,BlinkMacSystemFont,'Helvetica Neue','PingFang SC','Microsoft YaHei',sans-serif;">
<table width="100%" cellpadding="0" cellspacing="0" style="background:#eef0f3;padding:32px 0;">
<tr><td align="center">
<table width="660" cellpadding="0" cellspacing="0" style="background:#ffffff;">
<!-- ── Header ── -->
<tr>
<td style="background:#1e3269;padding:36px 40px 28px;">
<table width="100%" cellpadding="0" cellspacing="0">
<tr>
<td style="vertical-align:middle;">
${logoHtml}<span style="color:#c9a55a;font-size:11px;letter-spacing:0.18em;text-transform:uppercase;font-weight:700;vertical-align:middle;">HIGHBLOCK</span>
</td>
<td align="right" style="color:rgba(255,255,255,0.4);font-size:10px;letter-spacing:0.08em;">
INTERNAL REFERENCE · ${dateRange}
</td>
</tr>
</table>
<div style="color:#ffffff;font-size:23px;font-weight:700;margin-top:16px;line-height:1.35;letter-spacing:0.01em;">
行业研究周报
</div>
<div style="background:#c9a55a;height:3px;width:48px;margin-top:18px;border-radius:2px;"></div>
</td>
</tr>
<!-- ── Meta bar ── -->
<tr>
<td style="background:#f8f7f4;border-bottom:2px solid #1e3269;padding:10px 40px;">
<table width="100%" cellpadding="0" cellspacing="0">
<tr>
<td style="color:#6b7280;font-size:11px;letter-spacing:0.06em;">
产品部行研组 · ${dateRange}
</td>
<td align="right" style="color:#9ca3af;font-size:11px;">
${today}
</td>
</tr>
</table>
</td>
</tr>
<!-- ── Greeting ── -->
<tr>
<td style="padding:32px 40px 0;color:#374151;font-size:14px;line-height:1.9;">
<div style="margin-bottom:8px;">尊敬的各位领导,</div>
<div style="color:#6b7280;font-size:13px;">以下为本周香港 Web3 行业核心动态,供参阅。</div>
</td>
</tr>
<!-- ── Divider ── -->
<tr><td style="padding:20px 40px 0;">
<div style="border-top:1px solid #e5e7eb;"></div>
</td></tr>
<!-- ── Summary ── -->
<tr>
<td style="padding:24px 40px;">
<div style="font-size:10px;letter-spacing:0.15em;text-transform:uppercase;color:#9ca3af;font-weight:600;margin-bottom:16px;">
本周研判
</div>
<div style="border-left:3px solid #c9a55a;padding:16px 20px;background:#f9fafb;border-radius:0 4px 4px 0;">
${summaryHtml}
</div>
</td>
</tr>
<!-- ── Images ── -->
${imagePaths.length > 0 ? `
<tr><td style="padding:0 40px 16px;">
<div style="font-size:10px;letter-spacing:0.15em;text-transform:uppercase;color:#9ca3af;font-weight:600;margin-bottom:16px;">
行业动态图表
</div>
</td></tr>` : ''}
${imageSection}
<!-- ── Doc link ── -->
<tr>
<td style="padding:0 40px 32px;">
<table width="100%" cellpadding="0" cellspacing="0" style="background:#1e3269;border-radius:4px;">
<tr>
<td style="padding:14px 20px;color:rgba(255,255,255,0.65);font-size:12px;letter-spacing:0.05em;">
完整周报文档
</td>
<td align="right" style="padding:14px 20px;">
<a href="https://doc.weixin.qq.com/doc/w3_ARMAsQbTANACNGOlT0neMRK64hCk5?scode=ANEAUgd7AFo0Aba4VCARMAsQbTANA"
style="color:#c9a55a;text-decoration:none;font-size:12px;font-weight:700;letter-spacing:0.05em;">
点击查看 →
</a>
</td>
</tr>
</table>
</td>
</tr>
<!-- ── Divider ── -->
<tr><td style="padding:0 40px;">
<div style="border-top:1px solid #e5e7eb;"></div>
</td></tr>
<!-- ── Signature ── -->
<tr>
<td style="padding:24px 40px 32px;">
<table width="100%" cellpadding="0" cellspacing="0">
<tr>
<td style="color:#6b7280;font-size:13px;line-height:1.8;">
如有疑问,欢迎随时沟通。
</td>
<td align="right">
<div style="border-left:3px solid #c9a55a;padding:8px 0 8px 16px;text-align:left;display:inline-block;">
<div style="font-size:13px;font-weight:700;color:#1e3269;letter-spacing:0.02em;">产品部行研组</div>
<div style="font-size:11px;color:#9ca3af;margin-top:3px;">HighBlock Research</div>
</div>
</td>
</tr>
</table>
</td>
</tr>
<!-- ── Footer ── -->
<tr>
<td style="background:#1e3269;padding:14px 40px;">
<table width="100%" cellpadding="0" cellspacing="0">
<tr>
<td style="color:rgba(255,255,255,0.3);font-size:10px;letter-spacing:0.08em;">
HIGHBLOCK · 产品部行研组
</td>
<td align="right" style="color:rgba(255,255,255,0.2);font-size:10px;">
Powered by Web3Watch HK
</td>
</tr>
</table>
</td>
</tr>
</table>
</td></tr>
</table>
</body>
</html>`;
}
/**
* 发送人工周报邮件(自定义标题 + 结论 + 多图内嵌,无 PDF 附件)
* @param {string} subject - 邮件标题
* @param {string} summary - 本周结论文字
* @param {string} dateRange - 周期字符串,如 "0327 ~ 0409"
* @param {string|string[]} imagePaths - 图片路径(单张兼容旧调用,或数组)
*/
async function sendManualWeeklyEmail(subject, summary, dateRange, imagePaths) {
const fs = require('fs');
const path = require('path');
const smtpHost = process.env.SMTP_HOST;
const smtpUser = process.env.SMTP_USER;
const smtpPass = process.env.SMTP_PASS;
const smtpPort = parseInt(process.env.SMTP_PORT || '465', 10);
const recipients = (process.env.WEEKLY_EMAIL_TO || process.env.EMAIL_TO || '').trim();
const cc = (process.env.WEEKLY_EMAIL_CC || '').trim() || undefined;
if (!smtpHost || !smtpUser || !smtpPass) {
console.log('[Email] SMTP not configured, skipping.');
return false;
}
if (!recipients) {
console.warn('[Email] No recipients configured, skipping.');
return false;
}
// 兼容旧的单路径调用
const paths = Array.isArray(imagePaths)
? imagePaths.filter(p => p && fs.existsSync(p))
: (imagePaths && fs.existsSync(imagePaths) ? [imagePaths] : []);
if (paths.length === 0) console.warn('[Email] No images found, sending without inline images.');
// Logo(assets/logo.jpg),存在则以 CID 内嵌进 header
const logoPath = path.join(__dirname, 'assets', 'logo.jpg');
const hasLogo = fs.existsSync(logoPath);
if (!hasLogo) console.warn('[Email] assets/logo.jpg not found, header will render without logo.');
const html = buildManualEmailHtml(
summary,
paths,
dateRange,
hasLogo ? 'cid:highblock_logo' : null,
);
const attachments = paths.map((p, i) => ({
filename: `weekly-report-${i + 1}${path.extname(p)}`,
path: p,
cid: `weekly_report_image_${i}`,
}));
if (hasLogo) {
attachments.push({
filename: 'logo.jpg',
path: logoPath,
cid: 'highblock_logo',
});
}
const transporter = nodemailer.createTransport({
host: smtpHost,
port: smtpPort,
secure: smtpPort === 465,
auth: { user: smtpUser, pass: smtpPass },
});
try {
const info = await transporter.sendMail({
from: `"Web3Watch HK" <${smtpUser}>`,
to: recipients,
cc,
subject,
text: summary,
html,
attachments,
});
console.log(`[Email] Manual weekly email sent → ${recipients}${cc ? ` CC: ${cc}` : ''} (${paths.length} image(s), messageId: ${info.messageId})`);
return true;
} catch (err) {
console.error('[Email] Failed to send manual weekly email:', err.message);
return false;
}
}
module.exports = { sendWeeklyReportEmail, sendManualWeeklyEmail, buildManualEmailHtml };