Gitea push 通知邮件服务:webhook → 邮件 → 本机 Mailcow

This commit is contained in:
gitea committed 2026-11-18 02:57:18 +08:00
commit 6f35e957a5
5 files changed
+493

No files matched your search

+65
View File
@@ -0,0 +1,65 @@
# gitea-mail-notify
把 **Gitea 的 push 事件**变成一封邮件,投递到本机 **Mailcow** 的邮箱里。
只做一件事:收到 webhook → 渲染一封能看的邮件 → 用本机 SMTP 投递。
- 零依赖(Node 内置 `node:http` / `node:net`)
- 支持多收件人、HTML + 纯文本双格式
- 邮件里带仓库名、推送人、分支、提交列表、每个提交的链接和文件数
- 排队串行发送,失败只记日志不阻塞 webhook(Gitea 不会因此重试刷屏)
## 用起来
```bash
# 1. 配置
sudo tee /etc/gitea-mail-notify.json >/dev/null <<'JSON'
{
"secret": "换成一串你自己记得住的随机字符",
"port": 8095,
"smtpHost": "127.0.0.1",
"smtpPort": 25,
"mailFrom": "gitea@mail.example.com",
"mailTo": "me@mail.example.com",
"subjectPrefix": "[Gitea]"
}
JSON
sudo chmod 600 /etc/gitea-mail-notify.json
# 2. 起服务
sudo node server.mjs
# 或者用 systemd:见 install.sh
# 3. 在 Gitea 里加 Web 钩子
# 仓库 → 设置 → Web 钩子 → 添加 Web 钩子 → Gitea
# 目标 URL: http://127.0.0.1:8095/hook/<secret>
# 触发条件: 推送事件
# 数据格式: application/json
```
批量给所有仓库加钩子(需要 Gitea 令牌,scopes 至少 `write:repository`):
```bash
GITEA=http://127.0.0.1:3000 TOKEN=xxx SECRET=xxx node add-hooks.mjs
```
## 为什么走本机 25 端口
Mailcow 的 Postfix 在 `127.0.0.1:25` 接受本机投递,收件人如果是 Mailcow 里存在的邮箱,会直接进 Dovecot,**不经过外网**,所以云主机封 25 出站也能用。
要给外部邮箱(QQ/Gmail)转发,就得在 Mailcow 里配中继(smarthost),那是另一件事。
## 接口
| 方法 | 路径 | 说明 |
| --- | --- | --- |
| GET | `/health` | 返回发送计数、队列长度、当前收发地址 |
| POST | `/hook/<secret>` | Gitea webhook 入口,只处理 `X-Gitea-Event: push` |
## 文件
| 文件 | 作用 |
| --- | --- |
| `server.mjs` | HTTP 服务 + SMTP 客户端 + 邮件模板 |
| `add-hooks.mjs` | 给 Gitea 里所有仓库批量加 webhook |
| `install.sh` | 装成 systemd 服务 |
MIT
+57
View File
@@ -0,0 +1,57 @@
#!/usr/bin/env node
/**
* 给 Gitea 里所有仓库批量加 push webhook。
* GITEA=http://127.0.0.1:3000 TOKEN=xxx SECRET=xxx node add-hooks.mjs [--all] [--owner gitea]
* 默认只处理 owner 名下的仓库;--all 处理全部。
*/
const GITEA = (process.env.GITEA || 'http://127.0.0.1:3000').replace(/\/+$/, '')
const TOKEN = process.env.TOKEN || ''
const SECRET = process.env.SECRET || ''
const HOOK_URL = process.env.HOOK_URL || `http://127.0.0.1:8095/hook/${SECRET}`
const owner = (process.argv.find((a) => a.startsWith('--owner=')) || '').split('=')[1] || ''
const all = process.argv.includes('--all')
if (!TOKEN || !SECRET) {
console.error('用法:GITEA=http://127.0.0.1:3000 TOKEN=xxx SECRET=xxx node add-hooks.mjs')
process.exit(1)
}
const api = async (path, init = {}) => {
const res = await fetch(GITEA + '/api/v1' + path, {
...init,
headers: { Authorization: 'token ' + TOKEN, 'content-type': 'application/json', ...(init.headers || {}) },
})
const text = await res.text()
let body = null
try { body = JSON.parse(text) } catch { body = text }
return { status: res.status, body }
}
const me = await api('/user')
if (me.status !== 200) {
console.error('拿不到用户信息,检查 TOKEN:', me.status, me.body)
process.exit(1)
}
const login = owner || me.body.login
const repos = await api(`/users/${encodeURIComponent(login)}/repos?limit=50`)
if (repos.status !== 200) {
console.error('列仓库失败:', repos.status, repos.body)
process.exit(1)
}
const list = repos.body.filter((r) => all || !r.private || true)
console.log(`仓库 ${list.length} 个,钩子地址 ${HOOK_URL}`)
for (const repo of list) {
const payload = {
type: 'gitea',
active: true,
events: ['push'],
config: { url: HOOK_URL, content_type: 'json', http_method: 'post' },
}
const created = await api(`/repos/${login}/${repo.name}/hooks`, { method: 'POST', body: JSON.stringify(payload) })
if (created.status === 201) {
console.log(' ✓', repo.full_name)
} else {
console.log(' ✗', repo.full_name, created.status, JSON.stringify(created.body).slice(0, 160))
}
}
Executable
+54
View File
@@ -0,0 +1,54 @@
#!/usr/bin/env bash
# 把 gitea-mail-notify 装成 systemd 服务(需要 Node >= 18)
set -euo pipefail
[ "$(id -u)" = 0 ] || { echo "用 root 跑:sudo bash install.sh"; exit 1; }
DIR="${DIR:-/opt/gitea-mail-notify}"
NODE_BIN="$(command -v node || true)"
[ -n "$NODE_BIN" ] || { echo "没找到 node,先装 Node 18+"; exit 1; }
NODE_BIN="$(readlink -f "$NODE_BIN")"
mkdir -p "$DIR"
cp -f server.mjs add-hooks.mjs package.json README.md "$DIR"/
if [ ! -f /etc/gitea-mail-notify.json ]; then
SECRET="$(head -c 18 /dev/urandom | base64 | tr -d '/+=' | cut -c1-24)"
cat > /etc/gitea-mail-notify.json <<JSON
{
"secret": "${SECRET}",
"port": 8095,
"smtpHost": "127.0.0.1",
"smtpPort": 25,
"mailFrom": "gitea@localhost",
"mailTo": "gitea@localhost",
"subjectPrefix": "[Gitea]"
}
JSON
chmod 600 /etc/gitea-mail-notify.json
echo "已生成 /etc/gitea-mail-notify.json(记得改 mailFrom / mailTo)"
fi
cat > /etc/systemd/system/gitea-mail-notify.service <<UNIT
[Unit]
Description=Gitea push → 邮件通知
After=network-online.target docker.service
Wants=network-online.target
[Service]
Type=simple
Environment=NODE_ENV=production
ExecStart=${NODE_BIN} ${DIR}/server.mjs
Restart=always
RestartSec=3
NoNewPrivileges=true
PrivateTmp=true
[Install]
WantedBy=multi-user.target
UNIT
systemctl daemon-reload
systemctl enable --now gitea-mail-notify
sleep 1
systemctl is-active gitea-mail-notify
SECRET_SHOWN="$(node -e "console.log(require('/etc/gitea-mail-notify.json').secret)" 2>/dev/null || jq -r .secret /etc/gitea-mail-notify.json)"
echo "服务已启动。Gitea 里填:http://127.0.0.1:8095/hook/${SECRET_SHOWN}"
+11
View File
@@ -0,0 +1,11 @@
{
"name": "gitea-mail-notify",
"version": "1.0.0",
"private": true,
"description": "把 Gitea 的 push 事件转成一封邮件,投递到本机 Mailcow 邮箱",
"type": "module",
"main": "server.mjs",
"scripts": { "start": "node server.mjs" },
"engines": { "node": ">=18" },
"license": "MIT"
}
+306
View File
@@ -0,0 +1,306 @@
#!/usr/bin/env node
/**
* gitea-mail-notify —— 把 Gitea 的 push 事件转成邮件,投递到 Mailcow 邮箱。
*
* Gitea → 仓库设置 → Web 钩子 → 添加 Web 钩子(Gitea):
* 目标 URL: http://127.0.0.1:8095/hook/<secret>
* 触发条件: 推送事件
* 数据格式: application/json
*
* 配置(环境变量或 /etc/gitea-mail-notify.json):
* port, host, secret,
* smtpHost(127.0.0.1), smtpPort(587), smtpUser, smtpPass, smtpSecure(starttls|ssl|none)
* mailFrom, mailTo, subjectPrefix
*/
import { createServer } from 'node:http'
import { connect } from 'node:net'
import { TLSSocket } from 'node:tls'
import { readFileSync, existsSync } from 'node:fs'
const CONFIG_FILE = process.env.CONFIG_FILE || '/etc/gitea-mail-notify.json'
const fileCfg = existsSync(CONFIG_FILE) ? JSON.parse(readFileSync(CONFIG_FILE, 'utf8')) : {}
const pick = (env, key, def) => process.env[env] || fileCfg[key] || def
const cfg = {
port: Number(pick('PORT', 'port', 8095)),
host: pick('HOST', 'host', '127.0.0.1'),
secret: pick('SECRET', 'secret', ''),
smtpHost: pick('SMTP_HOST', 'smtpHost', '127.0.0.1'),
smtpPort: Number(pick('SMTP_PORT', 'smtpPort', 587)),
smtpUser: pick('SMTP_USER', 'smtpUser', ''),
smtpPass: pick('SMTP_PASS', 'smtpPass', ''),
smtpSecure: pick('SMTP_SECURE', 'smtpSecure', 'starttls'), // starttls | ssl | none
mailFrom: pick('MAIL_FROM', 'mailFrom', 'gitea@localhost'),
mailTo: String(pick('MAIL_TO', 'mailTo', 'gitea@localhost')).split(',').map((s) => s.trim()).filter(Boolean),
prefix: pick('SUBJECT_PREFIX', 'subjectPrefix', '[Gitea]'),
}
if (!cfg.secret) {
console.error('[fatal] 缺少 secret:写进 /etc/gitea-mail-notify.json 或设 SECRET')
process.exit(1)
}
const log = (...a) => console.log(new Date().toISOString(), ...a)
/* ============ 极简 SMTP 客户端(支持 starttls / ssl / 明文 + AUTH LOGIN) ============ */
class Smtp {
constructor() {
this.buf = ''
this.waiter = null
}
async connect() {
await new Promise((resolve, reject) => {
const onErr = (e) => { reject(e) }
this.raw = connect({ host: cfg.smtpHost, port: cfg.smtpPort })
this.raw.once('error', onErr)
this.raw.once('connect', () => { this.raw.removeListener('error', onErr); resolve() })
})
this.raw.setEncoding('utf8')
this.raw.setTimeout(20000, () => this.fail(new Error('SMTP 空闲超时')))
this.raw.on('data', (c) => this.onData(c))
this.raw.on('error', (e) => this.fail(e))
this.raw.on('close', () => this.fail(new Error('SMTP 连接被关闭')))
if (cfg.smtpSecure === 'ssl') {
const plain = this.raw
this.raw = new TLSSocket(plain, { rejectUnauthorized: false, servername: cfg.smtpHost })
this.raw.setEncoding('utf8')
this.raw.on('data', (c) => this.onData(c))
this.raw.on('error', (e) => this.fail(e))
this.raw.on('close', () => this.fail(new Error('SMTP 连接被关闭')))
}
await this.expect(220)
const ehlo = await this.cmd(`EHLO gitea-mail-notify`, 250)
if (cfg.smtpSecure === 'starttls') {
if (!/STARTTLS/i.test(ehlo)) throw new Error('服务器不支持 STARTTLS')
await this.cmd('STARTTLS', 220)
const plain = this.raw
this.raw = new TLSSocket(plain, { rejectUnauthorized: false, servername: cfg.smtpHost })
this.raw.setEncoding('utf8')
this.raw.on('data', (c) => this.onData(c))
this.raw.on('error', (e) => this.fail(e))
this.raw.on('close', () => this.fail(new Error('SMTP 连接被关闭')))
this.buf = ''
await this.cmd('EHLO gitea-mail-notify', 250)
}
if (cfg.smtpUser) {
await this.cmd('AUTH LOGIN', 334)
await this.cmd(Buffer.from(cfg.smtpUser).toString('base64'), 334)
await this.cmd(Buffer.from(cfg.smtpPass).toString('base64'), 235)
}
}
onData(chunk) {
this.buf += chunk
const lines = []
while (true) {
const i = this.buf.indexOf('\r\n')
if (i < 0) break
lines.push(this.buf.slice(0, i))
this.buf = this.buf.slice(i + 2)
}
if (!lines.length) return
// 多行响应的最后一行为 "250 xxx",前面的都是 "250-xxx"
const last = lines[lines.length - 1]
if (/^\d{3}-/.test(last)) return // 还没结束,继续等
this.lastCode = Number(last.slice(0, 3))
this.lastText = lines.join('\n')
const w = this.waiter
this.waiter = null
if (w) w.resolve(this.lastText)
}
fail(err) {
const w = this.waiter
this.waiter = null
if (w) w.reject(err)
}
expect(code) {
return new Promise((resolve, reject) => {
this.waiter = { resolve: (text) => (this.lastCode === code ? resolve(text) : reject(new Error(`期望 ${code},收到 ${this.lastCode}:${text}`))), reject }
})
}
async cmd(line, code) {
const p = this.expect(code)
this.raw.write(line + '\r\n')
return p
}
async sendMail({ from, to, data }) {
await this.cmd(`MAIL FROM:<${from}>`, 250)
for (const rcpt of to) await this.cmd(`RCPT TO:<${rcpt}>`, 250)
await this.cmd('DATA', 354)
const p = this.expect(250)
this.raw.write(data.replace(/\r?\n/g, '\r\n') + '\r\n.\r\n')
await p
await this.cmd('QUIT', 221).catch(() => {})
this.raw.end()
}
}
/* ============ 邮件内容 ============ */
const esc = (s = '') => String(s).replace(/[&<>"']/g, (c) => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;' }[c]))
const sha = (s = '') => String(s).slice(0, 7)
const branchOf = (ref = '') => String(ref).replace('refs/heads/', '').replace('refs/tags/', '')
const trim = (s, n) => (s.length > n ? s.slice(0, n - 1) + '…' : s)
const wrap76 = (b64) => b64.replace(/(.{76})/g, '$1\r\n')
const encodeHeader = (s) => (/^[\x20-\x7e]*$/.test(s) ? s : '=?UTF-8?B?' + Buffer.from(s, 'utf8').toString('base64') + '?=')
function buildMail(payload) {
const repo = payload.repository || {}
const repoName = repo.full_name || repo.name || 'unknown/repo'
const branch = branchOf(payload.ref)
const commits = Array.isArray(payload.commits) ? payload.commits : []
const pusher = (payload.pusher && (payload.pusher.login || payload.pusher.username)) || 'someone'
const isTag = String(payload.ref || '').startsWith('refs/tags/')
const head = commits[commits.length - 1] || {}
const firstLine = (head.message || '').split('\n')[0] || (isTag ? '新标签 ' + branch : '更新')
const subject = `${cfg.prefix} ${repoName} · ${pusher} → ${branch}:${commits.length || 1} 个提交 · ${trim(firstLine, 50)}`
const compareUrl = payload.compare_url || (repo.html_url ? `${repo.html_url}/commits/${branch}` : '')
const text = [
`${repoName} 有新提交`,
'',
`推送人:${pusher}`,
`分支:${branch}${isTag ? '(标签)' : ''}`,
`提交数:${commits.length}`,
compareUrl ? `对比:${compareUrl}` : '',
'',
...commits.map((c) => {
const msg = (c.message || '').split('\n')[0]
const who = (c.author && (c.author.name || c.author.username)) || ''
return `- ${sha(c.id)} ${msg}${who ? ' —— ' + who : ''}\n ${c.url || ''}`
}),
'',
'—— 由 gitea-mail-notify 自动发送',
].filter((x) => x !== '').join('\n')
const rows = commits.map((c) => {
const files = [].concat(c.added || [], c.removed || [], c.modified || [])
return `<tr>
<td style="padding:8px 10px;border-bottom:1px solid #eef1f6;font-family:ui-monospace,Menlo,monospace;font-size:13px;white-space:nowrap">
<a href="${esc(c.url)}" style="color:#3a67f0;text-decoration:none">${sha(esc(c.id))}</a></td>
<td style="padding:8px 10px;border-bottom:1px solid #eef1f6;font-size:14px;color:#1a2035">${esc((c.message || '').split('\n')[0])}</td>
<td style="padding:8px 10px;border-bottom:1px solid #eef1f6;font-size:12px;color:#6b7893;white-space:nowrap">${esc((c.author && (c.author.name || c.author.username)) || '')}</td>
<td style="padding:8px 10px;border-bottom:1px solid #eef1f6;font-size:12px;color:#6b7893;white-space:nowrap">${files.length} 个文件</td>
</tr>`
}).join('')
const html = `<!doctype html><html><body style="margin:0;padding:24px;background:#f4f6fb;font-family:-apple-system,'Segoe UI',Roboto,'PingFang SC','Microsoft YaHei',sans-serif">
<div style="max-width:680px;margin:0 auto;background:#fff;border-radius:14px;overflow:hidden;border:1px solid #e6e9f0">
<div style="padding:18px 22px;background:linear-gradient(120deg,#3a67f0,#0c9fb2);color:#fff">
<div style="font-size:11px;letter-spacing:.16em;opacity:.85">GITEA · 仓库更新</div>
<div style="font-size:20px;font-weight:700;margin-top:6px">${esc(repoName)}</div>
<div style="font-size:13px;opacity:.92;margin-top:4px">${esc(pusher)} 推送到 <b>${esc(branch)}</b>${isTag ? '(标签)' : ''} · ${commits.length} 个提交</div>
</div>
<table style="width:100%;border-collapse:collapse">
<thead><tr style="background:#f9fafc">
<th align="left" style="padding:10px;font-size:12px;color:#6b7893">提交</th>
<th align="left" style="padding:10px;font-size:12px;color:#6b7893">说明</th>
<th align="left" style="padding:10px;font-size:12px;color:#6b7893">作者</th>
<th align="left" style="padding:10px;font-size:12px;color:#6b7893">改动</th>
</tr></thead>
<tbody>${rows || '<tr><td colspan="4" style="padding:14px;color:#6b7893">没有提交明细</td></tr>'}</tbody>
</table>
<div style="padding:16px 22px">
${compareUrl ? `<a href="${esc(compareUrl)}" style="display:inline-block;padding:9px 16px;background:#3a67f0;color:#fff;border-radius:8px;text-decoration:none;font-size:13px">看这次改动</a>` : ''}
<p style="font-size:12px;color:#a0aec0;margin:14px 0 0">这封邮件由 gitea-mail-notify 自动发出。</p>
</div>
</div></body></html>`
const boundary = 'gmn_' + Date.now().toString(36)
const mime = [
`From: ${cfg.mailFrom}`,
`To: ${cfg.mailTo.join(', ')}`,
`Subject: ${encodeHeader(subject)}`,
'MIME-Version: 1.0',
`Date: ${new Date().toUTCString()}`,
`Message-ID: <${Date.now()}.${Math.random().toString(36).slice(2)}@gitea-mail-notify>`,
`Content-Type: multipart/alternative; boundary="${boundary}"`,
'',
`--${boundary}`,
'Content-Type: text/plain; charset=utf-8',
'Content-Transfer-Encoding: base64',
'',
wrap76(Buffer.from(text, 'utf8').toString('base64')),
`--${boundary}`,
'Content-Type: text/html; charset=utf-8',
'Content-Transfer-Encoding: base64',
'',
wrap76(Buffer.from(html, 'utf8').toString('base64')),
`--${boundary}--`,
'',
].join('\r\n')
return { subject, mime }
}
/* ============ 发送队列 ============ */
const queue = []
let busy = false
let sent = 0
let failed = 0
async function drain() {
if (busy) return
busy = true
while (queue.length) {
const job = queue.shift()
try {
const smtp = new Smtp()
await smtp.connect()
await smtp.sendMail({ from: cfg.mailFrom, to: cfg.mailTo, data: job.mime })
sent++
log('sent', job.subject)
} catch (err) {
failed++
log('send failed:', err.message)
}
}
busy = false
}
/* ============ HTTP ============ */
const server = createServer((req, res) => {
const url = new URL(req.url, 'http://localhost')
const json = (code, obj) => { res.writeHead(code, { 'content-type': 'application/json; charset=utf-8' }); res.end(JSON.stringify(obj)) }
if (req.method === 'GET' && url.pathname === '/health') {
return json(200, { ok: true, sent, failed, queued: queue.length, mailFrom: cfg.mailFrom, mailTo: cfg.mailTo, smtp: `${cfg.smtpHost}:${cfg.smtpPort}/${cfg.smtpSecure}` })
}
if (req.method === 'POST' && url.pathname.startsWith('/hook/')) {
if (url.pathname.slice(6) !== cfg.secret) return json(403, { ok: false, error: 'bad token' })
let size = 0
const chunks = []
req.on('data', (c) => {
size += c.length
if (size > 2 * 1024 * 1024) { req.destroy(); return }
chunks.push(c)
})
req.on('end', () => {
let payload
try { payload = JSON.parse(Buffer.concat(chunks).toString('utf8')) } catch { return json(400, { ok: false, error: 'bad json' }) }
const event = req.headers['x-gitea-event'] || 'push'
if (event !== 'push') return json(200, { ok: true, ignored: event })
if (!payload.commits || !payload.commits.length) return json(200, { ok: true, ignored: 'empty push' })
const mail = buildMail(payload)
queue.push(mail)
json(200, { ok: true, queued: queue.length, subject: mail.subject })
drain()
})
return
}
json(404, { ok: false })
})
server.listen(cfg.port, cfg.host, () => {
log(`listening http://${cfg.host}:${cfg.port} · smtp ${cfg.smtpHost}:${cfg.smtpPort}/${cfg.smtpSecure} · ${cfg.mailFrom} → ${cfg.mailTo.join(', ')}`)
})