Files
imgbed/lib/mail.mjs
T

152 lines
4.4 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
// 极简 SMTP 发信(STARTTLS/SSL + AUTH LOGIN),只用来发找回密码邮件。
// 配置来源(按优先级):
// 1. 环境变量 IMGBED_SMTP(JSON 字符串)
// 2. 环境变量 IMGBED_SMTP_FILE 指向的 JSON 文件
// 3. <data>/mail.json
// 4. /etc/gitea-mail-notify.json(复用服务器上已有的发信配置)
// 形如 { "smtpHost": "smtp.qq.com", "smtpPort": 587, "smtpSecure": "starttls",
// "smtpUser": "xx@qq.com", "smtpPass": "授权码", "mailFrom": "xx@qq.com", "fromName": "imgbed" }
import { connect as netConnect } from 'node:net'
import { connect as tlsConnect } from 'node:tls'
import { readFileSync } from 'node:fs'
import { join } from 'node:path'
export function loadMailConfig(dataDir) {
if (process.env.IMGBED_SMTP) {
try {
return JSON.parse(process.env.IMGBED_SMTP)
} catch {}
}
const files = [process.env.IMGBED_SMTP_FILE, join(dataDir, 'mail.json'), '/etc/gitea-mail-notify.json'].filter(Boolean)
for (const file of files) {
try {
const cfg = JSON.parse(readFileSync(file, 'utf8'))
if (cfg.smtpHost && cfg.smtpUser) return cfg
} catch {}
}
return null
}
const b64 = (str) => Buffer.from(String(str), 'utf8').toString('base64')
function encodeHeader(str) {
return /^[\x20-\x7e]*$/.test(str) ? str : `=?UTF-8?B?${b64(str)}?=`
}
function chunk76(b64text) {
return b64text.match(/.{1,76}/g)?.join('\r\n') || ''
}
class Smtp {
constructor(cfg) {
this.cfg = cfg
this.sock = null
this.buffer = ''
this.pending = null
}
listen() {
this.sock.setEncoding('utf8')
this.sock.on('data', (chunk) => {
this.buffer += chunk
if (!this.pending) return
const lines = this.buffer.split(/\r?\n/)
const last = lines.findLastIndex((l) => /^\d{3} /.test(l))
if (last < 0) return
const reply = lines.slice(0, last + 1).join('\n')
this.buffer = lines.slice(last + 1).join('\n')
const p = this.pending
this.pending = null
if (/^[45]/.test(lines[last])) p.reject(new Error(reply))
else p.resolve(reply)
})
this.sock.on('error', (err) => {
const p = this.pending
this.pending = null
p?.reject(err)
})
}
expect() {
return new Promise((resolve, reject) => {
this.pending = { resolve, reject }
const timer = setTimeout(() => {
if (this.pending) {
this.pending = null
reject(new Error('SMTP 等待回复超时'))
}
}, 20000)
timer.unref()
})
}
cmd(line) {
const p = this.expect()
this.sock.write(`${line}\r\n`)
return p
}
async open() {
const { smtpHost, smtpPort = 587, smtpSecure = 'starttls' } = this.cfg
const port = Number(smtpPort)
const directTls = smtpSecure === 'ssl' || port === 465
this.sock = directTls
? tlsConnect({ host: smtpHost, port, servername: smtpHost, rejectUnauthorized: false })
: netConnect({ host: smtpHost, port })
this.listen()
await this.expect()
await this.cmd(`EHLO ${this.cfg.helo || 'imgbed.local'}`)
if (!directTls) {
await this.cmd('STARTTLS')
const plain = this.sock
plain.removeAllListeners()
this.buffer = ''
this.sock = tlsConnect({ socket: plain, servername: smtpHost, rejectUnauthorized: false })
this.listen()
await this.cmd(`EHLO ${this.cfg.helo || 'imgbed.local'}`)
}
if (this.cfg.smtpUser) {
await this.cmd('AUTH LOGIN')
await this.cmd(b64(this.cfg.smtpUser))
await this.cmd(b64(this.cfg.smtpPass || ''))
}
}
async send({ from, to, subject, text }) {
await this.cmd(`MAIL FROM:<${from}>`)
await this.cmd(`RCPT TO:<${to}>`)
await this.cmd('DATA')
const body = [
`From: ${encodeHeader(this.cfg.fromName || 'imgbed')} <${from}>`,
`To: <${to}>`,
`Subject: ${encodeHeader(subject)}`,
`Date: ${new Date().toUTCString()}`,
'MIME-Version: 1.0',
'Content-Type: text/plain; charset=UTF-8',
'Content-Transfer-Encoding: base64',
'',
chunk76(b64(text)),
].join('\r\n')
const p = this.expect()
this.sock.write(`${body}\r\n.\r\n`)
await p
await this.cmd('QUIT').catch(() => {})
}
close() {
try {
this.sock?.destroy()
} catch {}
}
}
export async function sendMail(cfg, { to, subject, text }) {
const smtp = new Smtp(cfg)
try {
await smtp.open()
await smtp.send({ from: cfg.mailFrom || cfg.smtpUser, to, subject, text })
} finally {
smtp.close()
}
}