Compare commits
3
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
1b81e5ccf8 | ||
|
|
56a3baae95 | ||
|
|
75a1619c68 |
@@ -1,31 +1,18 @@
|
||||
# MailGo
|
||||
|
||||
Go 语言编写的轻量级邮件系统,集成 SMTP / IMAP / POP3 协议服务和 Web 管理界面。
|
||||
Web 前端采用 QQ 邮箱风格的布局:顶部导航 + 左侧文件夹栏 + 邮件列表三栏设计。
|
||||
|
||||
## 功能特性
|
||||
|
||||
- **邮件协议**:SMTP(发送)、IMAP(同步)、POP3(收取),均支持 TLS 加密
|
||||
- **外部投递**:认证用户可向外部邮箱(QQ/Gmail/Outlook 等)发送邮件,内置外发队列、MX 直投、STARTTLS、指数退避重试、退信通知与 DKIM 签名
|
||||
- **Web 邮箱**:QQ 邮箱风格界面,支持收件箱 / 已发送 / 草稿箱、未读角标与搜索过滤、全选 / 批量删除、发件人头像、富文本编辑(Quill.js)、附件上传/下载
|
||||
- **Web 邮箱**:收件箱、已发送、草稿箱、富文本编辑(Quill.js)、附件上传/下载
|
||||
- **管理后台**:域名管理、用户管理、DKIM 密钥自动生成、DNS 配置提示、全量邮件查看、外发队列管理、IP 封禁管理、仪表盘统计
|
||||
- **外部认证**:OAuth2(Google / GitHub)、LDAP(可选,默认关闭)
|
||||
- **安全机制**:BCrypt 密码哈希、登录失败自动封禁 IP、外发频率限制(防滥用)、非认证禁止中继(防开放中继)、管理员可解封
|
||||
- **多数据库**:默认 SQLite,可切换 MySQL
|
||||
- **跨平台**:Linux 生产部署 + Windows 本地调试
|
||||
|
||||
## 界面预览
|
||||
|
||||
| 收件箱 | 邮件阅读 |
|
||||
|--------|----------|
|
||||
|  |  |
|
||||
|
||||
| 写信 | 设置 | 登录 |
|
||||
|------|------|------|
|
||||
|  |  |  |
|
||||
|
||||
> 截图使用演示数据渲染,实际界面以部署为准。
|
||||
|
||||
## 快速开始
|
||||
|
||||
### 编译
|
||||
@@ -121,11 +108,6 @@ ldap_use_tls = false
|
||||
max_fail_attempts = 5 # 登录失败次数阈值
|
||||
ban_duration_min = 30 # 封禁时长(分钟)
|
||||
|
||||
[caddy]
|
||||
data_dir = "" # Caddy 数据目录(含 certificates/ 的那个),
|
||||
# 供后台一键导入证书;留空自动探测
|
||||
# /var/lib/caddy/.local/share/caddy 等常见位置
|
||||
|
||||
[outbound]
|
||||
hostname = "" # EHLO 主机名,留空使用 [smtp] domain
|
||||
poll_interval = 15 # 外发队列扫描间隔(秒)
|
||||
@@ -225,32 +207,6 @@ tls_key = "/etc/mail_go/certs/server.key"
|
||||
> # 私钥路径: /etc/letsencrypt/live/mail.example.com/privkey.pem
|
||||
> ```
|
||||
|
||||
#### 从 Caddy 一键导入证书
|
||||
|
||||
如果本机已用 [Caddy](https://caddyserver.com/) 托管该域名 HTTPS(Caddy 会自动签发并续期证书),
|
||||
可在管理后台 **域名管理 → 编辑域名** 页面点击 **“从 Caddy 获取证书”** 按钮,
|
||||
一键把 Caddy 存储中的证书与私钥导入邮件服务(自动启用该域名的 TLS),无需手动复制 PEM 文件。
|
||||
支持通配符证书(如 `*.example.com` 可匹配 `mail.example.com`)。
|
||||
证书支持**热加载**:导入(或手动上传)后立即生效,无需重启服务——SMTP/IMAP/POP3
|
||||
每次 TLS 握手会自动检查并重载变化的证书文件。
|
||||
|
||||
由于 Caddy 的证书目录仅 `caddy` 用户可读,install.sh 会安装一个 root 权限的证书同步任务
|
||||
(`mailgo-caddy-sync.{path,timer}`),把 Caddy 证书树镜像到 `/srv/mail_go/tls/caddy`,
|
||||
证书续期后自动同步,mail_go 始终可读;另外还会授予 ACL 权限作为直接读取的兜底。
|
||||
安装时自动配置,也可手动执行:
|
||||
|
||||
```bash
|
||||
sudo ./install.sh setup-caddy-cert # 自动探测 Caddy 数据目录并配置同步 + ACL
|
||||
sudo ./install.sh setup-caddy-cert /path/to/caddy/data # 或手动指定数据目录
|
||||
```
|
||||
|
||||
若 Caddy 数据目录不在常见位置,可在配置文件中显式指定:
|
||||
|
||||
```toml
|
||||
[caddy]
|
||||
data_dir = "/var/lib/caddy/.local/share/caddy"
|
||||
```
|
||||
|
||||
### 4. 启用 OAuth2 登录(Google 示例)
|
||||
|
||||
```toml
|
||||
|
||||
@@ -79,15 +79,6 @@ type BanConfig struct {
|
||||
BanDurationMin int `toml:"ban_duration_min"` // Default: 30 (minutes)
|
||||
}
|
||||
|
||||
// CaddyConfig holds settings for importing TLS certificates from a local Caddy.
|
||||
type CaddyConfig struct {
|
||||
// DataDir is the Caddy data directory (the one containing the
|
||||
// "certificates/" subdirectory), used by the one-click certificate
|
||||
// import in the admin panel. Leave empty to auto-detect common
|
||||
// locations such as /var/lib/caddy/.local/share/caddy.
|
||||
DataDir string `toml:"data_dir"`
|
||||
}
|
||||
|
||||
// OutboundConfig holds outbound (external) mail delivery settings.
|
||||
type OutboundConfig struct {
|
||||
Hostname string `toml:"hostname"` // EHLO 主机名,留空使用 [smtp] domain
|
||||
@@ -123,7 +114,6 @@ type Config struct {
|
||||
POP3 POP3Config `toml:"pop3"`
|
||||
Auth AuthConfig `toml:"auth"`
|
||||
Ban BanConfig `toml:"ban"`
|
||||
Caddy CaddyConfig `toml:"caddy"`
|
||||
Outbound OutboundConfig `toml:"outbound"`
|
||||
}
|
||||
|
||||
@@ -194,8 +184,6 @@ func defaultConfig() *Config {
|
||||
MaxFailAttempts: 5,
|
||||
BanDurationMin: 30,
|
||||
},
|
||||
// Caddy: 留空则自动探测常见数据目录,无需配置
|
||||
Caddy: CaddyConfig{},
|
||||
Outbound: OutboundConfig{
|
||||
PollInterval: 15, // 15 秒扫描一次队列
|
||||
MaxAttempts: 12, // 最多尝试 12 次
|
||||
|
||||
Binary file not shown.
|
Before Width: | Height: | Size: 50 KiB |
Binary file not shown.
|
Before Width: | Height: | Size: 81 KiB |
Binary file not shown.
|
Before Width: | Height: | Size: 148 KiB |
Binary file not shown.
|
Before Width: | Height: | Size: 66 KiB |
Binary file not shown.
|
Before Width: | Height: | Size: 52 KiB |
+13
-177
@@ -214,20 +214,6 @@ do_install() {
|
||||
# 4. 拉取代码并编译
|
||||
build_binary
|
||||
|
||||
# 4.5 配置 Caddy 证书同步(若检测到 Caddy),供后台一键导入使用
|
||||
local caddy_data
|
||||
caddy_data="$(find_caddy_data_dir 2>/dev/null || true)"
|
||||
if [[ -n "${caddy_data}" ]]; then
|
||||
info "检测到 Caddy(${caddy_data}),配置证书同步任务 ..."
|
||||
if install_caddy_sync "${caddy_data}"; then
|
||||
ok "Caddy 证书同步已配置(后台可一键导入证书)"
|
||||
else
|
||||
warn "Caddy 证书同步配置失败,可稍后手动执行: sudo $0 setup-caddy-cert"
|
||||
fi
|
||||
# ACL 兜底(失败不影响使用)
|
||||
command -v setfacl &>/dev/null && setup_caddy_acls "${caddy_data}" || true
|
||||
fi
|
||||
|
||||
# 5. 部署文件
|
||||
deploy_files
|
||||
|
||||
@@ -264,153 +250,6 @@ do_install() {
|
||||
warn "⚠ 请登录后立即修改默认密码!"
|
||||
}
|
||||
|
||||
# ======================== Caddy 证书同步 ========================
|
||||
# mail_go 后台有一键“从 Caddy 获取证书”功能:从 Caddy 的证书存储读取
|
||||
# 域名证书与私钥并导入邮件服务。Caddy 证书目录默认仅 caddy 用户可读
|
||||
# (0700/0600),且证书续期后文件会被替换(权限重置),因此安装一个
|
||||
# root 权限的 systemd path/timer 同步任务,把 Caddy 证书树镜像到
|
||||
# mail_go 可读的 <storage>/tls/caddy 目录,续期后自动更新;
|
||||
# 同时授予 ACL 作为直接读取的兜底。用法: sudo ./install.sh setup-caddy-cert [caddy数据目录]
|
||||
|
||||
# 探测 Caddy 数据目录(包含 certificates/ 子目录的那个目录)
|
||||
find_caddy_data_dir() {
|
||||
local candidates=(
|
||||
"/var/lib/caddy/.local/share/caddy"
|
||||
"/root/.local/share/caddy"
|
||||
"/home/caddy/.local/share/caddy"
|
||||
)
|
||||
local d
|
||||
for d in "${candidates[@]}"; do
|
||||
if [[ -d "${d}/certificates" ]]; then
|
||||
echo "${d}"
|
||||
return 0
|
||||
fi
|
||||
done
|
||||
# systemd 服务可能配置了自定义 HOME
|
||||
local home
|
||||
home=$(systemctl show caddy -p Environment --value 2>/dev/null | grep -oP '(?<=HOME=)[^ ]+' || true)
|
||||
if [[ -n "${home}" && -d "${home}/.local/share/caddy/certificates" ]]; then
|
||||
echo "${home}/.local/share/caddy"
|
||||
return 0
|
||||
fi
|
||||
return 1
|
||||
}
|
||||
|
||||
# 用 ACL 授予 mail_go 用户读取 Caddy 证书的权限(幂等,兜底用:
|
||||
# 续期后 caddy 以 0600 重建文件,ACL 可能失效,靠同步任务保障)
|
||||
setup_caddy_acls() {
|
||||
local data_dir="${1:-$(find_caddy_data_dir 2>/dev/null || true)}"
|
||||
[[ -n "${data_dir}" ]] || return 1
|
||||
local certs_dir="${data_dir}/certificates"
|
||||
[[ -d "${certs_dir}" ]] || return 1
|
||||
|
||||
command -v setfacl &>/dev/null || return 1
|
||||
|
||||
# 各级父目录需要 x(遍历)权限
|
||||
local p="${data_dir}"
|
||||
while [[ "${p}" != "/" ]]; do
|
||||
setfacl -m "u:${SERVICE_USER}:x" "${p}" 2>/dev/null
|
||||
p="$(dirname "${p}")"
|
||||
done
|
||||
setfacl -R -m "u:${SERVICE_USER}:rX" "${certs_dir}" 2>/dev/null
|
||||
setfacl -R -m "d:u:${SERVICE_USER}:rX" "${certs_dir}" 2>/dev/null
|
||||
return 0
|
||||
}
|
||||
|
||||
# 安装证书同步脚本 + systemd path/timer 单元,并立即同步一次
|
||||
install_caddy_sync() {
|
||||
local data_dir="$1"
|
||||
local sync_script="/usr/local/sbin/mailgo-caddy-cert-sync.sh"
|
||||
local sync_dir="${DATA_DIR}/tls/caddy"
|
||||
local certs_dir="${data_dir}/certificates"
|
||||
|
||||
# 同步脚本(把数据目录固化进去)
|
||||
cat > "${sync_script}" <<EOF
|
||||
#!/usr/bin/env bash
|
||||
# MailGo - 将 Caddy 证书存储镜像到 mail_go 可读目录(root 运行,
|
||||
# 由 mailgo-caddy-sync.{path,timer} 触发),供后台一键导入使用。
|
||||
set -euo pipefail
|
||||
SRC="${certs_dir}"
|
||||
SYNC="${sync_dir}"
|
||||
[[ -d "\${SRC}" ]] || exit 0
|
||||
mkdir -p "\${SYNC}"
|
||||
rm -rf "\${SYNC}/.certs.tmp"
|
||||
cp -a "\${SRC}" "\${SYNC}/.certs.tmp"
|
||||
chown -R "${SERVICE_USER}:${SERVICE_USER}" "\${SYNC}/.certs.tmp"
|
||||
chmod -R u+rwX,go-rwx "\${SYNC}/.certs.tmp"
|
||||
rm -rf "\${SYNC}/certificates"
|
||||
mv "\${SYNC}/.certs.tmp" "\${SYNC}/certificates"
|
||||
EOF
|
||||
chmod 700 "${sync_script}"
|
||||
|
||||
cat > /etc/systemd/system/mailgo-caddy-sync.service <<EOF
|
||||
[Unit]
|
||||
Description=MailGo - 同步 Caddy 证书到 mail_go TLS 目录
|
||||
After=network.target
|
||||
|
||||
[Service]
|
||||
Type=oneshot
|
||||
ExecStart=${sync_script}
|
||||
EOF
|
||||
|
||||
cat > /etc/systemd/system/mailgo-caddy-sync.path <<EOF
|
||||
[Unit]
|
||||
Description=MailGo - 监视 Caddy 证书目录变化并触发同步
|
||||
|
||||
[Path]
|
||||
PathChanged=${certs_dir}
|
||||
PathChanged=${certs_dir}/*/*
|
||||
Unit=mailgo-caddy-sync.service
|
||||
|
||||
[Install]
|
||||
WantedBy=multi-user.target
|
||||
EOF
|
||||
|
||||
cat > /etc/systemd/system/mailgo-caddy-sync.timer <<EOF
|
||||
[Unit]
|
||||
Description=MailGo - 定期同步 Caddy 证书(开机 + 每日兜底)
|
||||
|
||||
[Timer]
|
||||
OnBootSec=1min
|
||||
OnUnitActiveSec=1d
|
||||
Unit=mailgo-caddy-sync.service
|
||||
|
||||
[Install]
|
||||
WantedBy=timers.target
|
||||
EOF
|
||||
|
||||
systemctl daemon-reload
|
||||
systemctl enable --now mailgo-caddy-sync.path mailgo-caddy-sync.timer >/dev/null
|
||||
systemctl start mailgo-caddy-sync.service
|
||||
return 0
|
||||
}
|
||||
|
||||
do_setup_caddy_cert() {
|
||||
check_root
|
||||
local data_dir="${2:-}"
|
||||
if [[ -z "${data_dir}" ]]; then
|
||||
data_dir="$(find_caddy_data_dir || true)"
|
||||
if [[ -z "${data_dir}" ]]; then
|
||||
error "未检测到 Caddy 数据目录(/var/lib/caddy 等),请手动指定: sudo $0 setup-caddy-cert <caddy数据目录>"
|
||||
fi
|
||||
info "检测到 Caddy 数据目录: ${data_dir}"
|
||||
elif [[ ! -d "${data_dir}/certificates" ]]; then
|
||||
error "目录 ${data_dir} 下未找到 certificates/ 子目录,请确认传入的是 Caddy 数据目录"
|
||||
fi
|
||||
|
||||
info "安装证书同步任务(systemd path + timer,续期后自动同步)..."
|
||||
install_caddy_sync "${data_dir}"
|
||||
ok "证书同步任务已安装并完成首次同步"
|
||||
|
||||
if command -v setfacl &>/dev/null && setup_caddy_acls "${data_dir}"; then
|
||||
ok "已授予 ${SERVICE_USER} 用户直接读取 Caddy 证书的 ACL 权限(兜底)"
|
||||
else
|
||||
warn "未配置 ACL 兜底(不影响使用,同步镜像始终可读)"
|
||||
fi
|
||||
|
||||
ok "现在可在管理后台“编辑域名”页点击“从 Caddy 获取证书”一键导入"
|
||||
}
|
||||
|
||||
# ======================== 卸载 ========================
|
||||
do_uninstall() {
|
||||
info "========== 卸载 ${SERVICE_NAME} =========="
|
||||
@@ -513,24 +352,21 @@ do_status() {
|
||||
|
||||
# ======================== 入口 ========================
|
||||
case "${1:-}" in
|
||||
install) do_install ;;
|
||||
uninstall) do_uninstall ;;
|
||||
start) do_start ;;
|
||||
stop) do_stop ;;
|
||||
restart) do_restart ;;
|
||||
status) do_status ;;
|
||||
setup-caddy-cert) do_setup_caddy_cert ;;
|
||||
install) do_install ;;
|
||||
uninstall) do_uninstall ;;
|
||||
start) do_start ;;
|
||||
stop) do_stop ;;
|
||||
restart) do_restart ;;
|
||||
status) do_status ;;
|
||||
*)
|
||||
echo "用法: sudo $0 {install|uninstall|start|stop|restart|status|setup-caddy-cert}"
|
||||
echo "用法: sudo $0 {install|uninstall|start|stop|restart|status}"
|
||||
echo ""
|
||||
echo " install — 完整安装/更新(拉代码+编译+部署+启动+开机自启)"
|
||||
echo " uninstall — 卸载服务(可选保留数据)"
|
||||
echo " start — 启动服务"
|
||||
echo " stop — 停止服务"
|
||||
echo " restart — 重启服务"
|
||||
echo " status — 查看服务状态"
|
||||
echo " setup-caddy-cert — 授予 mail_go 读取本机 Caddy 证书的 ACL 权限"
|
||||
echo " (后台“从 Caddy 获取证书”按钮的前置条件)"
|
||||
echo " install — 完整安装/更新(拉代码+编译+部署+启动+开机自启)"
|
||||
echo " uninstall — 卸载服务(可选保留数据)"
|
||||
echo " start — 启动服务"
|
||||
echo " stop — 停止服务"
|
||||
echo " restart — 重启服务"
|
||||
echo " status — 查看服务状态"
|
||||
exit 1
|
||||
;;
|
||||
esac
|
||||
@@ -1,243 +0,0 @@
|
||||
// Package caddycert 从本机 Caddy 的证书存储中查找并读取某个域名
|
||||
// 的 TLS 证书与私钥,供 MailGo 一键导入使用。
|
||||
//
|
||||
// Caddy(certmagic)将 ACME 证书保存在其数据目录下的
|
||||
//
|
||||
// <data>/certificates/<CA 目录>/<域名>/<域名>.crt
|
||||
// <data>/certificates/<CA 目录>/<域名>/<域名>.key
|
||||
//
|
||||
// 数据目录默认是 $HOME/.local/share/caddy(systemd 服务通常是
|
||||
// /var/lib/caddy/.local/share/caddy),可通过配置 caddy.data_dir 覆盖。
|
||||
package caddycert
|
||||
|
||||
import (
|
||||
"crypto/tls"
|
||||
"crypto/x509"
|
||||
"fmt"
|
||||
"os"
|
||||
"os/user"
|
||||
"path/filepath"
|
||||
"sort"
|
||||
"strings"
|
||||
"time"
|
||||
)
|
||||
|
||||
// DefaultDataDirs 是未显式配置时依次探测的 Caddy 数据目录。
|
||||
var DefaultDataDirs = []string{
|
||||
"/var/lib/caddy/.local/share/caddy", // Debian/Ubuntu 软件包的 systemd 服务默认 HOME
|
||||
"/root/.local/share/caddy", // 直接以 root 运行的 caddy
|
||||
"/home/caddy/.local/share/caddy",
|
||||
}
|
||||
|
||||
// Cert 是从 Caddy 存储中找到的一对证书与私钥(PEM 编码)。
|
||||
type Cert struct {
|
||||
CertPEM []byte // 证书链(含叶子证书)
|
||||
KeyPEM []byte // 私钥
|
||||
Source string // 来源 .crt 文件的绝对路径
|
||||
}
|
||||
|
||||
// Fetch 在给定的 Caddy 证书数据目录中查找 domain 的证书与私钥。
|
||||
//
|
||||
// dataDirs 按优先级从高到低排列,每个目录都是包含 certificates/ 子目录的
|
||||
// Caddy 数据目录(如 /var/lib/caddy/.local/share/caddy,或 mail_go 的同步
|
||||
// 镜像目录 /srv/mail_go/tls/caddy);空字符串项被忽略。dataDirs 为空时仅
|
||||
// 探测 DefaultDataDirs 及当前进程用户的数据目录。
|
||||
//
|
||||
// 返回的证书保证:能组成有效的密钥对、尚未过期、且证书 SAN 覆盖 domain
|
||||
// (支持通配符证书,例如 *.example.com 的证书可匹配 mail.example.com)。
|
||||
func Fetch(domain string, dataDirs []string) (*Cert, error) {
|
||||
domain = strings.ToLower(strings.TrimSpace(domain))
|
||||
if domain == "" {
|
||||
return nil, fmt.Errorf("域名为空")
|
||||
}
|
||||
|
||||
roots := dataRoots(dataDirs)
|
||||
|
||||
var (
|
||||
permDenied []string
|
||||
seen []string // 找到同名/相关文件但证书无效的来源
|
||||
)
|
||||
for _, root := range roots {
|
||||
cert, found, invalid, err := searchRoot(domain, root)
|
||||
if err != nil {
|
||||
if os.IsPermission(err) {
|
||||
permDenied = append(permDenied, root)
|
||||
continue
|
||||
}
|
||||
continue
|
||||
}
|
||||
if found {
|
||||
return cert, nil
|
||||
}
|
||||
seen = append(seen, invalid...)
|
||||
}
|
||||
|
||||
msg := fmt.Sprintf("在 Caddy 证书存储中未找到域名 %q 的证书(请确认 Caddy 已为该域名签发证书)", domain)
|
||||
if len(seen) > 0 {
|
||||
msg += fmt.Sprintf(";发现相关文件但证书无效/已过期/不匹配域名: %s", strings.Join(seen, "、"))
|
||||
}
|
||||
if len(permDenied) > 0 {
|
||||
msg += fmt.Sprintf(";另有目录因权限不足未能检查: %s,可运行 install.sh 的 setup-caddy-cert 授予 %s 用户读取权限",
|
||||
strings.Join(permDenied, "、"), currentUsername())
|
||||
}
|
||||
return nil, fmt.Errorf("%s", msg)
|
||||
}
|
||||
|
||||
// dataRoots 返回要探测的候选数据目录列表(去重,保留优先级顺序)。
|
||||
func dataRoots(dataDirs []string) []string {
|
||||
var roots []string
|
||||
seen := map[string]bool{}
|
||||
add := func(p string) {
|
||||
p = strings.TrimRight(filepath.Clean(p), string(filepath.Separator))
|
||||
if p == "" || seen[p] {
|
||||
return
|
||||
}
|
||||
seen[p] = true
|
||||
roots = append(roots, p)
|
||||
}
|
||||
|
||||
for _, d := range dataDirs {
|
||||
add(d)
|
||||
}
|
||||
for _, d := range DefaultDataDirs {
|
||||
add(d)
|
||||
}
|
||||
if home, err := os.UserHomeDir(); err == nil && home != "" {
|
||||
add(filepath.Join(home, ".local", "share", "caddy"))
|
||||
}
|
||||
return roots
|
||||
}
|
||||
|
||||
// searchRoot 在单个数据目录中查找 domain 的证书。
|
||||
// 返回 (证书, 是否找到, 找到但无效的来源列表, 错误)。
|
||||
func searchRoot(domain, root string) (*Cert, bool, []string, error) {
|
||||
// 允许把 certificates/ 目录本身当作 data_dir 传入
|
||||
certsDir := root
|
||||
if filepath.Base(certsDir) != "certificates" {
|
||||
certsDir = filepath.Join(root, "certificates")
|
||||
}
|
||||
|
||||
info, err := os.Stat(certsDir)
|
||||
if err != nil {
|
||||
if os.IsNotExist(err) {
|
||||
return nil, false, nil, nil
|
||||
}
|
||||
return nil, false, nil, err
|
||||
}
|
||||
if !info.IsDir() {
|
||||
return nil, false, nil, nil
|
||||
}
|
||||
|
||||
caDirs, err := os.ReadDir(certsDir)
|
||||
if err != nil {
|
||||
return nil, false, nil, err
|
||||
}
|
||||
|
||||
var invalid []string
|
||||
|
||||
// 1) 直接路径: certificates/<CA>/<domain>/<domain>.crt|.key
|
||||
for _, ca := range caDirs {
|
||||
if !ca.IsDir() {
|
||||
continue
|
||||
}
|
||||
cert, found, bad, err := readDomainDir(filepath.Join(certsDir, ca.Name(), domain), domain)
|
||||
if err != nil {
|
||||
return nil, false, nil, err
|
||||
}
|
||||
if found {
|
||||
return cert, true, nil, nil
|
||||
}
|
||||
invalid = append(invalid, bad...)
|
||||
}
|
||||
|
||||
// 2) 全量扫描,处理通配符证书(如 *.example.com 目录)等情况
|
||||
for _, ca := range caDirs {
|
||||
if !ca.IsDir() {
|
||||
continue
|
||||
}
|
||||
caPath := filepath.Join(certsDir, ca.Name())
|
||||
domDirs, err := os.ReadDir(caPath)
|
||||
if err != nil {
|
||||
return nil, false, nil, err
|
||||
}
|
||||
for _, d := range domDirs {
|
||||
if !d.IsDir() {
|
||||
continue
|
||||
}
|
||||
cert, found, bad, err := readDomainDir(filepath.Join(caPath, d.Name()), domain)
|
||||
if err != nil {
|
||||
return nil, false, nil, err
|
||||
}
|
||||
if found {
|
||||
return cert, true, nil, nil
|
||||
}
|
||||
invalid = append(invalid, bad...)
|
||||
}
|
||||
}
|
||||
|
||||
sort.Strings(invalid)
|
||||
return nil, false, invalid, nil
|
||||
}
|
||||
|
||||
// readDomainDir 读取 Caddy 某个域名目录下的 <name>.crt 与 <name>.key,
|
||||
// 校验其是否为 domain 的有效证书。bad 返回“存在但无效”的来源路径。
|
||||
func readDomainDir(dirPath, domain string) (*Cert, bool, []string, error) {
|
||||
name := filepath.Base(dirPath)
|
||||
certPath := filepath.Join(dirPath, name+".crt")
|
||||
keyPath := filepath.Join(dirPath, name+".key")
|
||||
|
||||
certPEM, err := os.ReadFile(certPath)
|
||||
if err != nil {
|
||||
if os.IsNotExist(err) {
|
||||
return nil, false, nil, nil
|
||||
}
|
||||
return nil, false, nil, err
|
||||
}
|
||||
keyPEM, err := os.ReadFile(keyPath)
|
||||
if err != nil {
|
||||
if os.IsNotExist(err) {
|
||||
return nil, false, nil, nil
|
||||
}
|
||||
return nil, false, nil, err
|
||||
}
|
||||
|
||||
// 只有与目标域名相关的目录才值得报“无效”,否则静默跳过
|
||||
related := strings.TrimSuffix(name, "."+domain) == domain ||
|
||||
name == domain || strings.HasPrefix(name, "*.") && strings.HasSuffix(domain, name[1:])
|
||||
|
||||
if !validPair(certPEM, keyPEM, domain) {
|
||||
if related {
|
||||
return nil, false, []string{certPath}, nil
|
||||
}
|
||||
return nil, false, nil, nil
|
||||
}
|
||||
|
||||
return &Cert{CertPEM: certPEM, KeyPEM: keyPEM, Source: certPath}, true, nil, nil
|
||||
}
|
||||
|
||||
// validPair 校验证书/私钥是否组成有效密钥对、未过期且 SAN 覆盖 domain。
|
||||
func validPair(certPEM, keyPEM []byte, domain string) bool {
|
||||
pair, err := tls.X509KeyPair(certPEM, keyPEM)
|
||||
if err != nil {
|
||||
return false
|
||||
}
|
||||
if len(pair.Certificate) == 0 {
|
||||
return false
|
||||
}
|
||||
leaf, err := x509.ParseCertificate(pair.Certificate[0])
|
||||
if err != nil {
|
||||
return false
|
||||
}
|
||||
if time.Now().After(leaf.NotAfter) {
|
||||
return false
|
||||
}
|
||||
return leaf.VerifyHostname(domain) == nil
|
||||
}
|
||||
|
||||
// currentUsername 返回当前进程的运行用户(错误提示用)。
|
||||
func currentUsername() string {
|
||||
if u, err := user.Current(); err == nil && u.Username != "" {
|
||||
return u.Username
|
||||
}
|
||||
return os.Getenv("USER")
|
||||
}
|
||||
@@ -1,176 +0,0 @@
|
||||
package caddycert
|
||||
|
||||
import (
|
||||
"crypto/rand"
|
||||
"crypto/rsa"
|
||||
"crypto/x509"
|
||||
"crypto/x509/pkix"
|
||||
"encoding/pem"
|
||||
"math/big"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
// makeCert 生成一份自签名证书(含指定 SAN),返回 PEM 编码的证书与私钥。
|
||||
func makeCert(t *testing.T, dnsNames []string, notBefore, notAfter time.Time) (certPEM, keyPEM []byte) {
|
||||
t.Helper()
|
||||
|
||||
key, err := rsa.GenerateKey(rand.Reader, 2048)
|
||||
if err != nil {
|
||||
t.Fatalf("生成私钥失败: %v", err)
|
||||
}
|
||||
|
||||
tmpl := &x509.Certificate{
|
||||
SerialNumber: big.NewInt(1),
|
||||
Subject: pkix.Name{CommonName: dnsNames[0]},
|
||||
DNSNames: dnsNames,
|
||||
NotBefore: notBefore,
|
||||
NotAfter: notAfter,
|
||||
KeyUsage: x509.KeyUsageDigitalSignature | x509.KeyUsageKeyEncipherment,
|
||||
ExtKeyUsage: []x509.ExtKeyUsage{x509.ExtKeyUsageServerAuth},
|
||||
}
|
||||
der, err := x509.CreateCertificate(rand.Reader, tmpl, tmpl, &key.PublicKey, key)
|
||||
if err != nil {
|
||||
t.Fatalf("生成证书失败: %v", err)
|
||||
}
|
||||
|
||||
certPEM = pem.EncodeToMemory(&pem.Block{Type: "CERTIFICATE", Bytes: der})
|
||||
keyPEM = pem.EncodeToMemory(&pem.Block{Type: "RSA PRIVATE KEY", Bytes: x509.MarshalPKCS1PrivateKey(key)})
|
||||
return certPEM, keyPEM
|
||||
}
|
||||
|
||||
// writeSite 在 Caddy 风格目录结构中写入某个域名的证书。
|
||||
func writeSite(t *testing.T, dataDir, domain string, certPEM, keyPEM []byte) {
|
||||
t.Helper()
|
||||
dir := filepath.Join(dataDir, "certificates", "acme-v02.api.letsencrypt.org-directory", domain)
|
||||
if err := os.MkdirAll(dir, 0700); err != nil {
|
||||
t.Fatalf("创建目录失败: %v", err)
|
||||
}
|
||||
if err := os.WriteFile(filepath.Join(dir, domain+".crt"), certPEM, 0600); err != nil {
|
||||
t.Fatalf("写入证书失败: %v", err)
|
||||
}
|
||||
if err := os.WriteFile(filepath.Join(dir, domain+".key"), keyPEM, 0600); err != nil {
|
||||
t.Fatalf("写入私钥失败: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestFetchExactDomain(t *testing.T) {
|
||||
dataDir := t.TempDir()
|
||||
certPEM, keyPEM := makeCert(t, []string{"mail.example.com"}, time.Now().Add(-time.Hour), time.Now().Add(24*time.Hour))
|
||||
writeSite(t, dataDir, "mail.example.com", certPEM, keyPEM)
|
||||
|
||||
got, err := Fetch("mail.example.com", []string{dataDir})
|
||||
if err != nil {
|
||||
t.Fatalf("Fetch 失败: %v", err)
|
||||
}
|
||||
if string(got.CertPEM) != string(certPEM) {
|
||||
t.Error("返回的证书与写入的不一致")
|
||||
}
|
||||
if string(got.KeyPEM) != string(keyPEM) {
|
||||
t.Error("返回的私钥与写入的不一致")
|
||||
}
|
||||
}
|
||||
|
||||
func TestFetchWildcardCoversSubdomain(t *testing.T) {
|
||||
dataDir := t.TempDir()
|
||||
certPEM, keyPEM := makeCert(t, []string{"*.example.com", "example.com"}, time.Now().Add(-time.Hour), time.Now().Add(24*time.Hour))
|
||||
writeSite(t, dataDir, "*.example.com", certPEM, keyPEM)
|
||||
|
||||
got, err := Fetch("mail.example.com", []string{dataDir})
|
||||
if err != nil {
|
||||
t.Fatalf("通配符证书应覆盖子域名,Fetch 失败: %v", err)
|
||||
}
|
||||
if got.Source == "" {
|
||||
t.Error("Source 不应为空")
|
||||
}
|
||||
}
|
||||
|
||||
func TestFetchSkipsExpiredCert(t *testing.T) {
|
||||
dataDir := t.TempDir()
|
||||
certPEM, keyPEM := makeCert(t, []string{"mail.example.com"}, time.Now().Add(-48*time.Hour), time.Now().Add(-24*time.Hour))
|
||||
writeSite(t, dataDir, "mail.example.com", certPEM, keyPEM)
|
||||
|
||||
_, err := Fetch("mail.example.com", []string{dataDir})
|
||||
if err == nil {
|
||||
t.Fatal("过期证书不应被返回")
|
||||
}
|
||||
if !strings.Contains(err.Error(), "无效") {
|
||||
t.Errorf("错误信息应说明证书无效,实际: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestFetchNotExist(t *testing.T) {
|
||||
dataDir := t.TempDir()
|
||||
|
||||
_, err := Fetch("nobody.example.com", []string{dataDir})
|
||||
if err == nil {
|
||||
t.Fatal("不存在的域名应返回错误")
|
||||
}
|
||||
if !strings.Contains(err.Error(), "未找到") {
|
||||
t.Errorf("错误信息应包含“未找到”,实际: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestFetchUppercaseDomainIsLowercased(t *testing.T) {
|
||||
dataDir := t.TempDir()
|
||||
certPEM, keyPEM := makeCert(t, []string{"mail.example.com"}, time.Now().Add(-time.Hour), time.Now().Add(24*time.Hour))
|
||||
writeSite(t, dataDir, "mail.example.com", certPEM, keyPEM)
|
||||
|
||||
if _, err := Fetch("MAIL.Example.COM", []string{dataDir}); err != nil {
|
||||
t.Fatalf("域名大小写应被归一化,Fetch 失败: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestFetchCertificatesDirAsDataDir(t *testing.T) {
|
||||
dataDir := t.TempDir()
|
||||
certPEM, keyPEM := makeCert(t, []string{"mail.example.com"}, time.Now().Add(-time.Hour), time.Now().Add(24*time.Hour))
|
||||
writeSite(t, dataDir, "mail.example.com", certPEM, keyPEM)
|
||||
|
||||
// 把 certificates 目录本身当作 data_dir 传入
|
||||
certsDir := filepath.Join(dataDir, "certificates")
|
||||
if _, err := Fetch("mail.example.com", []string{certsDir}); err != nil {
|
||||
t.Fatalf("data_dir 直接指向 certificates 目录时应可用: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestFetchPrefersFirstDataDir(t *testing.T) {
|
||||
// 模拟“同步镜像目录优先”:两个目录都有该域名证书时,应返回第一个的
|
||||
dirA := t.TempDir()
|
||||
dirB := t.TempDir()
|
||||
certA, keyA := makeCert(t, []string{"mail.example.com"}, time.Now().Add(-time.Hour), time.Now().Add(48*time.Hour))
|
||||
certB, keyB := makeCert(t, []string{"mail.example.com"}, time.Now().Add(-time.Hour), time.Now().Add(24*time.Hour))
|
||||
writeSite(t, dirA, "mail.example.com", certA, keyA)
|
||||
writeSite(t, dirB, "mail.example.com", certB, keyB)
|
||||
|
||||
got, err := Fetch("mail.example.com", []string{dirA, dirB})
|
||||
if err != nil {
|
||||
t.Fatalf("Fetch 失败: %v", err)
|
||||
}
|
||||
if string(got.CertPEM) != string(certA) {
|
||||
t.Error("应按优先级返回第一个目录中的证书")
|
||||
}
|
||||
}
|
||||
|
||||
func TestFetchPermissionDeniedHint(t *testing.T) {
|
||||
if os.Geteuid() == 0 {
|
||||
t.Skip("root 用户不受文件权限限制,跳过")
|
||||
}
|
||||
dataDir := t.TempDir()
|
||||
certPEM, keyPEM := makeCert(t, []string{"mail.example.com"}, time.Now().Add(-time.Hour), time.Now().Add(24*time.Hour))
|
||||
writeSite(t, dataDir, "mail.example.com", certPEM, keyPEM)
|
||||
if err := os.Chmod(dataDir, 0000); err != nil {
|
||||
t.Fatalf("chmod 失败: %v", err)
|
||||
}
|
||||
defer os.Chmod(dataDir, 0700)
|
||||
|
||||
_, err := Fetch("mail.example.com", []string{dataDir})
|
||||
if err == nil {
|
||||
t.Fatal("无权限时应返回错误")
|
||||
}
|
||||
if !strings.Contains(err.Error(), "权限不足") {
|
||||
t.Errorf("错误信息应提示权限不足,实际: %v", err)
|
||||
}
|
||||
}
|
||||
@@ -7,7 +7,6 @@ import (
|
||||
|
||||
"mail_go/config"
|
||||
"mail_go/internal/store"
|
||||
"mail_go/internal/tlsutil"
|
||||
|
||||
"github.com/emersion/go-imap/backend"
|
||||
imapserver "github.com/emersion/go-imap/server"
|
||||
@@ -15,27 +14,27 @@ import (
|
||||
|
||||
// IMAPServer wraps a go-imap Server and provides mailbox access capability.
|
||||
type IMAPServer struct {
|
||||
stores *store.Stores
|
||||
cfg config.IMAPConfig
|
||||
tlsLoader *tlsutil.Loader
|
||||
stores *store.Stores
|
||||
cfg config.IMAPConfig
|
||||
}
|
||||
|
||||
// NewIMAPServer creates a new IMAP server instance. tlsLoader may be nil
|
||||
// when TLS is not configured.
|
||||
func NewIMAPServer(cfg config.IMAPConfig, stores *store.Stores, tlsLoader *tlsutil.Loader) *IMAPServer {
|
||||
// NewIMAPServer creates a new IMAP server instance.
|
||||
func NewIMAPServer(cfg config.IMAPConfig, stores *store.Stores) *IMAPServer {
|
||||
return &IMAPServer{
|
||||
stores: stores,
|
||||
cfg: cfg,
|
||||
tlsLoader: tlsLoader,
|
||||
stores: stores,
|
||||
cfg: cfg,
|
||||
}
|
||||
}
|
||||
|
||||
func (s *IMAPServer) tlsConfig() (*tls.Config, error) {
|
||||
if s.tlsLoader == nil {
|
||||
if s.cfg.TLSCert == "" || s.cfg.TLSKey == "" {
|
||||
return nil, fmt.Errorf("IMAP TLS certificate or key not configured")
|
||||
}
|
||||
// GetCertificate 每次握手按需重载证书,证书更新后无需重启服务
|
||||
return &tls.Config{GetCertificate: s.tlsLoader.GetCertificate}, nil
|
||||
cert, err := tls.LoadX509KeyPair(s.cfg.TLSCert, s.cfg.TLSKey)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to load IMAP TLS certificate: %w", err)
|
||||
}
|
||||
return &tls.Config{Certificates: []tls.Certificate{cert}}, nil
|
||||
}
|
||||
|
||||
// newServer creates a configured imapserver.Server with the given address.
|
||||
|
||||
@@ -14,30 +14,30 @@ import (
|
||||
"mail_go/config"
|
||||
"mail_go/internal/db"
|
||||
"mail_go/internal/store"
|
||||
"mail_go/internal/tlsutil"
|
||||
)
|
||||
|
||||
// POP3Server implements a simple POP3 mail server over TCP.
|
||||
type POP3Server struct {
|
||||
listener net.Listener
|
||||
stores *store.Stores
|
||||
cfg config.POP3Config
|
||||
tlsLoader *tlsutil.Loader
|
||||
wg sync.WaitGroup
|
||||
listener net.Listener
|
||||
stores *store.Stores
|
||||
cfg config.POP3Config
|
||||
wg sync.WaitGroup
|
||||
}
|
||||
|
||||
// NewPOP3Server creates a new POP3 server instance. tlsLoader may be nil
|
||||
// when TLS is not configured.
|
||||
func NewPOP3Server(cfg config.POP3Config, stores *store.Stores, tlsLoader *tlsutil.Loader) *POP3Server {
|
||||
return &POP3Server{stores: stores, cfg: cfg, tlsLoader: tlsLoader}
|
||||
// NewPOP3Server creates a new POP3 server instance.
|
||||
func NewPOP3Server(cfg config.POP3Config, stores *store.Stores) *POP3Server {
|
||||
return &POP3Server{stores: stores, cfg: cfg}
|
||||
}
|
||||
|
||||
func (s *POP3Server) tlsConfig() (*tls.Config, error) {
|
||||
if s.tlsLoader == nil {
|
||||
if s.cfg.TLSCert == "" || s.cfg.TLSKey == "" {
|
||||
return nil, fmt.Errorf("POP3 TLS certificate or key not configured")
|
||||
}
|
||||
// GetCertificate 每次握手按需重载证书,证书更新后无需重启服务
|
||||
return &tls.Config{GetCertificate: s.tlsLoader.GetCertificate}, nil
|
||||
cert, err := tls.LoadX509KeyPair(s.cfg.TLSCert, s.cfg.TLSKey)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("load POP3 TLS certificate failed: %w", err)
|
||||
}
|
||||
return &tls.Config{Certificates: []tls.Certificate{cert}}, nil
|
||||
}
|
||||
|
||||
// Start starts the POP3 server on the configured plain-text port.
|
||||
|
||||
@@ -15,7 +15,6 @@ import (
|
||||
"mail_go/internal/outbound"
|
||||
"mail_go/internal/storage"
|
||||
"mail_go/internal/store"
|
||||
"mail_go/internal/tlsutil"
|
||||
|
||||
"github.com/emersion/go-message/mail"
|
||||
"github.com/emersion/go-sasl"
|
||||
@@ -32,25 +31,27 @@ const (
|
||||
|
||||
// SMTPServer wraps go-smtp servers and provides local mail delivery.
|
||||
type SMTPServer struct {
|
||||
stores *store.Stores
|
||||
storage *storage.AttachmentStorage
|
||||
outbound *outbound.Manager
|
||||
cfg config.SMTPConfig
|
||||
tlsLoader *tlsutil.Loader
|
||||
stores *store.Stores
|
||||
storage *storage.AttachmentStorage
|
||||
outbound *outbound.Manager
|
||||
cfg config.SMTPConfig
|
||||
}
|
||||
|
||||
// NewSMTPServer creates a new SMTP server instance. tlsLoader may be nil
|
||||
// when TLS is not configured.
|
||||
func NewSMTPServer(cfg config.SMTPConfig, stores *store.Stores, attStorage *storage.AttachmentStorage, ob *outbound.Manager, tlsLoader *tlsutil.Loader) *SMTPServer {
|
||||
return &SMTPServer{stores: stores, storage: attStorage, outbound: ob, cfg: cfg, tlsLoader: tlsLoader}
|
||||
// NewSMTPServer creates a new SMTP server instance.
|
||||
func NewSMTPServer(cfg config.SMTPConfig, stores *store.Stores, attStorage *storage.AttachmentStorage, ob *outbound.Manager) *SMTPServer {
|
||||
return &SMTPServer{stores: stores, storage: attStorage, outbound: ob, cfg: cfg}
|
||||
}
|
||||
|
||||
func (s *SMTPServer) tlsConfig() (*tls.Config, error) {
|
||||
if s.tlsLoader == nil {
|
||||
if s.cfg.TLSCert == "" || s.cfg.TLSKey == "" {
|
||||
return nil, fmt.Errorf("SMTP TLS certificate or key not configured")
|
||||
}
|
||||
// GetCertificate 每次握手按需重载证书,证书更新后无需重启服务
|
||||
return &tls.Config{GetCertificate: s.tlsLoader.GetCertificate}, nil
|
||||
|
||||
cert, err := tls.LoadX509KeyPair(s.cfg.TLSCert, s.cfg.TLSKey)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to load SMTP TLS certificate: %w", err)
|
||||
}
|
||||
return &tls.Config{Certificates: []tls.Certificate{cert}}, nil
|
||||
}
|
||||
|
||||
func (s *SMTPServer) newServer(addr string, mode smtpMode, tlsConfig *tls.Config) *smtp.Server {
|
||||
@@ -284,14 +285,7 @@ type parsedSMTPMessage struct {
|
||||
textBody string
|
||||
htmlBody string
|
||||
date time.Time
|
||||
attachments []*parsedAttachment
|
||||
}
|
||||
|
||||
// parsedAttachment holds an extracted MIME attachment part.
|
||||
type parsedAttachment struct {
|
||||
fileName string
|
||||
contentType string
|
||||
data []byte
|
||||
attachments []*db.Attachment
|
||||
}
|
||||
|
||||
func parseSMTPMessage(data []byte) (*parsedSMTPMessage, error) {
|
||||
@@ -352,10 +346,10 @@ func parseSMTPMessage(data []byte) (*parsedSMTPMessage, error) {
|
||||
log.Printf("SMTP: error reading attachment part: %v", readErr)
|
||||
continue
|
||||
}
|
||||
msg.attachments = append(msg.attachments, &parsedAttachment{
|
||||
fileName: filename,
|
||||
contentType: contentType,
|
||||
data: buf,
|
||||
msg.attachments = append(msg.attachments, &db.Attachment{
|
||||
FileName: filename,
|
||||
ContentType: contentType,
|
||||
FileSize: int64(len(buf)),
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -382,32 +376,7 @@ func (s *smtpSession) saveMessage(userID uint, folder string, parsed *parsedSMTP
|
||||
IsFlagged: false,
|
||||
Date: parsed.date,
|
||||
}
|
||||
if err := s.backend.server.stores.Mails.Create(msg); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
// Persist attachments to disk and link them to the message so that the
|
||||
// Web mail UI can list/download them and quota accounting stays correct.
|
||||
for _, att := range parsed.attachments {
|
||||
relPath, err := s.backend.server.storage.Save(att.fileName, att.data)
|
||||
if err != nil {
|
||||
log.Printf("SMTP: failed to save attachment %s: %v", att.fileName, err)
|
||||
continue
|
||||
}
|
||||
rec := &db.Attachment{
|
||||
MessageID: msg.ID,
|
||||
FileName: att.fileName,
|
||||
FilePath: relPath,
|
||||
ContentType: att.contentType,
|
||||
FileSize: int64(len(att.data)),
|
||||
}
|
||||
if err := s.backend.server.stores.Attachments.Create(rec); err != nil {
|
||||
log.Printf("SMTP: failed to create attachment record: %v", err)
|
||||
continue
|
||||
}
|
||||
_ = s.backend.server.stores.Users.UpdateUsedBytes(userID, rec.FileSize)
|
||||
}
|
||||
return nil
|
||||
return s.backend.server.stores.Mails.Create(msg)
|
||||
}
|
||||
|
||||
// Reset clears the session state for the next message on the same connection.
|
||||
|
||||
@@ -1,115 +0,0 @@
|
||||
package smtp_server
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"fmt"
|
||||
"testing"
|
||||
|
||||
"mail_go/internal/db"
|
||||
"mail_go/internal/storage"
|
||||
"mail_go/internal/store"
|
||||
|
||||
"gorm.io/driver/sqlite"
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
// testMultipartMessage builds an RFC 5322 message with one text part and one
|
||||
// base64 attachment.
|
||||
func testMultipartMessage() []byte {
|
||||
const boundary = "X"
|
||||
return []byte(fmt.Sprintf(
|
||||
"From: sender@example.com\r\n"+
|
||||
"To: rcpt@lmve.net\r\n"+
|
||||
"Subject: with attachment\r\n"+
|
||||
"MIME-Version: 1.0\r\n"+
|
||||
"Content-Type: multipart/mixed; boundary=\"%s\"\r\n"+
|
||||
"\r\n"+
|
||||
"--%s\r\n"+
|
||||
"Content-Type: text/plain; charset=utf-8\r\n"+
|
||||
"\r\n"+
|
||||
"hello body\r\n"+
|
||||
"--%s\r\n"+
|
||||
"Content-Type: text/plain; name=\"test.txt\"\r\n"+
|
||||
"Content-Transfer-Encoding: base64\r\n"+
|
||||
"Content-Disposition: attachment; filename=\"test.txt\"\r\n"+
|
||||
"\r\n"+
|
||||
"aGVsbG8gd29ybGQ=\r\n"+
|
||||
"--%s--\r\n",
|
||||
boundary, boundary, boundary, boundary))
|
||||
}
|
||||
|
||||
func TestParseSMTPMessageExtractsAttachmentData(t *testing.T) {
|
||||
parsed, err := parseSMTPMessage(testMultipartMessage())
|
||||
if err != nil {
|
||||
t.Fatalf("parseSMTPMessage: %v", err)
|
||||
}
|
||||
if parsed.textBody != "hello body" {
|
||||
t.Fatalf("unexpected text body: %q", parsed.textBody)
|
||||
}
|
||||
if len(parsed.attachments) != 1 {
|
||||
t.Fatalf("expected 1 attachment, got %d", len(parsed.attachments))
|
||||
}
|
||||
att := parsed.attachments[0]
|
||||
if att.fileName != "test.txt" {
|
||||
t.Fatalf("unexpected filename: %q", att.fileName)
|
||||
}
|
||||
if string(att.data) != "hello world" {
|
||||
t.Fatalf("unexpected attachment data: %q", att.data)
|
||||
}
|
||||
}
|
||||
|
||||
func TestSaveMessagePersistsAttachments(t *testing.T) {
|
||||
gdb, err := gorm.Open(sqlite.Open(":memory:"), &gorm.Config{})
|
||||
if err != nil {
|
||||
t.Fatalf("open sqlite: %v", err)
|
||||
}
|
||||
if err := gdb.AutoMigrate(&db.User{}, &db.Domain{}, &db.Message{}, &db.Attachment{}, &db.BanEntry{}, &db.OutboundMessage{}); err != nil {
|
||||
t.Fatalf("migrate: %v", err)
|
||||
}
|
||||
stores := store.NewStores(gdb)
|
||||
|
||||
attStorage := storage.NewAttachmentStorage(t.TempDir())
|
||||
srv := &SMTPServer{stores: stores, storage: attStorage}
|
||||
sess := &smtpSession{backend: &smtpBackend{server: srv}}
|
||||
|
||||
data := testMultipartMessage()
|
||||
parsed, err := parseSMTPMessage(data)
|
||||
if err != nil {
|
||||
t.Fatalf("parseSMTPMessage: %v", err)
|
||||
}
|
||||
|
||||
user := &db.User{Username: "rcpt", PasswordHash: "x", DomainID: 0, IsActive: true}
|
||||
if err := stores.Users.Create(user); err != nil {
|
||||
t.Fatalf("create user: %v", err)
|
||||
}
|
||||
|
||||
if err := sess.saveMessage(user.ID, "INBOX", parsed, data, false); err != nil {
|
||||
t.Fatalf("saveMessage: %v", err)
|
||||
}
|
||||
|
||||
msgs, err := stores.Mails.ListAllByUserAndFolder(user.ID, "INBOX")
|
||||
if err != nil || len(msgs) != 1 {
|
||||
t.Fatalf("expected 1 inbox message, got %d (err=%v)", len(msgs), err)
|
||||
}
|
||||
|
||||
atts, err := stores.Attachments.ListByMessage(msgs[0].ID)
|
||||
if err != nil {
|
||||
t.Fatalf("ListByMessage: %v", err)
|
||||
}
|
||||
if len(atts) != 1 {
|
||||
t.Fatalf("expected 1 attachment record, got %d", len(atts))
|
||||
}
|
||||
att := atts[0]
|
||||
if att.FileName != "test.txt" || att.FileSize != int64(len("hello world")) {
|
||||
t.Fatalf("unexpected attachment record: %+v", att)
|
||||
}
|
||||
|
||||
// The file must exist on disk with the original content.
|
||||
content, err := attStorage.Read(att.FilePath)
|
||||
if err != nil {
|
||||
t.Fatalf("read attachment from disk: %v", err)
|
||||
}
|
||||
if !bytes.Equal(content, []byte("hello world")) {
|
||||
t.Fatalf("attachment content mismatch: %q", content)
|
||||
}
|
||||
}
|
||||
@@ -1,127 +0,0 @@
|
||||
// Package tlsutil 提供 TLS 证书热加载:每次 TLS 握手时按需检查
|
||||
// 证书路径与文件内容是否变化,变化则自动重载,证书更新后无需重启
|
||||
// 服务即可生效。
|
||||
package tlsutil
|
||||
|
||||
import (
|
||||
"crypto/tls"
|
||||
"fmt"
|
||||
"os"
|
||||
"sync"
|
||||
"time"
|
||||
)
|
||||
|
||||
// retryInterval 是重载失败后的最小重试间隔,避免证书文件损坏时
|
||||
// 每个握手都重复做无意义的磁盘读取。
|
||||
const retryInterval = 5 * time.Second
|
||||
|
||||
// Source 返回当前应使用的证书路径。路径可能随时间变化(例如管理后台
|
||||
// 一键导入证书后切换到新的域名证书);返回空路径表示暂无可用证书。
|
||||
type Source func() (certPath, keyPath string)
|
||||
|
||||
// Loader 管理一对可热加载的证书。所有方法均并发安全。
|
||||
type Loader struct {
|
||||
mu sync.Mutex
|
||||
source Source
|
||||
certPath string
|
||||
keyPath string
|
||||
cert *tls.Certificate
|
||||
certMod time.Time
|
||||
keyMod time.Time
|
||||
lastTry time.Time
|
||||
logf func(format string, args ...interface{})
|
||||
}
|
||||
|
||||
// NewLoader 立即加载并校验证书,失败返回错误(保持启动时 fail-fast)。
|
||||
// source 为 nil 时证书路径固定不变,仅检测文件内容变化。
|
||||
func NewLoader(certPath, keyPath string, source Source, logf func(string, ...interface{})) (*Loader, error) {
|
||||
if certPath == "" || keyPath == "" {
|
||||
return nil, fmt.Errorf("TLS 证书路径为空")
|
||||
}
|
||||
l := &Loader{
|
||||
source: source,
|
||||
certPath: certPath,
|
||||
keyPath: keyPath,
|
||||
logf: logf,
|
||||
}
|
||||
if err := l.load(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return l, nil
|
||||
}
|
||||
|
||||
// GetCertificate 实现 tls.Config.GetCertificate:
|
||||
// 每次 TLS 握手时检查证书路径与文件是否有变化,有则自动重载;
|
||||
// 重载失败时继续使用上一次成功加载的证书,避免中断现有服务。
|
||||
func (l *Loader) GetCertificate(_ *tls.ClientHelloInfo) (*tls.Certificate, error) {
|
||||
l.mu.Lock()
|
||||
defer l.mu.Unlock()
|
||||
|
||||
certPath, keyPath := l.certPath, l.keyPath
|
||||
if l.source != nil {
|
||||
certPath, keyPath = l.source()
|
||||
}
|
||||
if certPath == "" || keyPath == "" {
|
||||
// 暂无证书可用:继续使用旧证书(若有)
|
||||
return l.current()
|
||||
}
|
||||
|
||||
changed := certPath != l.certPath || keyPath != l.keyPath
|
||||
if !changed {
|
||||
changed = l.filesChanged(certPath, keyPath)
|
||||
}
|
||||
|
||||
// 仅在重载失败后节流(避免证书文件损坏时每个握手都重复读盘);
|
||||
// 成功后清零节流,保证正常的连续更新立即生效。
|
||||
if changed && time.Since(l.lastTry) >= retryInterval {
|
||||
l.lastTry = time.Now()
|
||||
l.certPath, l.keyPath = certPath, keyPath
|
||||
if err := l.load(); err != nil {
|
||||
if l.logf != nil {
|
||||
l.logf("TLS 证书重载失败 (%s, %s): %v,继续使用旧证书", certPath, keyPath, err)
|
||||
}
|
||||
} else {
|
||||
l.lastTry = time.Time{}
|
||||
if l.logf != nil {
|
||||
l.logf("TLS 证书已热加载: %s", certPath)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return l.current()
|
||||
}
|
||||
|
||||
// current 返回当前已加载的证书。
|
||||
func (l *Loader) current() (*tls.Certificate, error) {
|
||||
if l.cert == nil {
|
||||
return nil, fmt.Errorf("TLS 证书不可用")
|
||||
}
|
||||
return l.cert, nil
|
||||
}
|
||||
|
||||
// filesChanged 判断证书/私钥文件自上次加载后是否被修改。
|
||||
// 文件暂时不可读(如正在原子替换)时视为已变化,触发重载尝试。
|
||||
func (l *Loader) filesChanged(certPath, keyPath string) bool {
|
||||
stC, errC := os.Stat(certPath)
|
||||
stK, errK := os.Stat(keyPath)
|
||||
if errC != nil || errK != nil {
|
||||
return true
|
||||
}
|
||||
return !stC.ModTime().Equal(l.certMod) || !stK.ModTime().Equal(l.keyMod)
|
||||
}
|
||||
|
||||
// load 从当前路径加载证书对并记录文件修改时间。
|
||||
func (l *Loader) load() error {
|
||||
cert, err := tls.LoadX509KeyPair(l.certPath, l.keyPath)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if stC, err := os.Stat(l.certPath); err == nil {
|
||||
l.certMod = stC.ModTime()
|
||||
}
|
||||
if stK, err := os.Stat(l.keyPath); err == nil {
|
||||
l.keyMod = stK.ModTime()
|
||||
}
|
||||
l.cert = &cert
|
||||
return nil
|
||||
}
|
||||
@@ -1,241 +0,0 @@
|
||||
package tlsutil
|
||||
|
||||
import (
|
||||
"crypto/rand"
|
||||
"crypto/rsa"
|
||||
"crypto/x509"
|
||||
"crypto/x509/pkix"
|
||||
"encoding/pem"
|
||||
"math/big"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"sync"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
// writeCertPair 生成一对自签名证书并写入文件,返回叶子证书序列号。
|
||||
func writeCertPair(t *testing.T, certPath, keyPath string, serial int64) {
|
||||
t.Helper()
|
||||
|
||||
key, err := rsa.GenerateKey(rand.Reader, 2048)
|
||||
if err != nil {
|
||||
t.Fatalf("生成私钥失败: %v", err)
|
||||
}
|
||||
tmpl := &x509.Certificate{
|
||||
SerialNumber: big.NewInt(serial),
|
||||
Subject: pkix.Name{CommonName: "test"},
|
||||
NotBefore: time.Now().Add(-time.Hour),
|
||||
NotAfter: time.Now().Add(24 * time.Hour),
|
||||
DNSNames: []string{"localhost"},
|
||||
KeyUsage: x509.KeyUsageDigitalSignature | x509.KeyUsageKeyEncipherment,
|
||||
ExtKeyUsage: []x509.ExtKeyUsage{x509.ExtKeyUsageServerAuth},
|
||||
}
|
||||
der, err := x509.CreateCertificate(rand.Reader, tmpl, tmpl, &key.PublicKey, key)
|
||||
if err != nil {
|
||||
t.Fatalf("生成证书失败: %v", err)
|
||||
}
|
||||
|
||||
certPEM := pem.EncodeToMemory(&pem.Block{Type: "CERTIFICATE", Bytes: der})
|
||||
keyPEM := pem.EncodeToMemory(&pem.Block{Type: "RSA PRIVATE KEY", Bytes: x509.MarshalPKCS1PrivateKey(key)})
|
||||
|
||||
if err := os.MkdirAll(filepath.Dir(certPath), 0700); err != nil {
|
||||
t.Fatalf("创建目录失败: %v", err)
|
||||
}
|
||||
if err := os.WriteFile(certPath, certPEM, 0600); err != nil {
|
||||
t.Fatalf("写入证书失败: %v", err)
|
||||
}
|
||||
if err := os.WriteFile(keyPath, keyPEM, 0600); err != nil {
|
||||
t.Fatalf("写入私钥失败: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func leafSerial(t *testing.T, cert *x509.Certificate) *big.Int {
|
||||
t.Helper()
|
||||
return cert.SerialNumber
|
||||
}
|
||||
|
||||
func TestNewLoaderFailsFast(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
certPath := filepath.Join(dir, "cert.pem")
|
||||
keyPath := filepath.Join(dir, "key.pem")
|
||||
os.WriteFile(certPath, []byte("garbage"), 0600)
|
||||
os.WriteFile(keyPath, []byte("garbage"), 0600)
|
||||
|
||||
if _, err := NewLoader(certPath, keyPath, nil, nil); err == nil {
|
||||
t.Fatal("无效证书应返回错误")
|
||||
}
|
||||
}
|
||||
|
||||
func TestReloadOnFileChange(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
certPath := filepath.Join(dir, "cert.pem")
|
||||
keyPath := filepath.Join(dir, "key.pem")
|
||||
|
||||
writeCertPair(t, certPath, keyPath, 1)
|
||||
l, err := NewLoader(certPath, keyPath, nil, nil)
|
||||
if err != nil {
|
||||
t.Fatalf("NewLoader 失败: %v", err)
|
||||
}
|
||||
|
||||
c1, err := l.GetCertificate(nil)
|
||||
if err != nil {
|
||||
t.Fatalf("GetCertificate 失败: %v", err)
|
||||
}
|
||||
if c1.Leaf == nil {
|
||||
if parsed, err := x509.ParseCertificate(c1.Certificate[0]); err == nil {
|
||||
c1.Leaf = parsed
|
||||
}
|
||||
}
|
||||
if leafSerial(t, c1.Leaf).Int64() != 1 {
|
||||
t.Fatalf("初始证书序列号应为 1")
|
||||
}
|
||||
|
||||
// 替换文件内容(模拟证书更新),无需重启
|
||||
time.Sleep(10 * time.Millisecond) // 确保 mtime 变化
|
||||
writeCertPair(t, certPath, keyPath, 2)
|
||||
|
||||
c2, err := l.GetCertificate(nil)
|
||||
if err != nil {
|
||||
t.Fatalf("更新后 GetCertificate 失败: %v", err)
|
||||
}
|
||||
if parsed, err := x509.ParseCertificate(c2.Certificate[0]); err == nil {
|
||||
c2.Leaf = parsed
|
||||
}
|
||||
if leafSerial(t, c2.Leaf).Int64() != 2 {
|
||||
t.Fatal("文件更新后应自动加载新证书(序列号 2)")
|
||||
}
|
||||
}
|
||||
|
||||
func TestStaleCertOnInvalidReload(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
certPath := filepath.Join(dir, "cert.pem")
|
||||
keyPath := filepath.Join(dir, "key.pem")
|
||||
|
||||
writeCertPair(t, certPath, keyPath, 1)
|
||||
l, err := NewLoader(certPath, keyPath, nil, nil)
|
||||
if err != nil {
|
||||
t.Fatalf("NewLoader 失败: %v", err)
|
||||
}
|
||||
|
||||
// 写入损坏的证书:重载失败时应继续使用旧证书
|
||||
time.Sleep(10 * time.Millisecond)
|
||||
os.WriteFile(certPath, []byte("broken"), 0600)
|
||||
|
||||
c, err := l.GetCertificate(nil)
|
||||
if err != nil {
|
||||
t.Fatalf("重载失败时不应返回错误: %v", err)
|
||||
}
|
||||
if parsed, err := x509.ParseCertificate(c.Certificate[0]); err == nil {
|
||||
c.Leaf = parsed
|
||||
}
|
||||
if leafSerial(t, c.Leaf).Int64() != 1 {
|
||||
t.Fatal("重载失败时应继续使用旧证书")
|
||||
}
|
||||
}
|
||||
|
||||
func TestSourcePathSwitch(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
certA := filepath.Join(dir, "a", "cert.pem")
|
||||
keyA := filepath.Join(dir, "a", "key.pem")
|
||||
certB := filepath.Join(dir, "b", "cert.pem")
|
||||
keyB := filepath.Join(dir, "b", "key.pem")
|
||||
writeCertPair(t, certA, keyA, 1)
|
||||
writeCertPair(t, certB, keyB, 2)
|
||||
|
||||
// 初始用 A,source 后续切换到 B(模拟后台导入新域名证书)
|
||||
source := func() (string, string) { return certB, keyB }
|
||||
l, err := NewLoader(certA, keyA, source, nil)
|
||||
if err != nil {
|
||||
t.Fatalf("NewLoader 失败: %v", err)
|
||||
}
|
||||
|
||||
c, err := l.GetCertificate(nil)
|
||||
if err != nil {
|
||||
t.Fatalf("GetCertificate 失败: %v", err)
|
||||
}
|
||||
if parsed, err := x509.ParseCertificate(c.Certificate[0]); err == nil {
|
||||
c.Leaf = parsed
|
||||
}
|
||||
if leafSerial(t, c.Leaf).Int64() != 2 {
|
||||
t.Fatal("source 切换路径后应自动加载新证书")
|
||||
}
|
||||
}
|
||||
|
||||
func TestRapidSuccessiveChanges(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
certPath := filepath.Join(dir, "cert.pem")
|
||||
keyPath := filepath.Join(dir, "key.pem")
|
||||
|
||||
writeCertPair(t, certPath, keyPath, 1)
|
||||
l, err := NewLoader(certPath, keyPath, nil, nil)
|
||||
if err != nil {
|
||||
t.Fatalf("NewLoader 失败: %v", err)
|
||||
}
|
||||
|
||||
serialOf := func() int64 {
|
||||
t.Helper()
|
||||
c, err := l.GetCertificate(nil)
|
||||
if err != nil {
|
||||
t.Fatalf("GetCertificate 失败: %v", err)
|
||||
}
|
||||
parsed, err := x509.ParseCertificate(c.Certificate[0])
|
||||
if err != nil {
|
||||
t.Fatalf("解析证书失败: %v", err)
|
||||
}
|
||||
return parsed.SerialNumber.Int64()
|
||||
}
|
||||
|
||||
// 5 秒内连续两次更新,两次都应立即生效(节流只针对失败重载)
|
||||
time.Sleep(10 * time.Millisecond)
|
||||
writeCertPair(t, certPath, keyPath, 2)
|
||||
if got := serialOf(); got != 2 {
|
||||
t.Fatalf("第一次更新后应加载序列号 2,实际 %d", got)
|
||||
}
|
||||
|
||||
time.Sleep(10 * time.Millisecond)
|
||||
writeCertPair(t, certPath, keyPath, 3)
|
||||
if got := serialOf(); got != 3 {
|
||||
t.Fatalf("第二次快速更新后应立即加载序列号 3,实际 %d", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestConcurrentGetCertificate(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
certPath := filepath.Join(dir, "cert.pem")
|
||||
keyPath := filepath.Join(dir, "key.pem")
|
||||
writeCertPair(t, certPath, keyPath, 1)
|
||||
|
||||
l, err := NewLoader(certPath, keyPath, nil, nil)
|
||||
if err != nil {
|
||||
t.Fatalf("NewLoader 失败: %v", err)
|
||||
}
|
||||
|
||||
var wg sync.WaitGroup
|
||||
stop := make(chan struct{})
|
||||
// 并发读
|
||||
for i := 0; i < 8; i++ {
|
||||
wg.Add(1)
|
||||
go func() {
|
||||
defer wg.Done()
|
||||
for {
|
||||
select {
|
||||
case <-stop:
|
||||
return
|
||||
default:
|
||||
if _, err := l.GetCertificate(nil); err != nil {
|
||||
t.Errorf("并发 GetCertificate 失败: %v", err)
|
||||
return
|
||||
}
|
||||
}
|
||||
}
|
||||
}()
|
||||
}
|
||||
// 同时反复替换证书文件(模拟续期)
|
||||
for i := int64(2); i < 6; i++ {
|
||||
writeCertPair(t, certPath, keyPath, i)
|
||||
time.Sleep(20 * time.Millisecond)
|
||||
}
|
||||
close(stop)
|
||||
wg.Wait()
|
||||
}
|
||||
@@ -5,14 +5,12 @@ import (
|
||||
"fmt"
|
||||
"log"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"mail_go/internal/caddycert"
|
||||
"mail_go/internal/db"
|
||||
"mail_go/internal/dkim"
|
||||
"mail_go/internal/outbound"
|
||||
@@ -25,17 +23,16 @@ import (
|
||||
|
||||
// AdminHandler handles admin-related routes (dashboard, domain/user management).
|
||||
type AdminHandler struct {
|
||||
stores *store.Stores
|
||||
storage *storage.AttachmentStorage
|
||||
tlsDir string
|
||||
caddyDataDir string
|
||||
outbound *outbound.Manager
|
||||
stores *store.Stores
|
||||
storage *storage.AttachmentStorage
|
||||
tlsDir string
|
||||
outbound *outbound.Manager
|
||||
}
|
||||
|
||||
// NewAdminHandler creates a new AdminHandler with the given stores, attachment
|
||||
// storage, TLS directory, Caddy data directory and outbound delivery manager.
|
||||
func NewAdminHandler(stores *store.Stores, attStorage *storage.AttachmentStorage, tlsDir string, caddyDataDir string, ob *outbound.Manager) *AdminHandler {
|
||||
return &AdminHandler{stores: stores, storage: attStorage, tlsDir: tlsDir, caddyDataDir: caddyDataDir, outbound: ob}
|
||||
// storage, TLS directory and outbound delivery manager.
|
||||
func NewAdminHandler(stores *store.Stores, attStorage *storage.AttachmentStorage, tlsDir string, ob *outbound.Manager) *AdminHandler {
|
||||
return &AdminHandler{stores: stores, storage: attStorage, tlsDir: tlsDir, outbound: ob}
|
||||
}
|
||||
|
||||
// Dashboard renders the admin dashboard with summary statistics.
|
||||
@@ -212,16 +209,6 @@ func (h *AdminHandler) EditDomain(c *gin.Context) {
|
||||
}
|
||||
|
||||
currentUser, _ := c.Get("currentUser")
|
||||
|
||||
caddyMsg, caddyMsgType := "", ""
|
||||
if c.Query("caddy_err") != "" {
|
||||
caddyMsg = c.Query("caddy_err")
|
||||
caddyMsgType = "error"
|
||||
} else if c.Query("caddy_ok") == "1" {
|
||||
caddyMsg = "✅ 已从 Caddy 获取证书并保存到域名 TLS 目录,同时已启用该域名的 TLS;证书已热加载,无需重启服务。"
|
||||
caddyMsgType = "success"
|
||||
}
|
||||
|
||||
c.HTML(200, "admin_domain_form", gin.H{
|
||||
"currentUser": currentUser,
|
||||
"activeFolder": "domains",
|
||||
@@ -230,8 +217,6 @@ func (h *AdminHandler) EditDomain(c *gin.Context) {
|
||||
"domain": domain,
|
||||
"tlsPublicCert": readTLSCert(domain.TlsCertPath),
|
||||
"tlsCertConfigured": domain.TlsCertPath != "" && domain.TlsKeyPath != "",
|
||||
"caddyMsg": caddyMsg,
|
||||
"caddyMsgType": caddyMsgType,
|
||||
})
|
||||
}
|
||||
|
||||
@@ -279,78 +264,6 @@ func (h *AdminHandler) UpdateDomain(c *gin.Context) {
|
||||
c.Redirect(http.StatusFound, "/admin/domains")
|
||||
}
|
||||
|
||||
// FetchCaddyCert 尝试从本机 Caddy 的证书存储中获取该域名的证书与私钥,
|
||||
// 保存到 MailGo 的域名 TLS 目录并更新数据库记录。结果通过查询参数回显到
|
||||
// 编辑页面(caddy_ok=1 成功 / caddy_err=<消息> 失败)。
|
||||
func (h *AdminHandler) FetchCaddyCert(c *gin.Context) {
|
||||
id, err := strconv.ParseUint(c.Param("id"), 10, 64)
|
||||
if err != nil {
|
||||
c.String(http.StatusBadRequest, "无效的域名ID")
|
||||
return
|
||||
}
|
||||
|
||||
domain, err := h.stores.Domains.GetByID(uint(id))
|
||||
if err != nil {
|
||||
c.String(http.StatusNotFound, "域名不存在")
|
||||
return
|
||||
}
|
||||
|
||||
editURL := fmt.Sprintf("/admin/domains/%d/edit", domain.ID)
|
||||
fail := func(msg string) {
|
||||
log.Printf("从 Caddy 获取证书失败 domain=%s: %s", domain.Name, msg)
|
||||
c.Redirect(http.StatusFound, editURL+"?caddy_err="+url.QueryEscape(msg))
|
||||
}
|
||||
|
||||
cert, err := caddycert.Fetch(domain.Name, h.caddyCertRoots())
|
||||
if err != nil {
|
||||
fail(fmt.Sprintf("从 Caddy 获取证书失败: %v", err))
|
||||
return
|
||||
}
|
||||
|
||||
// 保存到域名 TLS 目录(与手动上传证书的位置一致)
|
||||
domainTLSDir := filepath.Join(h.tlsDir, strconv.FormatUint(uint64(domain.ID), 10))
|
||||
if err := os.MkdirAll(domainTLSDir, 0700); err != nil {
|
||||
fail(fmt.Sprintf("创建 TLS 证书目录失败: %v", err))
|
||||
return
|
||||
}
|
||||
|
||||
certPath := filepath.Join(domainTLSDir, "cert.pem")
|
||||
keyPath := filepath.Join(domainTLSDir, "key.pem")
|
||||
if err := os.WriteFile(certPath, cert.CertPEM, 0644); err != nil {
|
||||
fail(fmt.Sprintf("保存 TLS 公钥证书失败: %v", err))
|
||||
return
|
||||
}
|
||||
if err := os.WriteFile(keyPath, cert.KeyPEM, 0600); err != nil {
|
||||
fail(fmt.Sprintf("保存 TLS 私钥失败: %v", err))
|
||||
return
|
||||
}
|
||||
|
||||
domain.TlsCertPath = certPath
|
||||
domain.TlsKeyPath = keyPath
|
||||
domain.TlsEnabled = true
|
||||
if err := h.stores.Domains.Update(domain); err != nil {
|
||||
fail(fmt.Sprintf("更新域名记录失败: %v", err))
|
||||
return
|
||||
}
|
||||
|
||||
log.Printf("已从 Caddy 导入域名 %s 的证书 (%s),热加载生效", domain.Name, cert.Source)
|
||||
c.Redirect(http.StatusFound, editURL+"?caddy_ok=1")
|
||||
}
|
||||
|
||||
// caddyCertRoots 返回按优先级排列的证书来源目录:
|
||||
// 1. MailGo 的同步镜像目录 <storage>/tls/caddy —— 由 install.sh 安装的
|
||||
// systemd path 同步任务以 root 权限从 Caddy 证书存储镜像而来,
|
||||
// mail_go 始终可读,证书续期后自动更新;
|
||||
// 2. 配置文件 caddy.data_dir 指定的目录(可选);
|
||||
//
|
||||
// 其余默认位置由 caddycert.Fetch 自行探测。
|
||||
func (h *AdminHandler) caddyCertRoots() []string {
|
||||
return []string{
|
||||
filepath.Join(filepath.Dir(h.tlsDir), "caddy"),
|
||||
h.caddyDataDir,
|
||||
}
|
||||
}
|
||||
|
||||
func readTLSCert(path string) string {
|
||||
if path == "" {
|
||||
return ""
|
||||
@@ -363,20 +276,7 @@ func readTLSCert(path string) string {
|
||||
return string(data)
|
||||
}
|
||||
|
||||
// normalizePEM 统一 PEM 文本的换行为 LF:浏览器提交 textarea 时会把
|
||||
// 换行规范为 CRLF,而证书文件里通常是 LF,直接比较会误判“证书已修改”
|
||||
// (表现为:私钥留空保留现有私钥时仍报“必须同时填写”)。
|
||||
func normalizePEM(s string) string {
|
||||
s = strings.ReplaceAll(s, "\r\n", "\n")
|
||||
s = strings.ReplaceAll(s, "\r", "\n")
|
||||
return s
|
||||
}
|
||||
|
||||
func (h *AdminHandler) handleDomainTLSUpdate(domain *db.Domain, publicCert, privateKey string) error {
|
||||
// 归一化换行,保证与磁盘文件一致,避免表单往返时被误判为已修改
|
||||
publicCert = normalizePEM(strings.TrimSpace(publicCert))
|
||||
privateKey = normalizePEM(strings.TrimSpace(privateKey))
|
||||
|
||||
if !domain.TlsEnabled {
|
||||
return nil
|
||||
}
|
||||
@@ -388,7 +288,7 @@ func (h *AdminHandler) handleDomainTLSUpdate(domain *db.Domain, publicCert, priv
|
||||
}
|
||||
return fmt.Errorf("启用 TLS 时必须填写 TLS 私钥和公钥证书")
|
||||
}
|
||||
if hasExistingCert && privateKey == "" && normalizePEM(strings.TrimSpace(readTLSCert(domain.TlsCertPath))) == publicCert {
|
||||
if hasExistingCert && privateKey == "" && strings.TrimSpace(readTLSCert(domain.TlsCertPath)) == publicCert {
|
||||
return nil
|
||||
}
|
||||
if publicCert == "" || privateKey == "" {
|
||||
|
||||
@@ -1,126 +0,0 @@
|
||||
package handlers
|
||||
|
||||
import (
|
||||
"crypto/rand"
|
||||
"crypto/rsa"
|
||||
"crypto/tls"
|
||||
"crypto/x509"
|
||||
"crypto/x509/pkix"
|
||||
"encoding/pem"
|
||||
"math/big"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"mail_go/internal/db"
|
||||
)
|
||||
|
||||
// makeTestCertPair 生成一对自签名证书(PEM),可选 LF/CRLF 换行。
|
||||
func makeTestCertPair(t *testing.T, lineEnding string) (certPEM, keyPEM string) {
|
||||
t.Helper()
|
||||
|
||||
key, err := rsa.GenerateKey(rand.Reader, 2048)
|
||||
if err != nil {
|
||||
t.Fatalf("生成私钥失败: %v", err)
|
||||
}
|
||||
tmpl := &x509.Certificate{
|
||||
SerialNumber: big.NewInt(1),
|
||||
Subject: pkix.Name{CommonName: "test"},
|
||||
NotBefore: time.Now().Add(-time.Hour),
|
||||
NotAfter: time.Now().Add(24 * time.Hour),
|
||||
DNSNames: []string{"mail.example.com"},
|
||||
KeyUsage: x509.KeyUsageDigitalSignature | x509.KeyUsageKeyEncipherment,
|
||||
ExtKeyUsage: []x509.ExtKeyUsage{x509.ExtKeyUsageServerAuth},
|
||||
}
|
||||
der, err := x509.CreateCertificate(rand.Reader, tmpl, tmpl, &key.PublicKey, key)
|
||||
if err != nil {
|
||||
t.Fatalf("生成证书失败: %v", err)
|
||||
}
|
||||
|
||||
certPEM = string(pem.EncodeToMemory(&pem.Block{Type: "CERTIFICATE", Bytes: der}))
|
||||
if lineEnding == "crlf" {
|
||||
certPEM = strings.ReplaceAll(certPEM, "\n", "\r\n")
|
||||
}
|
||||
keyPEM = string(pem.EncodeToMemory(&pem.Block{Type: "RSA PRIVATE KEY", Bytes: x509.MarshalPKCS1PrivateKey(key)}))
|
||||
if lineEnding == "crlf" {
|
||||
keyPEM = strings.ReplaceAll(keyPEM, "\n", "\r\n")
|
||||
}
|
||||
return certPEM, keyPEM
|
||||
}
|
||||
|
||||
// writeExistingCert 模拟已有证书文件(LF 换行)并返回 domain。
|
||||
func writeExistingCert(t *testing.T, tlsDir string, certPEM, keyPEM string) *db.Domain {
|
||||
t.Helper()
|
||||
dir := filepath.Join(tlsDir, "1")
|
||||
if err := os.MkdirAll(dir, 0700); err != nil {
|
||||
t.Fatalf("创建目录失败: %v", err)
|
||||
}
|
||||
certPath := filepath.Join(dir, "cert.pem")
|
||||
keyPath := filepath.Join(dir, "key.pem")
|
||||
if err := os.WriteFile(certPath, []byte(certPEM+"\n"), 0644); err != nil {
|
||||
t.Fatalf("写入证书失败: %v", err)
|
||||
}
|
||||
if err := os.WriteFile(keyPath, []byte(keyPEM+"\n"), 0600); err != nil {
|
||||
t.Fatalf("写入私钥失败: %v", err)
|
||||
}
|
||||
return &db.Domain{
|
||||
ID: 1,
|
||||
Name: "mail.example.com",
|
||||
TlsEnabled: true,
|
||||
TlsCertPath: certPath,
|
||||
TlsKeyPath: keyPath,
|
||||
}
|
||||
}
|
||||
|
||||
// TestHandleDomainTLSUpdateUnchangedCertCRLF 复现用户报告的 bug:
|
||||
// 浏览器把 textarea 的 LF 换成 CRLF 提交,私钥留空(保留现有私钥),
|
||||
// 证书内容未变,此时保存不应报“必须同时填写”。
|
||||
func TestHandleDomainTLSUpdateUnchangedCertCRLF(t *testing.T) {
|
||||
certLF, keyLF := makeTestCertPair(t, "lf")
|
||||
h := &AdminHandler{tlsDir: t.TempDir()}
|
||||
domain := writeExistingCert(t, h.tlsDir, certLF, keyLF)
|
||||
|
||||
submittedCert := strings.ReplaceAll(certLF, "\n", "\r\n") // 模拟浏览器提交
|
||||
if err := h.handleDomainTLSUpdate(domain, submittedCert, ""); err != nil {
|
||||
t.Fatalf("证书未修改且私钥留空时应保留现有私钥,实际报错: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
// TestHandleDomainTLSUpdateNewPairCRLF 新证书+私钥(CRLF 提交)应正常保存,
|
||||
// 且写入文件为 LF 换行、能组成有效密钥对。
|
||||
func TestHandleDomainTLSUpdateNewPairCRLF(t *testing.T) {
|
||||
certCRLF, keyCRLF := makeTestCertPair(t, "crlf")
|
||||
h := &AdminHandler{tlsDir: t.TempDir()}
|
||||
domain := &db.Domain{ID: 1, Name: "mail.example.com", TlsEnabled: true}
|
||||
|
||||
if err := h.handleDomainTLSUpdate(domain, certCRLF, keyCRLF); err != nil {
|
||||
t.Fatalf("CRLF 提交的新证书应保存成功,实际报错: %v", err)
|
||||
}
|
||||
|
||||
data, err := os.ReadFile(domain.TlsCertPath)
|
||||
if err != nil {
|
||||
t.Fatalf("读取保存的证书失败: %v", err)
|
||||
}
|
||||
if strings.Contains(string(data), "\r") {
|
||||
t.Error("保存的证书文件不应包含 CR")
|
||||
}
|
||||
if _, err := tls.LoadX509KeyPair(domain.TlsCertPath, domain.TlsKeyPath); err != nil {
|
||||
t.Fatalf("保存的证书对无效: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
// TestHandleDomainTLSUpdateChangedCertWithoutKey 证书确实被修改但私钥留空,
|
||||
// 应报“必须同时填写”(防止用不匹配的私钥)。
|
||||
func TestHandleDomainTLSUpdateChangedCertWithoutKey(t *testing.T) {
|
||||
certA, keyA := makeTestCertPair(t, "lf")
|
||||
certB, _ := makeTestCertPair(t, "lf")
|
||||
h := &AdminHandler{tlsDir: t.TempDir()}
|
||||
domain := writeExistingCert(t, h.tlsDir, certA, keyA)
|
||||
|
||||
err := h.handleDomainTLSUpdate(domain, certB, "")
|
||||
if err == nil || !strings.Contains(err.Error(), "必须同时填写") {
|
||||
t.Fatalf("修改证书但私钥留空应报“必须同时填写”,实际: %v", err)
|
||||
}
|
||||
}
|
||||
@@ -56,14 +56,6 @@ func NewMailHandler(stores *store.Stores, attStorage *storage.AttachmentStorage,
|
||||
return &MailHandler{stores: stores, storage: attStorage, outbound: ob}
|
||||
}
|
||||
|
||||
// folderCounts returns sidebar badge counts for the current user.
|
||||
func (h *MailHandler) folderCounts(userID uint) (inboxUnread, draftsTotal, sentTotal int64) {
|
||||
inboxUnread, _ = h.stores.Mails.CountUnread(userID, "INBOX")
|
||||
draftsTotal, _ = h.stores.Mails.CountByUserAndFolder(userID, "Drafts")
|
||||
sentTotal, _ = h.stores.Mails.CountByUserAndFolder(userID, "Sent")
|
||||
return
|
||||
}
|
||||
|
||||
// Inbox renders the inbox page showing all messages in the user's INBOX folder.
|
||||
func (h *MailHandler) Inbox(c *gin.Context) {
|
||||
userID := c.GetUint("userID")
|
||||
@@ -75,7 +67,7 @@ func (h *MailHandler) Inbox(c *gin.Context) {
|
||||
return
|
||||
}
|
||||
|
||||
inboxUnread, draftsTotal, sentTotal := h.folderCounts(userID)
|
||||
unreadCount, _ := h.stores.Mails.CountUnread(userID, "INBOX")
|
||||
|
||||
currentUser, _ := c.Get("currentUser")
|
||||
|
||||
@@ -91,14 +83,12 @@ func (h *MailHandler) Inbox(c *gin.Context) {
|
||||
"currentUser": currentUser,
|
||||
"messages": messages,
|
||||
"total": total,
|
||||
"unreadCount": unreadCount,
|
||||
"page": page,
|
||||
"pageSize": 20,
|
||||
"totalPages": totalPages,
|
||||
"folder": "INBOX",
|
||||
"activeFolder": "inbox",
|
||||
"inboxUnread": inboxUnread,
|
||||
"draftsTotal": draftsTotal,
|
||||
"sentTotal": sentTotal,
|
||||
})
|
||||
}
|
||||
|
||||
@@ -133,16 +123,12 @@ func (h *MailHandler) View(c *gin.Context) {
|
||||
}
|
||||
|
||||
currentUser, _ := c.Get("currentUser")
|
||||
inboxUnread, draftsTotal, sentTotal := h.folderCounts(userID)
|
||||
|
||||
c.HTML(200, "view", gin.H{
|
||||
"currentUser": currentUser,
|
||||
"message": msg,
|
||||
"attachments": attachments,
|
||||
"activeFolder": resolveActiveFolder(msg.Folder),
|
||||
"inboxUnread": inboxUnread,
|
||||
"draftsTotal": draftsTotal,
|
||||
"sentTotal": sentTotal,
|
||||
})
|
||||
}
|
||||
|
||||
@@ -160,8 +146,6 @@ func (h *MailHandler) Compose(c *gin.Context) {
|
||||
quotaBytes = user.QuotaBytes
|
||||
}
|
||||
|
||||
inboxUnread, draftsTotal, sentTotal := h.folderCounts(userID)
|
||||
|
||||
c.HTML(200, "compose", gin.H{
|
||||
"currentUser": currentUser,
|
||||
"activeFolder": "compose",
|
||||
@@ -171,9 +155,6 @@ func (h *MailHandler) Compose(c *gin.Context) {
|
||||
"bodyContent": "",
|
||||
"usedBytes": usedBytes,
|
||||
"quotaBytes": quotaBytes,
|
||||
"inboxUnread": inboxUnread,
|
||||
"draftsTotal": draftsTotal,
|
||||
"sentTotal": sentTotal,
|
||||
})
|
||||
}
|
||||
|
||||
@@ -514,7 +495,6 @@ func (h *MailHandler) Sent(c *gin.Context) {
|
||||
}
|
||||
|
||||
currentUser, _ := c.Get("currentUser")
|
||||
inboxUnread, draftsTotal, sentTotal := h.folderCounts(userID)
|
||||
|
||||
totalPages := int(total) / 20
|
||||
if int(total)%20 > 0 {
|
||||
@@ -533,9 +513,6 @@ func (h *MailHandler) Sent(c *gin.Context) {
|
||||
"totalPages": totalPages,
|
||||
"folder": "Sent",
|
||||
"activeFolder": "sent",
|
||||
"inboxUnread": inboxUnread,
|
||||
"draftsTotal": draftsTotal,
|
||||
"sentTotal": sentTotal,
|
||||
})
|
||||
}
|
||||
|
||||
@@ -653,7 +630,6 @@ func (h *MailHandler) Drafts(c *gin.Context) {
|
||||
}
|
||||
|
||||
currentUser, _ := c.Get("currentUser")
|
||||
inboxUnread, draftsTotal, sentTotal := h.folderCounts(userID)
|
||||
|
||||
totalPages := int(total) / 20
|
||||
if int(total)%20 > 0 {
|
||||
@@ -672,25 +648,17 @@ func (h *MailHandler) Drafts(c *gin.Context) {
|
||||
"totalPages": totalPages,
|
||||
"folder": "Drafts",
|
||||
"activeFolder": "drafts",
|
||||
"inboxUnread": inboxUnread,
|
||||
"draftsTotal": draftsTotal,
|
||||
"sentTotal": sentTotal,
|
||||
})
|
||||
}
|
||||
|
||||
// Settings renders the user settings page.
|
||||
func (h *MailHandler) Settings(c *gin.Context) {
|
||||
currentUser, _ := c.Get("currentUser")
|
||||
userID := c.GetUint("userID")
|
||||
inboxUnread, draftsTotal, sentTotal := h.folderCounts(userID)
|
||||
c.HTML(200, "settings", gin.H{
|
||||
"currentUser": currentUser,
|
||||
"activeFolder": "settings",
|
||||
"error": "",
|
||||
"success": "",
|
||||
"inboxUnread": inboxUnread,
|
||||
"draftsTotal": draftsTotal,
|
||||
"sentTotal": sentTotal,
|
||||
})
|
||||
}
|
||||
|
||||
|
||||
@@ -1,92 +0,0 @@
|
||||
package web
|
||||
|
||||
// Temporary render test used to validate the rewritten frontend templates.
|
||||
// Renders every page template with realistic dummy data and writes the
|
||||
// output to /tmp/mailgo_preview for visual verification.
|
||||
|
||||
import (
|
||||
"html/template"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"mail_go/internal/db"
|
||||
)
|
||||
|
||||
func TestRenderAllPages(t *testing.T) {
|
||||
wd, err := os.Getwd()
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
tmpl := template.Must(template.New("").Funcs(templateFuncs()).ParseGlob(filepath.Join(wd, "templates", "*.html")))
|
||||
template.Must(tmpl.ParseGlob(filepath.Join(wd, "templates", "admin", "*.html")))
|
||||
|
||||
now := time.Now()
|
||||
user := &db.User{
|
||||
ID: 1,
|
||||
Username: "admin",
|
||||
IsAdmin: true,
|
||||
Domain: db.Domain{Name: "lmve.net"},
|
||||
UsedBytes: 5 * 1024 * 1024,
|
||||
QuotaBytes: 5 * 1024 * 1024 * 1024,
|
||||
}
|
||||
|
||||
messages := []db.Message{
|
||||
{ID: 1, Folder: "INBOX", FromAddr: "=?UTF-8?B?5byg5LiJ?= <zhangsan@lmve.net>", ToAddr: "admin@lmve.net", Subject: "邮件系统部署完成通知", TextBody: "您好!您的 MailGo 邮件系统已成功部署,本邮件为测试邮件。", Date: now, IsRead: false},
|
||||
{ID: 2, Folder: "INBOX", FromAddr: "alice@example.com", ToAddr: "admin@lmve.net", Subject: "Re: 项目进度同步", TextBody: "好的,我们下周一上午十点开会同步一下进度。", Date: now.Add(-3 * time.Hour), IsRead: true},
|
||||
{ID: 3, Folder: "INBOX", FromAddr: "=?UTF-8?B?6ZmI5rKz?= <wangwu@lmve.net>", ToAddr: "admin@lmve.net", Subject: "服务器巡检报告(8 月)", TextBody: "本月巡检完成,磁盘使用率 62%,内存使用正常。", Date: now.Add(-48 * time.Hour), IsRead: false},
|
||||
{ID: 4, Folder: "INBOX", FromAddr: "bob@other.com", ToAddr: "admin@lmve.net", Subject: "Newsletter #42", TextBody: "这是本周的资讯摘要,共 5 篇文章。", Date: now.Add(-10 * 24 * time.Hour), IsRead: true},
|
||||
{ID: 5, Folder: "INBOX", FromAddr: "=?UTF-8?B?6ZmI5rKz?= <wangwu@lmve.net>", ToAddr: "admin@lmve.net", Subject: "DNS 记录更新", TextBody: "已按文档更新 SPF 与 DKIM 记录,请验证。", Date: now.Add(-100 * 24 * time.Hour), IsRead: true},
|
||||
}
|
||||
|
||||
attachments := []db.Attachment{
|
||||
{ID: 1, FileName: "部署文档.pdf", FileSize: 1024 * 1024},
|
||||
{ID: 2, FileName: "logo.png", FileSize: 128 * 1024},
|
||||
}
|
||||
|
||||
cases := []struct {
|
||||
name string
|
||||
data ginH
|
||||
}{
|
||||
{"login", ginH{"error": ""}},
|
||||
{"banned", ginH{"entry": &db.BanEntry{IPAddress: "1.2.3.4", Reason: "登录失败次数过多", FailCount: 8, ExpiresAt: now.Add(20 * time.Minute)}}},
|
||||
{"inbox", ginH{"currentUser": user, "messages": messages, "total": 5, "page": 1, "totalPages": 1, "activeFolder": "inbox", "inboxUnread": int64(2), "draftsTotal": int64(1), "sentTotal": int64(3)}},
|
||||
{"drafts", ginH{"currentUser": user, "messages": messages, "total": 1, "page": 1, "totalPages": 1, "activeFolder": "drafts", "inboxUnread": int64(2), "draftsTotal": int64(1), "sentTotal": int64(3)}},
|
||||
{"sent", ginH{"currentUser": user, "messages": messages, "total": 3, "page": 1, "totalPages": 1, "activeFolder": "sent", "inboxUnread": int64(2), "draftsTotal": int64(1), "sentTotal": int64(3)}},
|
||||
{"view", ginH{
|
||||
"currentUser": user, "activeFolder": "inbox",
|
||||
"message": &db.Message{ID: 1, Folder: "INBOX", FromAddr: "=?UTF-8?B?5byg5LiJ?= <zhangsan@lmve.net>", ToAddr: "admin@lmve.net", Subject: "邮件系统部署完成通知", TextBody: "您好!您的 MailGo 邮件系统已成功部署。", HtmlBody: "", Date: now, IsRead: false},
|
||||
"attachments": attachments, "inboxUnread": int64(2), "draftsTotal": int64(1), "sentTotal": int64(3),
|
||||
}},
|
||||
{"compose", ginH{
|
||||
"currentUser": user, "activeFolder": "compose", "error": "",
|
||||
"to": "zhangsan@lmve.net", "subject": "Re: 邮件系统部署完成通知", "bodyContent": "",
|
||||
"usedBytes": int64(5 * 1024 * 1024), "quotaBytes": int64(5 * 1024 * 1024 * 1024),
|
||||
"inboxUnread": int64(2), "draftsTotal": int64(1), "sentTotal": int64(3),
|
||||
}},
|
||||
{"settings", ginH{"currentUser": user, "activeFolder": "settings", "error": "", "success": "", "inboxUnread": int64(2), "draftsTotal": int64(1), "sentTotal": int64(3)}},
|
||||
{"admin_dashboard", ginH{"currentUser": user, "activeFolder": "admin", "domainCount": 2, "userCount": 5, "totalMails": 100, "banCount": 1, "inboxCount": 50, "sentCount": 30, "draftsCount": 10, "trashCount": 5, "inboxSize": int64(1024), "sentSize": int64(512), "totalSize": int64(2048), "todayReceived": 3, "todaySent": 2, "weekReceived": 20, "weekSent": 15}},
|
||||
}
|
||||
|
||||
outDir := os.Getenv("MAILGO_PREVIEW_DIR")
|
||||
if outDir == "" {
|
||||
outDir = filepath.Join(os.TempDir(), "mailgo_preview")
|
||||
}
|
||||
os.MkdirAll(outDir, 0755)
|
||||
|
||||
for _, tc := range cases {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
var buf strings.Builder
|
||||
if err := tmpl.ExecuteTemplate(&buf, tc.name, tc.data); err != nil {
|
||||
t.Fatalf("render %s: %v", tc.name, err)
|
||||
}
|
||||
os.WriteFile(filepath.Join(outDir, tc.name+".html"), []byte(buf.String()), 0644)
|
||||
t.Logf("%s -> %d bytes", tc.name, buf.Len())
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// ginH mimics gin.H so the test does not need the gin dependency surface.
|
||||
type ginH map[string]interface{}
|
||||
+18
-102
@@ -8,8 +8,6 @@ import (
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"time"
|
||||
"unicode/utf8"
|
||||
|
||||
"mail_go/config"
|
||||
"mail_go/internal/mailutil"
|
||||
@@ -40,15 +38,14 @@ func formatBytes(b int64) string {
|
||||
|
||||
// WebServer wraps the Gin engine and its dependencies.
|
||||
type WebServer struct {
|
||||
engine *gin.Engine
|
||||
stores *store.Stores
|
||||
storage *storage.AttachmentStorage
|
||||
cfg config.WebConfig
|
||||
storageCfg config.StorageConfig
|
||||
authCfg config.AuthConfig
|
||||
banCfg config.BanConfig
|
||||
caddyDataDir string
|
||||
outbound *outbound.Manager
|
||||
engine *gin.Engine
|
||||
stores *store.Stores
|
||||
storage *storage.AttachmentStorage
|
||||
cfg config.WebConfig
|
||||
storageCfg config.StorageConfig
|
||||
authCfg config.AuthConfig
|
||||
banCfg config.BanConfig
|
||||
outbound *outbound.Manager
|
||||
}
|
||||
|
||||
// templateFuncs returns custom template functions for rendering.
|
||||
@@ -82,91 +79,12 @@ func templateFuncs() template.FuncMap {
|
||||
"decodeHeader": func(s string) string {
|
||||
return mailutil.DecodeRFC2047(s)
|
||||
},
|
||||
// mailName 从 "Name <addr>" 中提取显示名;无显示名时退回邮箱地址。
|
||||
"mailName": mailName,
|
||||
// mailEmail 从 "Name <addr>" 中提取邮箱地址部分。
|
||||
"mailEmail": mailEmail,
|
||||
// initial 返回字符串的首字符(用于头像占位)。
|
||||
"initial": initial,
|
||||
// truncate 折叠空白并截断到 n 个字符(用于列表摘要)。
|
||||
"truncate": truncate,
|
||||
// shortDate 按 QQ 邮箱习惯格式化:今天显示 HH:mm,今年显示 MM-DD,更早显示 YYYY-MM-DD。
|
||||
"shortDate": shortDate,
|
||||
// avatarStyle 根据字符串哈希生成头像背景/前景色。
|
||||
"avatarStyle": avatarStyle,
|
||||
}
|
||||
}
|
||||
|
||||
// mailName extracts the display name from an RFC 5322 address.
|
||||
func mailName(s string) string {
|
||||
s = strings.TrimSpace(s)
|
||||
if i := strings.IndexByte(s, '<'); i >= 0 {
|
||||
name := strings.Trim(strings.TrimSpace(s[:i]), `"' `)
|
||||
if name != "" {
|
||||
return name
|
||||
}
|
||||
if j := strings.IndexByte(s, '>'); j > i {
|
||||
return s[i+1 : j]
|
||||
}
|
||||
}
|
||||
return s
|
||||
}
|
||||
|
||||
// mailEmail extracts the bare email address from an RFC 5322 address.
|
||||
func mailEmail(s string) string {
|
||||
if i := strings.IndexByte(s, '<'); i >= 0 {
|
||||
if j := strings.IndexByte(s, '>'); j > i {
|
||||
return s[i+1 : j]
|
||||
}
|
||||
}
|
||||
return strings.TrimSpace(s)
|
||||
}
|
||||
|
||||
// initial returns the first rune of a string, upper-cased.
|
||||
func initial(s string) string {
|
||||
s = strings.TrimSpace(s)
|
||||
if s == "" {
|
||||
return "?"
|
||||
}
|
||||
r, _ := utf8.DecodeRuneInString(s)
|
||||
return strings.ToUpper(string(r))
|
||||
}
|
||||
|
||||
// truncate collapses whitespace and cuts the string to n runes.
|
||||
func truncate(s string, n int) string {
|
||||
s = strings.Join(strings.Fields(s), " ")
|
||||
r := []rune(s)
|
||||
if len(r) <= n {
|
||||
return s
|
||||
}
|
||||
return string(r[:n]) + "…"
|
||||
}
|
||||
|
||||
// shortDate formats a time like QQ Mail does: today -> HH:mm,
|
||||
// this year -> MM-DD, otherwise -> YYYY-MM-DD.
|
||||
func shortDate(t time.Time) string {
|
||||
now := time.Now()
|
||||
if t.Year() == now.Year() && t.YearDay() == now.YearDay() {
|
||||
return t.Format("15:04")
|
||||
}
|
||||
if t.Year() == now.Year() {
|
||||
return t.Format("01-02")
|
||||
}
|
||||
return t.Format("2006-01-02")
|
||||
}
|
||||
|
||||
// avatarStyle returns inline CSS colors derived from a string hash.
|
||||
func avatarStyle(s string) string {
|
||||
h := 0
|
||||
for _, r := range s {
|
||||
h = (h*31 + int(r)) % 360
|
||||
}
|
||||
return fmt.Sprintf("background:hsl(%d,78%%,92%%);color:hsl(%d,72%%,36%%)", h, h)
|
||||
}
|
||||
|
||||
// NewWebServer creates a new WebServer, initializes the Gin engine,
|
||||
// configures sessions, middleware, and registers all routes.
|
||||
func NewWebServer(cfg config.WebConfig, stores *store.Stores, attStorage *storage.AttachmentStorage, storageCfg config.StorageConfig, authCfg config.AuthConfig, banCfg config.BanConfig, caddyCfg config.CaddyConfig, ob *outbound.Manager) *WebServer {
|
||||
func NewWebServer(cfg config.WebConfig, stores *store.Stores, attStorage *storage.AttachmentStorage, storageCfg config.StorageConfig, authCfg config.AuthConfig, banCfg config.BanConfig, ob *outbound.Manager) *WebServer {
|
||||
gin.SetMode(gin.ReleaseMode)
|
||||
engine := gin.New()
|
||||
engine.Use(gin.Logger())
|
||||
@@ -189,15 +107,14 @@ func NewWebServer(cfg config.WebConfig, stores *store.Stores, attStorage *storag
|
||||
engine.SetHTMLTemplate(tmpl)
|
||||
|
||||
ws := &WebServer{
|
||||
engine: engine,
|
||||
stores: stores,
|
||||
storage: attStorage,
|
||||
cfg: cfg,
|
||||
storageCfg: storageCfg,
|
||||
authCfg: authCfg,
|
||||
banCfg: banCfg,
|
||||
caddyDataDir: caddyCfg.DataDir,
|
||||
outbound: ob,
|
||||
engine: engine,
|
||||
stores: stores,
|
||||
storage: attStorage,
|
||||
cfg: cfg,
|
||||
storageCfg: storageCfg,
|
||||
authCfg: authCfg,
|
||||
banCfg: banCfg,
|
||||
outbound: ob,
|
||||
}
|
||||
|
||||
ws.registerRoutes()
|
||||
@@ -208,7 +125,7 @@ func NewWebServer(cfg config.WebConfig, stores *store.Stores, attStorage *storag
|
||||
func (ws *WebServer) registerRoutes() {
|
||||
authHandler := handlers.NewAuthHandler(ws.stores, ws.authCfg, ws.banCfg)
|
||||
mailHandler := handlers.NewMailHandler(ws.stores, ws.storage, ws.outbound)
|
||||
adminHandler := handlers.NewAdminHandler(ws.stores, ws.storage, filepath.Join(ws.storageCfg.BaseDir, "tls", "domains"), ws.caddyDataDir, ws.outbound)
|
||||
adminHandler := handlers.NewAdminHandler(ws.stores, ws.storage, filepath.Join(ws.storageCfg.BaseDir, "tls", "domains"), ws.outbound)
|
||||
|
||||
// Apply BanMiddleware globally before public routes
|
||||
ws.engine.Use(middleware.BanMiddleware(ws.stores))
|
||||
@@ -258,7 +175,6 @@ func (ws *WebServer) registerRoutes() {
|
||||
admin.GET("/domains/:id/edit", adminHandler.EditDomain)
|
||||
admin.POST("/domains/:id", adminHandler.UpdateDomain)
|
||||
admin.POST("/domains/:id/delete", adminHandler.DeleteDomain)
|
||||
admin.POST("/domains/:id/fetch-caddy-cert", adminHandler.FetchCaddyCert)
|
||||
admin.GET("/domains/:id/dns", adminHandler.DNSHint)
|
||||
admin.GET("/users", adminHandler.ListUsers)
|
||||
admin.GET("/users/new", adminHandler.NewUser)
|
||||
|
||||
@@ -3,7 +3,7 @@
|
||||
<html lang="zh-CN">
|
||||
<head>
|
||||
<meta charset="UTF-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0, viewport-fit=cover">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||||
<title>IP黑名单 - MailGo</title>
|
||||
{{template "styles" .}}
|
||||
</head>
|
||||
|
||||
@@ -3,7 +3,7 @@
|
||||
<html lang="zh-CN">
|
||||
<head>
|
||||
<meta charset="UTF-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0, viewport-fit=cover">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||||
<title>管理后台 - MailGo</title>
|
||||
{{template "styles" .}}
|
||||
</head>
|
||||
|
||||
@@ -3,7 +3,7 @@
|
||||
<html lang="zh-CN">
|
||||
<head>
|
||||
<meta charset="UTF-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0, viewport-fit=cover">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||||
<title>DNS配置 - MailGo</title>
|
||||
{{template "styles" .}}
|
||||
</head>
|
||||
|
||||
@@ -3,7 +3,7 @@
|
||||
<html lang="zh-CN">
|
||||
<head>
|
||||
<meta charset="UTF-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0, viewport-fit=cover">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||||
<title>{{if .isEdit}}编辑域名{{else}}新增域名{{end}} - MailGo</title>
|
||||
{{template "styles" .}}
|
||||
</head>
|
||||
@@ -24,7 +24,6 @@
|
||||
<div class="card">
|
||||
<h2 style="margin-bottom:16px;">{{if .isEdit}}编辑域名{{else}}新增域名{{end}}</h2>
|
||||
{{if .error}}<div class="alert alert-error">{{.error}}</div>{{end}}
|
||||
{{if .caddyMsg}}<div class="alert {{if eq .caddyMsgType "success"}}alert-success{{else}}alert-error{{end}}">{{.caddyMsg}}</div>{{end}}
|
||||
<form method="POST" action="{{if .isEdit}}/admin/domains/{{.domain.ID}}{{else}}/admin/domains{{end}}">
|
||||
<div class="form-group">
|
||||
<label>域名</label>
|
||||
@@ -64,40 +63,12 @@
|
||||
<label>TLS 公钥证书 PEM</label>
|
||||
<textarea name="tls_public_cert" rows="8" placeholder="-----BEGIN CERTIFICATE----- ... -----END CERTIFICATE-----" style="font-family:monospace;">{{.tlsPublicCert}}</textarea>
|
||||
{{if .tlsCertConfigured}}
|
||||
<p style="color:#27ae60;font-size:12px;margin-top:4px;">✅ TLS 证书已配置;上传新证书后自动热加载生效。</p>
|
||||
<p style="color:#27ae60;font-size:12px;margin-top:4px;">✅ TLS 证书已配置;上传新证书后需重启服务生效。</p>
|
||||
{{else}}
|
||||
<p style="color:#e67e22;font-size:12px;margin-top:4px;">⚠️ TLS 证书未配置,启用 TLS 时必须同时填写私钥和证书。</p>
|
||||
{{end}}
|
||||
</div>
|
||||
</div>
|
||||
<div class="form-group" style="margin-top:4px;">
|
||||
<label>从 Caddy 获取证书</label>
|
||||
<p style="color:#7f8c8d;font-size:12px;margin-top:2px;margin-bottom:8px;">若该域名已由本机 Caddy 托管 HTTPS(自动签发证书),可一键导入其证书与私钥,并自动启用 TLS;证书热加载,无需重启服务。</p>
|
||||
<button type="button" class="btn" id="btn_fetch_caddy" onclick="fetchCaddyCert()" style="background:#2e86de;color:#fff;">🔒 从 Caddy 获取证书</button>
|
||||
<span id="caddy_fetch_msg" style="margin-left:10px;font-size:12px;color:#7f8c8d;"></span>
|
||||
<script>
|
||||
async function fetchCaddyCert() {
|
||||
var btn = document.getElementById('btn_fetch_caddy');
|
||||
var msg = document.getElementById('caddy_fetch_msg');
|
||||
btn.disabled = true;
|
||||
var oldText = btn.textContent;
|
||||
btn.textContent = '获取中…';
|
||||
msg.textContent = '';
|
||||
try {
|
||||
var resp = await fetch('/admin/domains/{{.domain.ID}}/fetch-caddy-cert', { method: 'POST' });
|
||||
if (resp.redirected) {
|
||||
window.location.href = resp.url;
|
||||
return;
|
||||
}
|
||||
msg.textContent = '获取失败: ' + await resp.text();
|
||||
} catch (e) {
|
||||
msg.textContent = '请求失败: ' + e;
|
||||
}
|
||||
btn.disabled = false;
|
||||
btn.textContent = oldText;
|
||||
}
|
||||
</script>
|
||||
</div>
|
||||
{{end}}
|
||||
<script>
|
||||
function togglePorts() {
|
||||
|
||||
@@ -3,7 +3,7 @@
|
||||
<html lang="zh-CN">
|
||||
<head>
|
||||
<meta charset="UTF-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0, viewport-fit=cover">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||||
<title>域名管理 - MailGo</title>
|
||||
{{template "styles" .}}
|
||||
</head>
|
||||
|
||||
@@ -3,7 +3,7 @@
|
||||
<html lang="zh-CN">
|
||||
<head>
|
||||
<meta charset="UTF-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0, viewport-fit=cover">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||||
<title>查看邮件 - MailGo 管理后台</title>
|
||||
{{template "styles" .}}
|
||||
<style>
|
||||
|
||||
@@ -3,7 +3,7 @@
|
||||
<html lang="zh-CN">
|
||||
<head>
|
||||
<meta charset="UTF-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0, viewport-fit=cover">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||||
<title>所有邮件 - MailGo</title>
|
||||
{{template "styles" .}}
|
||||
</head>
|
||||
|
||||
@@ -3,7 +3,7 @@
|
||||
<html lang="zh-CN">
|
||||
<head>
|
||||
<meta charset="UTF-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0, viewport-fit=cover">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||||
<title>外发队列 - MailGo</title>
|
||||
{{template "styles" .}}
|
||||
</head>
|
||||
|
||||
@@ -3,7 +3,7 @@
|
||||
<html lang="zh-CN">
|
||||
<head>
|
||||
<meta charset="UTF-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0, viewport-fit=cover">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||||
<title>{{if .isEdit}}编辑用户{{else}}新增用户{{end}} - MailGo</title>
|
||||
{{template "styles" .}}
|
||||
</head>
|
||||
|
||||
@@ -3,7 +3,7 @@
|
||||
<html lang="zh-CN">
|
||||
<head>
|
||||
<meta charset="UTF-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0, viewport-fit=cover">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||||
<title>用户管理 - MailGo</title>
|
||||
{{template "styles" .}}
|
||||
</head>
|
||||
|
||||
@@ -3,40 +3,21 @@
|
||||
<html lang="zh-CN">
|
||||
<head>
|
||||
<meta charset="UTF-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0, viewport-fit=cover">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||||
<title>访问被禁止 - MailGo</title>
|
||||
<style>
|
||||
* { margin: 0; padding: 0; box-sizing: border-box; }
|
||||
body {
|
||||
font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", "PingFang SC",
|
||||
"Hiragino Sans GB", "Microsoft YaHei", sans-serif;
|
||||
background: linear-gradient(165deg, #fdecec 0%, #f6f8fc 55%, #eaf2ff 100%);
|
||||
color: #1f2329; display: flex; justify-content: center; align-items: center; min-height: 100vh;
|
||||
}
|
||||
.banned-card {
|
||||
background: #fff; border-radius: 14px;
|
||||
box-shadow: 0 10px 40px rgba(227, 77, 89, 0.10);
|
||||
padding: 48px; text-align: center; max-width: 480px; width: 100%;
|
||||
}
|
||||
.banned-icon {
|
||||
width: 72px; height: 72px; margin: 0 auto 18px; border-radius: 50%;
|
||||
background: #fde8e8; display: flex; align-items: center; justify-content: center;
|
||||
font-size: 34px;
|
||||
}
|
||||
h1 { font-size: 22px; color: #e34d59; margin-bottom: 12px; }
|
||||
p { color: #646a73; line-height: 1.7; margin-bottom: 8px; font-size: 14px; }
|
||||
.detail {
|
||||
background: #f8f9fb; border-radius: 10px; padding: 16px 18px;
|
||||
margin: 18px 0; text-align: left;
|
||||
}
|
||||
.detail-row { display: flex; justify-content: space-between; padding: 7px 0; border-bottom: 1px solid #f0f1f3; }
|
||||
body { font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif; background: #f5f5f5; color: #333; display: flex; justify-content: center; align-items: center; min-height: 100vh; }
|
||||
.banned-card { background: #fff; border-radius: 12px; box-shadow: 0 4px 12px rgba(0,0,0,0.1); padding: 48px; text-align: center; max-width: 480px; width: 100%; }
|
||||
.banned-icon { font-size: 64px; margin-bottom: 16px; }
|
||||
h1 { font-size: 24px; color: #c0392b; margin-bottom: 12px; }
|
||||
p { color: #7f8c8d; line-height: 1.6; margin-bottom: 8px; }
|
||||
.detail { background: #f8f9fa; border-radius: 6px; padding: 16px; margin: 16px 0; text-align: left; }
|
||||
.detail-row { display: flex; justify-content: space-between; padding: 6px 0; border-bottom: 1px solid #eee; }
|
||||
.detail-row:last-child { border-bottom: none; }
|
||||
.detail-label { color: #8f959e; font-size: 13px; }
|
||||
.detail-value { color: #1f2329; font-weight: 600; font-size: 13px; }
|
||||
.back-link {
|
||||
display: inline-block; margin-top: 22px; color: #1677ff;
|
||||
text-decoration: none; font-size: 14px;
|
||||
}
|
||||
.detail-label { color: #7f8c8d; font-size: 13px; }
|
||||
.detail-value { color: #2c3e50; font-weight: 600; font-size: 13px; }
|
||||
.back-link { display: inline-block; margin-top: 20px; color: #3498db; text-decoration: none; }
|
||||
.back-link:hover { text-decoration: underline; }
|
||||
</style>
|
||||
</head>
|
||||
|
||||
@@ -1,491 +1,66 @@
|
||||
{{define "styles"}}
|
||||
<style>
|
||||
/* ===== MailGo 设计系统(参考 QQ 邮箱布局) ===== */
|
||||
:root {
|
||||
--primary: #1677ff;
|
||||
--primary-hover: #0e5fd8;
|
||||
--primary-soft: #e8f1ff;
|
||||
--orange: #ff9500;
|
||||
--orange-hover: #f08800;
|
||||
--danger: #e34d59;
|
||||
--danger-soft: #fde8e8;
|
||||
--success: #34a853;
|
||||
--success-soft: #e6f7ec;
|
||||
--sidebar-bg: #f6f8fc;
|
||||
--topbar-h: 56px;
|
||||
--border: #e5e6eb;
|
||||
--border-light: #f0f1f3;
|
||||
--text: #1f2329;
|
||||
--text-2: #646a73;
|
||||
--text-3: #8f959e;
|
||||
--radius: 8px;
|
||||
}
|
||||
* { margin: 0; padding: 0; box-sizing: border-box; }
|
||||
body {
|
||||
font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", "PingFang SC",
|
||||
"Hiragino Sans GB", "Microsoft YaHei", sans-serif;
|
||||
background: #f6f8fc; color: var(--text); font-size: 14px;
|
||||
}
|
||||
a { text-decoration: none; color: inherit; }
|
||||
ul { list-style: none; }
|
||||
input, textarea, select, button { font-family: inherit; }
|
||||
input[type="checkbox"] { width: 15px; height: 15px; accent-color: var(--primary); cursor: pointer; flex-shrink: 0; }
|
||||
svg { flex-shrink: 0; }
|
||||
a, button { touch-action: manipulation; }
|
||||
|
||||
/* ---------- 顶部导航栏 ---------- */
|
||||
.topbar {
|
||||
position: fixed; top: 0; left: 0; right: 0; height: var(--topbar-h);
|
||||
background: #fff; border-bottom: 1px solid var(--border);
|
||||
display: flex; align-items: center; gap: 28px; padding: 0 20px; z-index: 100;
|
||||
}
|
||||
.logo { display: flex; align-items: center; gap: 9px; }
|
||||
.logo-icon {
|
||||
width: 34px; height: 34px; border-radius: 9px; color: #fff; font-size: 17px;
|
||||
background: linear-gradient(135deg, #1677ff, #4aa3ff);
|
||||
display: inline-flex; align-items: center; justify-content: center;
|
||||
box-shadow: 0 2px 6px rgba(22, 119, 255, 0.35);
|
||||
}
|
||||
.logo-text { font-size: 19px; font-weight: 700; color: var(--primary); letter-spacing: 0.5px; }
|
||||
.logo-text em { font-style: normal; font-weight: 400; font-size: 13px; color: var(--text-2); margin-left: 3px; }
|
||||
.topbar-search {
|
||||
flex: 0 1 340px; height: 34px; display: none; align-items: center; gap: 8px;
|
||||
background: #f2f3f5; border: 1px solid transparent; border-radius: 17px;
|
||||
padding: 0 14px; color: var(--text-3);
|
||||
}
|
||||
body.page-list .topbar-search { display: flex; }
|
||||
.topbar-search:focus-within { background: #fff; border-color: var(--primary); box-shadow: 0 0 0 3px rgba(22, 119, 255, 0.12); }
|
||||
.topbar-search input { border: none; outline: none; background: transparent; flex: 1; font-size: 13px; color: var(--text); }
|
||||
.topbar-search input::placeholder { color: var(--text-3); }
|
||||
.topbar-right { margin-left: auto; display: flex; align-items: center; gap: 18px; }
|
||||
.topbar-link { color: var(--text-2); font-size: 13.5px; }
|
||||
.topbar-link:hover { color: var(--primary); }
|
||||
.user-chip { display: flex; align-items: center; gap: 8px; }
|
||||
.user-email { font-size: 13px; color: var(--text-2); max-width: 220px; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
|
||||
.logout-form { display: inline-flex; }
|
||||
.icon-btn {
|
||||
display: inline-flex; align-items: center; justify-content: center;
|
||||
width: 30px; height: 30px; border: 1px solid var(--border); border-radius: 6px;
|
||||
background: #fff; color: var(--text-2); cursor: pointer;
|
||||
}
|
||||
.icon-btn:hover { color: var(--danger); border-color: var(--danger); }
|
||||
|
||||
/* ---------- 头像 ---------- */
|
||||
.avatar {
|
||||
width: 36px; height: 36px; border-radius: 50%;
|
||||
display: inline-flex; align-items: center; justify-content: center;
|
||||
font-size: 15px; font-weight: 600; flex-shrink: 0; user-select: none;
|
||||
}
|
||||
.avatar-sm { width: 28px; height: 28px; font-size: 12.5px; }
|
||||
|
||||
/* ---------- 整体布局 ---------- */
|
||||
.app-body { display: flex; min-height: 100vh; padding-top: var(--topbar-h); }
|
||||
|
||||
/* ---------- 左侧文件夹导航 ---------- */
|
||||
.mail-sidebar {
|
||||
width: 200px; flex-shrink: 0;
|
||||
background: var(--sidebar-bg); border-right: 1px solid var(--border);
|
||||
padding: 16px 12px; display: flex; flex-direction: column; gap: 14px;
|
||||
position: sticky; top: var(--topbar-h); height: calc(100vh - var(--topbar-h));
|
||||
}
|
||||
.compose-btn {
|
||||
display: flex; align-items: center; justify-content: center; gap: 7px;
|
||||
height: 38px; border-radius: 19px; color: #fff; font-size: 14.5px; font-weight: 600;
|
||||
background: linear-gradient(135deg, #ffa940, #ff9500);
|
||||
box-shadow: 0 2px 8px rgba(255, 149, 0, 0.35);
|
||||
transition: transform 0.1s, box-shadow 0.1s;
|
||||
}
|
||||
.compose-btn:hover { background: linear-gradient(135deg, #ff9d2e, #f08800); box-shadow: 0 3px 10px rgba(255, 149, 0, 0.45); transform: translateY(-1px); }
|
||||
.folder-nav { display: flex; flex-direction: column; gap: 3px; }
|
||||
.folder {
|
||||
display: flex; align-items: center; gap: 10px;
|
||||
height: 36px; padding: 0 10px; border-radius: 7px;
|
||||
color: var(--text-2); font-size: 13.5px; position: relative;
|
||||
}
|
||||
.folder:hover { background: #eef1f6; color: var(--text); }
|
||||
.folder.active { background: var(--primary-soft); color: var(--primary); font-weight: 600; }
|
||||
.folder.active::before {
|
||||
content: ""; position: absolute; left: -12px; top: 9px; bottom: 9px;
|
||||
width: 3px; border-radius: 2px; background: var(--primary);
|
||||
}
|
||||
.folder .badge {
|
||||
margin-left: auto; min-width: 20px; height: 20px; padding: 0 6px;
|
||||
border-radius: 10px; background: #ff4d4f; color: #fff;
|
||||
font-size: 11px; line-height: 20px; text-align: center; font-weight: 600;
|
||||
}
|
||||
.folder .count { margin-left: auto; color: var(--text-3); font-size: 12px; }
|
||||
.sidebar-footer { margin-top: auto; border-top: 1px solid var(--border-light); padding-top: 12px; display: flex; flex-direction: column; gap: 3px; }
|
||||
|
||||
/* ---------- 主内容区 ---------- */
|
||||
.mail-main { flex: 1; min-width: 0; background: #fff; display: flex; flex-direction: column; }
|
||||
|
||||
/* ---------- 列表工具条 ---------- */
|
||||
.list-toolbar {
|
||||
display: flex; align-items: center; gap: 10px;
|
||||
padding: 10px 18px; border-bottom: 1px solid var(--border-light); background: #fff;
|
||||
}
|
||||
.tb-btn {
|
||||
display: inline-flex; align-items: center; gap: 6px;
|
||||
height: 30px; padding: 0 11px; border: 1px solid var(--border); border-radius: 6px;
|
||||
background: #fff; color: var(--text-2); font-size: 13px; cursor: pointer;
|
||||
}
|
||||
.tb-btn:hover { color: var(--primary); border-color: var(--primary); }
|
||||
.tb-btn.danger:hover { color: var(--danger); border-color: var(--danger); }
|
||||
.check-all { display: flex; align-items: center; gap: 6px; font-size: 13px; color: var(--text-2); cursor: pointer; user-select: none; }
|
||||
.toolbar-spacer { flex: 1; }
|
||||
.page-info { font-size: 13px; color: var(--text-3); }
|
||||
|
||||
/* ---------- 邮件列表 ---------- */
|
||||
.mail-list { flex: 1; overflow-y: auto; }
|
||||
.mail-row {
|
||||
display: flex; align-items: center; gap: 10px;
|
||||
padding: 0 18px; height: 54px; border-bottom: 1px solid var(--border-light);
|
||||
cursor: pointer; transition: background 0.08s;
|
||||
background: #fff;
|
||||
}
|
||||
.mail-row:not(.unread) { background: #fbfcfe; }
|
||||
.mail-row:hover { background: #f2f6ff; }
|
||||
.mail-row.selected { background: var(--primary-soft); }
|
||||
.cell-check { display: flex; align-items: center; }
|
||||
.cell-avatar { flex: 0 0 auto; }
|
||||
.cell-from {
|
||||
width: 150px; flex-shrink: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap;
|
||||
font-size: 13.5px; color: var(--text-2);
|
||||
}
|
||||
.mail-row.unread .cell-from { color: var(--text); font-weight: 600; }
|
||||
.cell-subject-wrap { display: flex; align-items: center; gap: 7px; flex: 0 1 36%; min-width: 150px; }
|
||||
.unread-dot { width: 7px; height: 7px; border-radius: 50%; background: var(--primary); flex-shrink: 0; }
|
||||
.cell-subject {
|
||||
overflow: hidden; text-overflow: ellipsis; white-space: nowrap;
|
||||
font-size: 13.5px; color: var(--text-2);
|
||||
}
|
||||
.mail-row.unread .cell-subject { color: var(--text); font-weight: 600; }
|
||||
.cell-snippet {
|
||||
flex: 1; min-width: 60px; overflow: hidden; text-overflow: ellipsis; white-space: nowrap;
|
||||
font-size: 12.5px; color: var(--text-3);
|
||||
}
|
||||
.cell-date {
|
||||
width: 78px; flex-shrink: 0; text-align: right;
|
||||
font-size: 12.5px; color: var(--text-3);
|
||||
}
|
||||
.mail-row.unread .cell-date { color: var(--text-2); }
|
||||
.row-del { opacity: 0; transition: opacity 0.12s; }
|
||||
.mail-row:hover .row-del { opacity: 1; }
|
||||
.empty-tip { padding: 90px 0; text-align: center; color: var(--text-3); font-size: 14px; }
|
||||
.empty-tip .empty-icon { font-size: 46px; display: block; margin-bottom: 14px; opacity: 0.5; }
|
||||
|
||||
/* ---------- 列表底部分页 ---------- */
|
||||
.list-footer {
|
||||
display: flex; align-items: center; gap: 12px;
|
||||
padding: 10px 18px; border-top: 1px solid var(--border-light);
|
||||
font-size: 13px; color: var(--text-3); background: #fff;
|
||||
}
|
||||
.pager { margin-left: auto; display: flex; align-items: center; gap: 6px; }
|
||||
.page-btn {
|
||||
height: 28px; padding: 0 11px; border: 1px solid var(--border); border-radius: 6px;
|
||||
background: #fff; color: var(--text-2); font-size: 13px;
|
||||
display: inline-flex; align-items: center; gap: 4px;
|
||||
}
|
||||
.page-btn:hover:not(.disabled) { color: var(--primary); border-color: var(--primary); }
|
||||
.page-btn.disabled { opacity: 0.45; cursor: not-allowed; }
|
||||
.page-num { font-size: 13px; }
|
||||
|
||||
/* ---------- 邮件阅读页 ---------- */
|
||||
.view-toolbar { display: flex; align-items: center; gap: 10px; padding: 10px 18px; border-bottom: 1px solid var(--border-light); }
|
||||
.mail-head { padding: 22px 28px 0; }
|
||||
.mail-title { font-size: 20px; font-weight: 600; line-height: 1.45; word-break: break-word; }
|
||||
.mail-from-row { display: flex; align-items: center; gap: 12px; margin: 16px 0 18px; }
|
||||
.mail-from-name { font-size: 14.5px; font-weight: 600; }
|
||||
.mail-from-addr { color: var(--text-3); font-size: 12.5px; }
|
||||
.mail-date { color: var(--text-3); font-size: 12.5px; margin-left: auto; }
|
||||
.mail-body-wrap { padding: 22px 28px; flex: 1; overflow: auto; }
|
||||
.mail-body { line-height: 1.7; font-size: 14.5px; }
|
||||
.mail-body pre { white-space: pre-wrap; font-family: inherit; }
|
||||
.mail-body-iframe {
|
||||
width: 100%; min-height: 340px; border: 1px solid var(--border-light);
|
||||
border-radius: 8px; background: #fff;
|
||||
}
|
||||
.attachment-list { margin-top: 22px; padding-top: 18px; border-top: 1px solid var(--border-light); }
|
||||
.attachment-item {
|
||||
display: inline-flex; align-items: center; gap: 7px;
|
||||
margin: 0 12px 10px 0; padding: 7px 13px;
|
||||
background: #f2f3f5; border-radius: 7px; font-size: 13px; color: var(--text);
|
||||
}
|
||||
.attachment-item a { color: var(--text); }
|
||||
.attachment-item a:hover { color: var(--primary); }
|
||||
.view-actions { display: flex; align-items: center; gap: 10px; padding: 18px 28px 24px; }
|
||||
|
||||
/* ---------- 写信页 ---------- */
|
||||
.compose-toolbar { display: flex; align-items: center; gap: 10px; padding: 10px 18px; border-bottom: 1px solid var(--border-light); }
|
||||
.compose-form { flex: 1; display: flex; flex-direction: column; min-height: 0; }
|
||||
.compose-field { display: flex; align-items: center; gap: 12px; padding: 9px 22px; border-bottom: 1px solid var(--border-light); }
|
||||
.compose-field label { width: 54px; color: var(--text-2); font-size: 13.5px; flex-shrink: 0; }
|
||||
.compose-field input { border: none; outline: none; flex: 1; font-size: 14px; color: var(--text); background: transparent; }
|
||||
.editor-wrap { flex: 1; display: flex; flex-direction: column; min-height: 0; }
|
||||
.editor-wrap .ql-toolbar { border-left: none; border-right: none; border-top: none; }
|
||||
.editor-wrap .ql-container { border: none; flex: 1; font-size: 14.5px; }
|
||||
#editor { height: 100%; }
|
||||
.attach-chips { display: flex; flex-wrap: wrap; gap: 8px; padding: 10px 22px; border-bottom: 1px solid var(--border-light); }
|
||||
.attach-chip {
|
||||
display: inline-flex; align-items: center; gap: 7px;
|
||||
padding: 5px 11px; background: #f2f3f5; border-radius: 15px;
|
||||
font-size: 12.5px; color: var(--text-2);
|
||||
}
|
||||
.attach-chip .chip-del { cursor: pointer; color: var(--text-3); border: none; background: none; font-size: 13px; line-height: 1; }
|
||||
.attach-chip .chip-del:hover { color: var(--danger); }
|
||||
.compose-footer {
|
||||
display: flex; align-items: center; gap: 14px;
|
||||
padding: 12px 22px; border-top: 1px solid var(--border-light);
|
||||
font-size: 12.5px; color: var(--text-3); background: #fafbfc;
|
||||
}
|
||||
.quota-bar { width: 200px; height: 6px; background: #eceef1; border-radius: 3px; overflow: hidden; }
|
||||
.quota-bar i { display: block; height: 100%; background: linear-gradient(90deg, #4aa3ff, var(--primary)); border-radius: 3px; }
|
||||
.quota-bar.warn i { background: linear-gradient(90deg, #ffc53d, var(--orange)); }
|
||||
.quota-bar.over i { background: var(--danger); }
|
||||
|
||||
/* ---------- 登录页 ---------- */
|
||||
.login-page {
|
||||
min-height: 100vh; display: flex; align-items: center; justify-content: center;
|
||||
background: linear-gradient(165deg, #eaf2ff 0%, #f6f8fc 55%, #f0f6ff 100%);
|
||||
}
|
||||
.login-card {
|
||||
width: 400px; max-width: calc(100vw - 32px);
|
||||
background: #fff; border-radius: 14px;
|
||||
box-shadow: 0 10px 40px rgba(22, 119, 255, 0.10);
|
||||
padding: 42px 38px 36px;
|
||||
}
|
||||
.login-logo { display: flex; align-items: center; justify-content: center; gap: 10px; margin-bottom: 8px; }
|
||||
.login-title { text-align: center; font-size: 21px; font-weight: 700; color: var(--text); margin-bottom: 26px; }
|
||||
.login-sub { text-align: center; color: var(--text-3); font-size: 13px; margin-bottom: 26px; }
|
||||
.divider { display: flex; align-items: center; gap: 10px; color: var(--text-3); font-size: 12.5px; margin: 18px 0; }
|
||||
.divider::before, .divider::after { content: ""; flex: 1; height: 1px; background: var(--border-light); }
|
||||
|
||||
/* ---------- 通用组件(兼容管理后台) ---------- */
|
||||
.container { max-width: 1400px; margin: 20px auto; padding: 0 20px; }
|
||||
.card {
|
||||
background: #fff; border: 1px solid var(--border-light); border-radius: var(--radius);
|
||||
box-shadow: 0 1px 3px rgba(0, 0, 0, 0.04); padding: 20px; margin-bottom: 16px;
|
||||
}
|
||||
.btn {
|
||||
display: inline-block; padding: 8px 16px; border-radius: 6px; border: 1px solid transparent;
|
||||
text-decoration: none; font-size: 14px; cursor: pointer; text-align: center;
|
||||
background: #f2f3f5; color: var(--text); line-height: 1.4;
|
||||
}
|
||||
.btn-primary { background: var(--primary); color: #fff; }
|
||||
.btn-primary:hover { background: var(--primary-hover); }
|
||||
.btn-danger { background: var(--danger); color: #fff; }
|
||||
.btn-danger:hover { background: #d23b47; }
|
||||
.btn-sm { padding: 4px 10px; font-size: 12px; border-radius: 5px; }
|
||||
.alert { padding: 12px 16px; border-radius: 7px; margin-bottom: 16px; font-size: 13.5px; }
|
||||
.alert-error { background: var(--danger-soft); color: #c0392b; }
|
||||
.alert-success { background: var(--success-soft); color: #2e9e4f; }
|
||||
.form-group { margin-bottom: 16px; }
|
||||
.form-group label { display: block; margin-bottom: 7px; font-weight: 600; font-size: 13.5px; }
|
||||
.form-group input, .form-group textarea, .form-group select {
|
||||
width: 100%; padding: 8px 12px; border: 1px solid var(--border); border-radius: 6px;
|
||||
font-size: 14px; outline: none; background: #fff; color: var(--text);
|
||||
}
|
||||
.form-group input:focus, .form-group textarea:focus, .form-group select:focus {
|
||||
border-color: var(--primary); box-shadow: 0 0 0 3px rgba(22, 119, 255, 0.12);
|
||||
}
|
||||
.form-group input[type="checkbox"] { width: auto; }
|
||||
table { width: 100%; border-collapse: collapse; }
|
||||
th, td { padding: 10px 12px; text-align: left; border-bottom: 1px solid var(--border-light); font-size: 13.5px; }
|
||||
th { background: #f8f9fb; font-weight: 600; color: var(--text-2); }
|
||||
tbody tr:hover td { background: #fafbfc; }
|
||||
.unread { font-weight: bold; }
|
||||
.message-subject { color: var(--text); }
|
||||
.message-subject:hover { color: var(--primary); }
|
||||
.mail-meta { color: var(--text-2); font-size: 13px; margin-bottom: 10px; line-height: 1.9; }
|
||||
.pagination { margin-top: 16px; text-align: center; }
|
||||
.pagination a, .pagination span {
|
||||
display: inline-block; padding: 6px 12px; margin: 0 2px;
|
||||
border: 1px solid var(--border); border-radius: 6px; text-decoration: none;
|
||||
color: var(--text-2); font-size: 13px;
|
||||
}
|
||||
.pagination .current { background: var(--primary); color: #fff; border-color: var(--primary); }
|
||||
.badge { display: inline-block; padding: 2px 8px; border-radius: 10px; font-size: 11px; font-weight: bold; }
|
||||
.badge-unread { background: #ff4d4f; color: #fff; }
|
||||
.stat-card {
|
||||
display: inline-block; width: 200px; padding: 20px; margin: 0 20px 16px 0;
|
||||
background: #fff; border: 1px solid var(--border-light); border-radius: var(--radius);
|
||||
box-shadow: 0 1px 3px rgba(0, 0, 0, 0.04); text-align: center;
|
||||
}
|
||||
.stat-card h3 { font-size: 30px; color: var(--primary); margin-bottom: 4px; }
|
||||
.stat-card p { color: var(--text-2); font-size: 13.5px; }
|
||||
.dns-record {
|
||||
background: #f8f9fb; padding: 12px 16px; border-radius: 6px; margin-bottom: 12px;
|
||||
font-family: ui-monospace, SFMono-Regular, Menlo, Consolas, monospace;
|
||||
font-size: 12.5px; white-space: pre-wrap;
|
||||
}
|
||||
.clearfix::after { content: ""; display: table; clear: both; }
|
||||
/* 管理后台左侧导航兼容 */
|
||||
.sidebar { width: 200px; float: left; background: #fff; border: 1px solid var(--border-light); border-radius: var(--radius); padding: 8px; }
|
||||
.sidebar a { display: block; padding: 9px 14px; color: var(--text-2); text-decoration: none; border-radius: 6px; margin-bottom: 2px; font-size: 13.5px; }
|
||||
.sidebar a:hover, .sidebar a.active { background: var(--primary-soft); color: var(--primary); }
|
||||
.content { margin-left: 220px; }
|
||||
.settings-main { padding: 24px; background: var(--sidebar-bg); }
|
||||
|
||||
/* ===== 移动端适配(≤767px) ===== */
|
||||
@media (max-width: 767px) {
|
||||
:root { --topbar-h: 50px; }
|
||||
|
||||
/* 顶栏:紧凑单行 + 列表页搜索框下移为第二行 */
|
||||
.topbar { height: auto; min-height: 50px; padding: 8px 12px; gap: 8px; flex-wrap: wrap; }
|
||||
.logo-icon { width: 30px; height: 30px; font-size: 15px; border-radius: 8px; }
|
||||
.logo-text { font-size: 17px; }
|
||||
.logo-text em { display: none; }
|
||||
.topbar-search { flex: 1 1 100%; order: 9; border-radius: 8px; }
|
||||
body.page-list { --topbar-h: 96px; }
|
||||
.topbar-right { gap: 12px; }
|
||||
.user-email { display: none; }
|
||||
|
||||
/* 左侧文件夹栏 → 底部导航条 */
|
||||
.mail-sidebar {
|
||||
position: fixed; top: auto; bottom: 0; left: 0; right: 0;
|
||||
width: 100%; height: auto; min-height: 58px;
|
||||
padding: 4px 8px calc(4px + env(safe-area-inset-bottom));
|
||||
flex-direction: row; align-items: center; gap: 2px;
|
||||
background: #fff; border-top: 1px solid var(--border); border-right: none;
|
||||
z-index: 90; box-shadow: 0 -2px 8px rgba(0, 0, 0, 0.04);
|
||||
}
|
||||
.folder-nav { display: contents; }
|
||||
.folder {
|
||||
flex: 1; flex-direction: column; justify-content: center; gap: 2px;
|
||||
height: 46px; padding: 0; border-radius: 8px; font-size: 10.5px;
|
||||
position: relative;
|
||||
}
|
||||
.folder-nav .folder:nth-child(1) { order: 1; }
|
||||
.folder-nav .folder:nth-child(2) { order: 2; }
|
||||
.folder-nav .folder:nth-child(3) { order: 4; }
|
||||
.folder svg { width: 19px; height: 19px; }
|
||||
.folder.active::before { display: none; }
|
||||
.folder .badge {
|
||||
position: absolute; top: 1px; right: calc(50% - 20px);
|
||||
min-width: 16px; height: 16px; padding: 0 4px;
|
||||
font-size: 10px; line-height: 16px; border-radius: 8px;
|
||||
}
|
||||
.folder .count { display: none; }
|
||||
.compose-btn {
|
||||
width: 46px; height: 46px; padding: 0; border-radius: 50%;
|
||||
margin: 0 4px; flex-shrink: 0; order: 3;
|
||||
font-size: 0; box-shadow: 0 3px 10px rgba(255, 149, 0, 0.5);
|
||||
transform: translateY(-10px);
|
||||
}
|
||||
.compose-btn:hover { transform: translateY(-10px); }
|
||||
.compose-btn svg { width: 20px; height: 20px; }
|
||||
.sidebar-footer {
|
||||
margin: 0; border: none; padding: 0;
|
||||
flex-direction: row; gap: 2px; order: 5;
|
||||
}
|
||||
.mail-main { padding-bottom: calc(58px + env(safe-area-inset-bottom)); }
|
||||
|
||||
/* 邮件列表 */
|
||||
.list-toolbar { padding: 8px 10px; gap: 8px; }
|
||||
.check-all { font-size: 12.5px; }
|
||||
.tb-btn { height: 30px; padding: 0 9px; font-size: 12.5px; }
|
||||
.page-info { font-size: 12px; }
|
||||
.mail-row { padding: 0 10px; height: 60px; gap: 8px; }
|
||||
.avatar { width: 32px; height: 32px; font-size: 13px; }
|
||||
.cell-from { width: 88px; font-size: 13px; }
|
||||
.cell-subject-wrap { flex: 1; min-width: 0; }
|
||||
.cell-subject { font-size: 13px; }
|
||||
.cell-snippet { display: none; }
|
||||
.cell-date { width: 56px; font-size: 11.5px; }
|
||||
.row-del { opacity: 1; }
|
||||
.list-footer { padding: 8px 10px; }
|
||||
.pager { margin-left: auto; gap: 4px; }
|
||||
|
||||
/* 阅读页 */
|
||||
.view-toolbar { padding: 8px 10px; gap: 8px; }
|
||||
.mail-head { padding: 16px 16px 0; }
|
||||
.mail-title { font-size: 17px; }
|
||||
.mail-from-row { gap: 10px; margin: 12px 0 14px; }
|
||||
.mail-body-wrap { padding: 14px 16px; }
|
||||
.mail-body-iframe { min-height: 260px; }
|
||||
.view-actions { padding: 14px 16px 20px; flex-wrap: wrap; }
|
||||
|
||||
/* 写信页 */
|
||||
.compose-toolbar { padding: 8px 10px; gap: 8px; }
|
||||
.compose-field { padding: 8px 14px; gap: 8px; }
|
||||
.compose-field label { width: 44px; font-size: 13px; }
|
||||
.compose-footer { padding: 10px 14px; flex-wrap: wrap; }
|
||||
.quota-bar { width: 130px; }
|
||||
|
||||
/* 设置页 */
|
||||
.settings-main { padding: 14px; }
|
||||
|
||||
/* 管理后台 */
|
||||
.container { padding: 0 12px; margin: 12px auto; }
|
||||
.sidebar { float: none; width: 100%; margin-bottom: 12px; display: flex; flex-wrap: wrap; gap: 2px; padding: 6px; }
|
||||
.sidebar a { margin: 0; padding: 8px 12px; font-size: 13px; }
|
||||
.content { margin-left: 0; overflow-x: auto; }
|
||||
th, td { white-space: nowrap; }
|
||||
.stat-card { width: calc(50% - 10px); margin: 0 0 10px; }
|
||||
}
|
||||
* { margin:0; padding:0; box-sizing:border-box; }
|
||||
body { font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif; background:#f5f5f5; color:#333; }
|
||||
.navbar { background:#2c3e50; padding:0 20px; height:50px; display:flex; align-items:center; }
|
||||
.navbar a { color:#ecf0f1; text-decoration:none; margin-right:20px; font-size:14px; }
|
||||
.navbar a:hover { color:#3498db; }
|
||||
.navbar .right { margin-left:auto; }
|
||||
.container { max-width:1200px; margin:20px auto; padding:0 20px; }
|
||||
.card { background:#fff; border-radius:8px; box-shadow:0 2px 4px rgba(0,0,0,0.1); padding:20px; margin-bottom:20px; }
|
||||
table { width:100%; border-collapse:collapse; }
|
||||
th, td { padding:10px 12px; text-align:left; border-bottom:1px solid #eee; }
|
||||
th { background:#f8f9fa; font-weight:600; }
|
||||
.btn { display:inline-block; padding:8px 16px; border-radius:4px; text-decoration:none; font-size:14px; cursor:pointer; border:none; }
|
||||
.btn-primary { background:#3498db; color:#fff; }
|
||||
.btn-primary:hover { background:#2980b9; }
|
||||
.btn-danger { background:#e74c3c; color:#fff; }
|
||||
.btn-danger:hover { background:#c0392b; }
|
||||
.btn-sm { padding:4px 10px; font-size:12px; }
|
||||
.alert { padding:12px 16px; border-radius:4px; margin-bottom:16px; }
|
||||
.alert-error { background:#fde8e8; color:#c0392b; }
|
||||
.alert-success { background:#e8fde8; color:#27ae60; }
|
||||
.form-group { margin-bottom:16px; }
|
||||
.form-group label { display:block; margin-bottom:6px; font-weight:600; }
|
||||
.form-group input, .form-group textarea, .form-group select { width:100%; padding:8px 12px; border:1px solid #ddd; border-radius:4px; font-size:14px; }
|
||||
.form-group input[type="checkbox"] { width:auto; }
|
||||
.unread { font-weight:bold; }
|
||||
.message-subject { color:#2c3e50; text-decoration:none; }
|
||||
.message-subject:hover { color:#3498db; }
|
||||
.sidebar { width:200px; float:left; }
|
||||
.sidebar a { display:block; padding:10px 15px; color:#2c3e50; text-decoration:none; border-radius:4px; margin-bottom:2px; }
|
||||
.sidebar a:hover, .sidebar a.active { background:#3498db; color:#fff; }
|
||||
.content { margin-left:220px; }
|
||||
.pagination { margin-top:16px; text-align:center; }
|
||||
.pagination a, .pagination span { display:inline-block; padding:6px 12px; margin:0 2px; border:1px solid #ddd; border-radius:4px; text-decoration:none; color:#333; }
|
||||
.pagination .current { background:#3498db; color:#fff; border-color:#3498db; }
|
||||
.mail-meta { color:#7f8c8d; font-size:13px; margin-bottom:8px; }
|
||||
.mail-body { line-height:1.6; margin-top:16px; padding-top:16px; border-top:1px solid #eee; }
|
||||
.attachment-list { margin-top:16px; padding-top:16px; border-top:1px solid #eee; }
|
||||
.attachment-item { display:inline-block; margin-right:12px; margin-bottom:8px; padding:6px 12px; background:#ecf0f1; border-radius:4px; font-size:13px; }
|
||||
.attachment-item a { color:#2c3e50; text-decoration:none; }
|
||||
.attachment-item a:hover { color:#3498db; }
|
||||
.badge { display:inline-block; padding:2px 8px; border-radius:10px; font-size:11px; font-weight:bold; }
|
||||
.badge-unread { background:#e74c3c; color:#fff; }
|
||||
.stat-card { display:inline-block; width:200px; padding:20px; margin-right:20px; background:#fff; border-radius:8px; box-shadow:0 2px 4px rgba(0,0,0,0.1); text-align:center; }
|
||||
.stat-card h3 { font-size:32px; color:#2c3e50; margin-bottom:4px; }
|
||||
.stat-card p { color:#7f8c8d; font-size:14px; }
|
||||
.dns-record { background:#f8f9fa; padding:12px 16px; border-radius:4px; margin-bottom:12px; font-family:monospace; font-size:13px; white-space:pre-wrap; }
|
||||
.clearfix::after { content:""; display:table; clear:both; }
|
||||
</style>
|
||||
{{end}}
|
||||
|
||||
{{define "navbar"}}
|
||||
{{if .currentUser}}
|
||||
<header class="topbar">
|
||||
<div class="topbar-left">
|
||||
<a class="logo" href="/inbox">
|
||||
<span class="logo-icon">✉</span>
|
||||
<span class="logo-text">MailGo<em>邮箱</em></span>
|
||||
</a>
|
||||
</div>
|
||||
<div class="topbar-search">
|
||||
<svg width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><circle cx="11" cy="11" r="8"/><line x1="21" y1="21" x2="16.65" y2="16.65"/></svg>
|
||||
<input id="mail-search" type="text" placeholder="搜索邮件(发件人 / 主题)" autocomplete="off">
|
||||
</div>
|
||||
<div class="topbar-right">
|
||||
{{if .currentUser.IsAdmin}}<a class="topbar-link" href="/admin">管理后台</a>{{end}}
|
||||
<a class="topbar-link" href="/settings">设置</a>
|
||||
<span class="user-chip">
|
||||
<span class="avatar avatar-sm" style="{{avatarStyle .currentUser.Username}}">{{initial .currentUser.Username}}</span>
|
||||
<span class="user-email" title="{{.currentUser.Username}}@{{.currentUser.Domain.Name}}">{{.currentUser.Username}}@{{.currentUser.Domain.Name}}</span>
|
||||
</span>
|
||||
<form method="POST" action="/logout" class="logout-form">
|
||||
<button type="submit" class="icon-btn" title="退出登录">
|
||||
<svg width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M9 21H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h4"/><polyline points="16 17 21 12 16 7"/><line x1="21" y1="12" x2="9" y2="12"/></svg>
|
||||
</button>
|
||||
<nav class="navbar">
|
||||
<a href="/inbox">MailGo</a>
|
||||
{{if .currentUser.IsAdmin}}<a href="/admin">管理后台</a>{{end}}
|
||||
<div class="right">
|
||||
<span style="color:#ecf0f1;font-size:13px;">{{.currentUser.Username}}@{{.currentUser.Domain.Name}}</span>
|
||||
<form method="POST" action="/logout" style="display:inline;">
|
||||
<a href="#" onclick="this.parentElement.submit(); return false;">退出</a>
|
||||
</form>
|
||||
</div>
|
||||
</header>
|
||||
</nav>
|
||||
{{end}}
|
||||
{{end}}
|
||||
|
||||
{{define "sidebar"}}
|
||||
<aside class="mail-sidebar">
|
||||
<a href="/compose" class="compose-btn">
|
||||
<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M11 4H4a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h14a2 2 0 0 0 2-2v-7"/><path d="M18.5 2.5a2.121 2.121 0 0 1 3 3L12 15l-4 1 1-4 9.5-9.5z"/></svg>
|
||||
写信
|
||||
</a>
|
||||
<nav class="folder-nav">
|
||||
<a class="folder {{if eq .activeFolder `inbox`}}active{{end}}" href="/inbox">
|
||||
<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><polyline points="22 12 16 12 14 15 10 15 8 12 2 12"/><path d="M5.45 5.11L2 12v6a2 2 0 0 0 2 2h16a2 2 0 0 0 2-2v-6l-3.45-6.89A2 2 0 0 0 16.76 4H7.24a2 2 0 0 0-1.79 1.11z"/></svg>
|
||||
收件箱
|
||||
{{if .inboxUnread}}<span class="badge">{{.inboxUnread}}</span>{{end}}
|
||||
</a>
|
||||
<a class="folder {{if eq .activeFolder `drafts`}}active{{end}}" href="/drafts">
|
||||
<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z"/><polyline points="14 2 14 8 20 8"/><line x1="16" y1="13" x2="8" y2="13"/><line x1="16" y1="17" x2="8" y2="17"/></svg>
|
||||
草稿箱
|
||||
{{if .draftsTotal}}<span class="count">{{.draftsTotal}}</span>{{end}}
|
||||
</a>
|
||||
<a class="folder {{if eq .activeFolder `sent`}}active{{end}}" href="/sent">
|
||||
<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><line x1="22" y1="2" x2="11" y2="13"/><polygon points="22 2 15 22 11 13 2 9 22 2"/></svg>
|
||||
已发送
|
||||
{{if .sentTotal}}<span class="count">{{.sentTotal}}</span>{{end}}
|
||||
</a>
|
||||
</nav>
|
||||
<div class="sidebar-footer">
|
||||
{{if .currentUser.IsAdmin}}
|
||||
<a class="folder" href="/admin">
|
||||
<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M12 22s8-4 8-10V5l-8-3-8 3v7c0 6 8 10 8 10z"/></svg>
|
||||
管理后台
|
||||
</a>
|
||||
{{end}}
|
||||
</div>
|
||||
</aside>
|
||||
{{end}}
|
||||
@@ -3,68 +3,64 @@
|
||||
<html lang="zh-CN">
|
||||
<head>
|
||||
<meta charset="UTF-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0, viewport-fit=cover">
|
||||
<title>写信 - MailGo</title>
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||||
<title>撰写邮件 - MailGo</title>
|
||||
<link href="https://cdn.quilljs.com/1.3.7/quill.snow.css" rel="stylesheet">
|
||||
{{template "styles" .}}
|
||||
</head>
|
||||
<body class="page-compose">
|
||||
<body>
|
||||
{{template "navbar" .}}
|
||||
<div class="app-body">
|
||||
{{template "sidebar" .}}
|
||||
<main class="mail-main">
|
||||
<div class="compose-toolbar">
|
||||
<button type="submit" form="compose-form" class="btn btn-primary">
|
||||
<svg width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" style="vertical-align:-2px;margin-right:4px;"><line x1="22" y1="2" x2="11" y2="13"/><polygon points="22 2 15 22 11 13 2 9 22 2"/></svg>
|
||||
发送
|
||||
</button>
|
||||
<label class="tb-btn" style="cursor:pointer;">
|
||||
<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M21.44 11.05l-9.19 9.19a6 6 0 0 1-8.49-8.49l9.19-9.19a4 4 0 0 1 5.66 5.66l-9.2 9.19a2 2 0 0 1-2.83-2.83l8.49-8.48"/></svg>
|
||||
附件
|
||||
<input type="file" name="attachments" id="attach-input" multiple style="display:none;">
|
||||
</label>
|
||||
<a href="/inbox" class="tb-btn">取消</a>
|
||||
<div class="toolbar-spacer"></div>
|
||||
<span class="page-info">撰写新邮件</span>
|
||||
<div class="container">
|
||||
<div class="clearfix">
|
||||
<div class="sidebar">
|
||||
<a href="/inbox" class="{{if eq .activeFolder `inbox`}}active{{end}}">收件箱</a>
|
||||
<a href="/drafts" class="{{if eq .activeFolder `drafts`}}active{{end}}">草稿箱</a>
|
||||
<a href="/sent" class="{{if eq .activeFolder `sent`}}active{{end}}">发件箱</a>
|
||||
<a href="/compose" class="{{if eq .activeFolder `compose`}}active{{end}}">撰写邮件</a>
|
||||
<a href="/settings" class="{{if eq .activeFolder `settings`}}active{{end}}">设置</a>
|
||||
</div>
|
||||
|
||||
{{if .error}}<div class="alert alert-error" style="margin:12px 18px 0;">{{.error}}</div>{{end}}
|
||||
|
||||
<form id="compose-form" class="compose-form" method="POST" action="/compose" enctype="multipart/form-data">
|
||||
<div class="compose-field">
|
||||
<label>收件人</label>
|
||||
<input type="email" name="to" required value="{{.to}}" placeholder="输入收件人邮箱地址">
|
||||
<div class="content">
|
||||
<div class="card">
|
||||
<h2 style="margin-bottom:16px;">撰写邮件</h2>
|
||||
{{if .error}}<div class="alert alert-error">{{.error}}</div>{{end}}
|
||||
<form method="POST" action="/compose" enctype="multipart/form-data">
|
||||
<div class="form-group">
|
||||
<label>收件人</label>
|
||||
<input type="email" name="to" required value="{{.to}}" placeholder="user@example.com">
|
||||
</div>
|
||||
<div class="form-group">
|
||||
<label>抄送(可选)</label>
|
||||
<input type="text" name="cc" value="{{.cc}}" placeholder="cc@example.com">
|
||||
</div>
|
||||
<div class="form-group">
|
||||
<label>主题</label>
|
||||
<input type="text" name="subject" value="{{.subject}}" placeholder="邮件主题">
|
||||
</div>
|
||||
<div class="form-group">
|
||||
<label>正文</label>
|
||||
<div id="editor" style="height:300px;"></div>
|
||||
<input type="hidden" name="body" id="body-hidden">
|
||||
<input type="hidden" name="html_body" id="html-body-hidden">
|
||||
</div>
|
||||
<div class="form-group">
|
||||
<label>附件</label>
|
||||
<input type="file" name="attachments" multiple>
|
||||
</div>
|
||||
<div class="form-group" style="color:#7f8c8d;font-size:12px;">
|
||||
配额: {{formatBytes .usedBytes}} / {{formatBytes .quotaBytes}}
|
||||
</div>
|
||||
<button type="submit" class="btn btn-primary">发送邮件</button>
|
||||
<a href="/inbox" class="btn" style="margin-left:8px;">取消</a>
|
||||
</form>
|
||||
</div>
|
||||
<div class="compose-field">
|
||||
<label>抄送</label>
|
||||
<input type="text" name="cc" value="{{.cc}}" placeholder="多个地址用逗号分隔(可选)">
|
||||
</div>
|
||||
<div class="compose-field">
|
||||
<label>主题</label>
|
||||
<input type="text" name="subject" value="{{.subject}}" placeholder="输入邮件主题">
|
||||
</div>
|
||||
|
||||
<div id="attach-chips" class="attach-chips" style="{{if not .attachments}}display:none;{{end}}"></div>
|
||||
|
||||
<div class="editor-wrap">
|
||||
<div id="editor" data-placeholder="请输入邮件内容..."></div>
|
||||
<input type="hidden" name="body" id="body-hidden">
|
||||
<input type="hidden" name="html_body" id="html-body-hidden">
|
||||
</div>
|
||||
|
||||
<div class="compose-footer">
|
||||
<span>附件配额</span>
|
||||
<span class="quota-bar" id="quota-bar" data-used="{{.usedBytes}}" data-quota="{{.quotaBytes}}"><i></i></span>
|
||||
<span id="quota-text">{{formatBytes .usedBytes}} / {{formatBytes .quotaBytes}}</span>
|
||||
</div>
|
||||
</form>
|
||||
</main>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<script src="https://cdn.quilljs.com/1.3.7/quill.min.js"></script>
|
||||
<script>
|
||||
var quill = new Quill('#editor', {
|
||||
theme: 'snow',
|
||||
placeholder: document.getElementById('editor').dataset.placeholder || '请输入邮件内容...',
|
||||
placeholder: '请输入邮件内容...',
|
||||
modules: {
|
||||
toolbar: [
|
||||
[{ 'header': [1, 2, 3, false] }],
|
||||
@@ -76,54 +72,13 @@
|
||||
]
|
||||
}
|
||||
});
|
||||
{{if .bodyContent}}
|
||||
quill.root.innerHTML = {{.bodyContent | safeJS}};
|
||||
{{end}}
|
||||
|
||||
document.getElementById('compose-form').addEventListener('submit', function () {
|
||||
document.querySelector('form').addEventListener('submit', function() {
|
||||
document.getElementById('body-hidden').value = quill.getText();
|
||||
document.getElementById('html-body-hidden').value = quill.root.innerHTML;
|
||||
});
|
||||
|
||||
// 附件选择预览
|
||||
var attachInput = document.getElementById('attach-input');
|
||||
var chipsBox = document.getElementById('attach-chips');
|
||||
var files = [];
|
||||
function renderChips() {
|
||||
chipsBox.innerHTML = '';
|
||||
chipsBox.style.display = files.length ? 'flex' : 'none';
|
||||
files.forEach(function (f, i) {
|
||||
var chip = document.createElement('span');
|
||||
chip.className = 'attach-chip';
|
||||
chip.innerHTML = '📎 ' + f.name + ' (' + (f.size / 1024).toFixed(1) + ' KB)' +
|
||||
'<button type="button" class="chip-del" data-i="' + i + '" title="移除">✕</button>';
|
||||
chipsBox.appendChild(chip);
|
||||
});
|
||||
}
|
||||
attachInput.addEventListener('change', function () {
|
||||
files = Array.prototype.slice.call(attachInput.files);
|
||||
renderChips();
|
||||
});
|
||||
chipsBox.addEventListener('click', function (e) {
|
||||
var del = e.target.closest('.chip-del');
|
||||
if (!del) return;
|
||||
files.splice(parseInt(del.dataset.i, 10), 1);
|
||||
var dt = new DataTransfer();
|
||||
files.forEach(function (f) { dt.items.add(f); });
|
||||
attachInput.files = dt.files;
|
||||
renderChips();
|
||||
});
|
||||
|
||||
// 配额进度条
|
||||
var bar = document.getElementById('quota-bar');
|
||||
if (bar) {
|
||||
var used = parseInt(bar.dataset.used, 10) || 0;
|
||||
var quota = parseInt(bar.dataset.quota, 10) || 1;
|
||||
var pct = Math.min(100, Math.round(used / quota * 100));
|
||||
bar.querySelector('i').style.width = pct + '%';
|
||||
if (pct >= 90) bar.classList.add('warn');
|
||||
if (pct >= 100) bar.classList.add('over');
|
||||
}
|
||||
{{if .bodyContent}}
|
||||
quill.root.innerHTML = {{.bodyContent | safeJS}};
|
||||
{{end}}
|
||||
</script>
|
||||
</body>
|
||||
</html>
|
||||
|
||||
@@ -3,152 +3,72 @@
|
||||
<html lang="zh-CN">
|
||||
<head>
|
||||
<meta charset="UTF-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0, viewport-fit=cover">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||||
<title>草稿箱 - MailGo</title>
|
||||
{{template "styles" .}}
|
||||
</head>
|
||||
<body class="page-list">
|
||||
<body>
|
||||
{{template "navbar" .}}
|
||||
<div class="app-body">
|
||||
{{template "sidebar" .}}
|
||||
<main class="mail-main">
|
||||
<div class="list-toolbar">
|
||||
<label class="check-all" title="全选/取消全选">
|
||||
<input type="checkbox" id="select-all">
|
||||
全选
|
||||
</label>
|
||||
<button type="button" class="tb-btn" id="btn-refresh" title="刷新">
|
||||
<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><polyline points="23 4 23 10 17 10"/><path d="M20.49 15a9 9 0 1 1-2.12-9.36L23 10"/></svg>
|
||||
刷新
|
||||
</button>
|
||||
<button type="button" class="tb-btn danger" id="btn-delete" disabled>
|
||||
<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><polyline points="3 6 5 6 21 6"/><path d="M19 6v14a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2V6m3 0V4a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v2"/></svg>
|
||||
删除
|
||||
</button>
|
||||
<div class="toolbar-spacer"></div>
|
||||
<span class="page-info">共 {{.total}} 封</span>
|
||||
<div class="container">
|
||||
<div class="clearfix">
|
||||
<div class="sidebar">
|
||||
<a href="/inbox" class="{{if eq .activeFolder `inbox`}}active{{end}}">收件箱</a>
|
||||
<a href="/drafts" class="{{if eq .activeFolder `drafts`}}active{{end}}">草稿箱</a>
|
||||
<a href="/sent" class="{{if eq .activeFolder `sent`}}active{{end}}">发件箱</a>
|
||||
<a href="/compose" class="{{if eq .activeFolder `compose`}}active{{end}}">撰写邮件</a>
|
||||
<a href="/settings" class="{{if eq .activeFolder `settings`}}active{{end}}">设置</a>
|
||||
</div>
|
||||
|
||||
{{if not .messages}}
|
||||
<div class="mail-list">
|
||||
<div class="empty-tip"><span class="empty-icon">📝</span>草稿箱暂无邮件</div>
|
||||
</div>
|
||||
{{else}}
|
||||
<ul class="mail-list">
|
||||
{{range .messages}}
|
||||
<li class="mail-row" data-id="{{.ID}}">
|
||||
<label class="cell-check" onclick="event.stopPropagation()">
|
||||
<input type="checkbox" class="row-check" data-id="{{.ID}}">
|
||||
</label>
|
||||
<span class="cell-avatar">
|
||||
<span class="avatar" style="{{avatarStyle .ToAddr}}">{{initial (mailName .ToAddr)}}</span>
|
||||
</span>
|
||||
<span class="cell-from" title="收件人:{{.ToAddr}}">致:{{mailName .ToAddr}}</span>
|
||||
<span class="cell-subject-wrap">
|
||||
<a class="cell-subject" href="/drafts/{{.ID}}">
|
||||
{{if .Subject}}{{.Subject}}{{else}}(无主题){{end}}
|
||||
</a>
|
||||
</span>
|
||||
<span class="cell-snippet">
|
||||
{{if .TextBody}}{{truncate .TextBody 80}}{{else if .HtmlBody}}[HTML 邮件]{{end}}
|
||||
</span>
|
||||
<span class="cell-date">{{shortDate .Date}}</span>
|
||||
<form method="POST" action="/mail/delete/{{.ID}}" class="row-del"
|
||||
onsubmit="return confirm('确定要删除这封草稿吗?');">
|
||||
<button type="submit" class="icon-btn" title="删除">
|
||||
<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><polyline points="3 6 5 6 21 6"/><path d="M19 6v14a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2V6m3 0V4a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v2"/></svg>
|
||||
</button>
|
||||
</form>
|
||||
</li>
|
||||
{{end}}
|
||||
</ul>
|
||||
{{end}}
|
||||
|
||||
<div class="list-footer">
|
||||
<span class="page-num">第 {{.page}} / {{if .totalPages}}{{.totalPages}}{{else}}1{{end}} 页</span>
|
||||
<div class="pager">
|
||||
{{if gt .page 1}}
|
||||
<a class="page-btn" href="/drafts?page={{sub .page 1}}">
|
||||
<svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><polyline points="15 18 9 12 15 6"/></svg>
|
||||
上一页
|
||||
</a>
|
||||
<div class="content">
|
||||
<div class="card">
|
||||
<h2 style="margin-bottom:16px;">草稿箱</h2>
|
||||
{{if not .messages}}
|
||||
<p style="color:#7f8c8d;text-align:center;padding:40px 0;">暂无草稿邮件</p>
|
||||
{{else}}
|
||||
<span class="page-btn disabled">上一页</span>
|
||||
{{end}}
|
||||
{{if lt .page .totalPages}}
|
||||
<a class="page-btn" href="/drafts?page={{add .page 1}}">
|
||||
下一页
|
||||
<svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><polyline points="9 18 15 12 9 6"/></svg>
|
||||
</a>
|
||||
{{else}}
|
||||
<span class="page-btn disabled">下一页</span>
|
||||
<table>
|
||||
<thead>
|
||||
<tr>
|
||||
<th style="width:25%;">发件人/收件人</th>
|
||||
<th style="width:45%;">主题</th>
|
||||
<th style="width:20%;">时间</th>
|
||||
<th style="width:10%;">操作</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{{range .messages}}
|
||||
<tr>
|
||||
<td>{{.ToAddr}}</td>
|
||||
<td>
|
||||
<a href="/drafts/{{.ID}}" class="message-subject">
|
||||
{{if .Subject}}{{.Subject}}{{else}}(无主题){{end}}
|
||||
</a>
|
||||
</td>
|
||||
<td>{{.Date.Format "2006-01-02 15:04"}}</td>
|
||||
<td>
|
||||
<form method="POST" action="/mail/delete/{{.ID}}" style="display:inline;"
|
||||
onsubmit="return confirm('确定要删除这封邮件吗?');">
|
||||
<button type="submit" class="btn btn-danger btn-sm">删除</button>
|
||||
</form>
|
||||
</td>
|
||||
</tr>
|
||||
{{end}}
|
||||
</tbody>
|
||||
</table>
|
||||
{{end}}
|
||||
</div>
|
||||
{{if .totalPages}}
|
||||
<div class="pagination">
|
||||
{{if gt .page 1}}
|
||||
<a href="/drafts?page={{sub .page 1}}">上一页</a>
|
||||
{{end}}
|
||||
<span>第 {{.page}} / {{.totalPages}} 页</span>
|
||||
{{if lt .page .totalPages}}
|
||||
<a href="/drafts?page={{add .page 1}}">下一页</a>
|
||||
{{end}}
|
||||
</div>
|
||||
{{end}}
|
||||
</div>
|
||||
</main>
|
||||
</div>
|
||||
</div>
|
||||
<script>
|
||||
(function () {
|
||||
var searchInput = document.getElementById('mail-search');
|
||||
var rows = Array.prototype.slice.call(document.querySelectorAll('.mail-row'));
|
||||
var selectAll = document.getElementById('select-all');
|
||||
var btnDelete = document.getElementById('btn-delete');
|
||||
|
||||
rows.forEach(function (row) {
|
||||
row.addEventListener('click', function (e) {
|
||||
if (e.target.closest('.cell-check') || e.target.closest('.row-del')) return;
|
||||
window.location.href = row.querySelector('.cell-subject').getAttribute('href');
|
||||
});
|
||||
});
|
||||
|
||||
selectAll && selectAll.addEventListener('change', function () {
|
||||
rows.forEach(function (row) {
|
||||
var cb = row.querySelector('.row-check');
|
||||
cb.checked = selectAll.checked;
|
||||
row.classList.toggle('selected', cb.checked);
|
||||
});
|
||||
updateDeleteState();
|
||||
});
|
||||
rows.forEach(function (row) {
|
||||
var cb = row.querySelector('.row-check');
|
||||
cb.addEventListener('change', function () {
|
||||
row.classList.toggle('selected', cb.checked);
|
||||
if (!cb.checked && selectAll) selectAll.checked = false;
|
||||
updateDeleteState();
|
||||
});
|
||||
});
|
||||
|
||||
function updateDeleteState() {
|
||||
if (!btnDelete) return;
|
||||
var n = rows.filter(function (r) { return r.querySelector('.row-check').checked; }).length;
|
||||
btnDelete.disabled = n === 0;
|
||||
}
|
||||
|
||||
btnDelete && btnDelete.addEventListener('click', function () {
|
||||
var ids = rows.filter(function (r) { return r.querySelector('.row-check').checked; })
|
||||
.map(function (r) { return r.dataset.id; });
|
||||
if (!ids.length) return;
|
||||
if (!confirm('确定要删除选中的 ' + ids.length + ' 封邮件吗?')) return;
|
||||
var done = 0;
|
||||
ids.forEach(function (id) {
|
||||
fetch('/mail/delete/' + id, { method: 'POST', body: new FormData() })
|
||||
.then(function () { if (++done === ids.length) window.location.reload(); })
|
||||
.catch(function () { if (++done === ids.length) window.location.reload(); });
|
||||
});
|
||||
});
|
||||
|
||||
var btnRefresh = document.getElementById('btn-refresh');
|
||||
btnRefresh && btnRefresh.addEventListener('click', function () { window.location.reload(); });
|
||||
|
||||
searchInput && searchInput.addEventListener('input', function () {
|
||||
var q = searchInput.value.trim().toLowerCase();
|
||||
rows.forEach(function (row) {
|
||||
var text = row.textContent.toLowerCase();
|
||||
row.style.display = (!q || text.indexOf(q) !== -1) ? '' : 'none';
|
||||
});
|
||||
});
|
||||
})();
|
||||
</script>
|
||||
</body>
|
||||
</html>
|
||||
{{end}}
|
||||
@@ -3,154 +3,73 @@
|
||||
<html lang="zh-CN">
|
||||
<head>
|
||||
<meta charset="UTF-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0, viewport-fit=cover">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||||
<title>收件箱 - MailGo</title>
|
||||
{{template "styles" .}}
|
||||
</head>
|
||||
<body class="page-list">
|
||||
<body>
|
||||
{{template "navbar" .}}
|
||||
<div class="app-body">
|
||||
{{template "sidebar" .}}
|
||||
<main class="mail-main">
|
||||
<div class="list-toolbar">
|
||||
<label class="check-all" title="全选/取消全选">
|
||||
<input type="checkbox" id="select-all">
|
||||
全选
|
||||
</label>
|
||||
<button type="button" class="tb-btn" id="btn-refresh" title="刷新">
|
||||
<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><polyline points="23 4 23 10 17 10"/><path d="M20.49 15a9 9 0 1 1-2.12-9.36L23 10"/></svg>
|
||||
刷新
|
||||
</button>
|
||||
<button type="button" class="tb-btn danger" id="btn-delete" disabled>
|
||||
<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><polyline points="3 6 5 6 21 6"/><path d="M19 6v14a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2V6m3 0V4a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v2"/></svg>
|
||||
删除
|
||||
</button>
|
||||
<div class="toolbar-spacer"></div>
|
||||
<span class="page-info">共 {{.total}} 封</span>
|
||||
<div class="container">
|
||||
<div class="clearfix">
|
||||
<div class="sidebar">
|
||||
<a href="/inbox" class="{{if eq .activeFolder `inbox`}}active{{end}}">收件箱</a>
|
||||
<a href="/drafts" class="{{if eq .activeFolder `drafts`}}active{{end}}">草稿箱</a>
|
||||
<a href="/sent" class="{{if eq .activeFolder `sent`}}active{{end}}">发件箱</a>
|
||||
<a href="/compose" class="{{if eq .activeFolder `compose`}}active{{end}}">撰写邮件</a>
|
||||
<a href="/settings" class="{{if eq .activeFolder `settings`}}active{{end}}">设置</a>
|
||||
</div>
|
||||
|
||||
{{if not .messages}}
|
||||
<div class="mail-list">
|
||||
<div class="empty-tip"><span class="empty-icon">📭</span>收件箱暂无邮件</div>
|
||||
</div>
|
||||
{{else}}
|
||||
<ul class="mail-list">
|
||||
{{range .messages}}
|
||||
<li class="mail-row {{if not .IsRead}}unread{{end}}" data-id="{{.ID}}">
|
||||
<label class="cell-check" onclick="event.stopPropagation()">
|
||||
<input type="checkbox" class="row-check" data-id="{{.ID}}">
|
||||
</label>
|
||||
<span class="cell-avatar">
|
||||
<span class="avatar" style="{{avatarStyle .FromAddr}}">{{initial (mailName (decodeHeader .FromAddr))}}</span>
|
||||
</span>
|
||||
<span class="cell-from" title="{{decodeHeader .FromAddr}}">{{mailName (decodeHeader .FromAddr)}}</span>
|
||||
<span class="cell-subject-wrap">
|
||||
{{if not .IsRead}}<span class="unread-dot"></span>{{end}}
|
||||
<a class="cell-subject" href="/inbox/{{.ID}}">
|
||||
{{if .Subject}}{{.Subject}}{{else}}(无主题){{end}}
|
||||
</a>
|
||||
</span>
|
||||
<span class="cell-snippet">
|
||||
{{if .TextBody}}{{truncate .TextBody 80}}{{else if .HtmlBody}}[HTML 邮件]{{end}}
|
||||
</span>
|
||||
<span class="cell-date">{{shortDate .Date}}</span>
|
||||
</li>
|
||||
{{end}}
|
||||
</ul>
|
||||
{{end}}
|
||||
|
||||
<div class="list-footer">
|
||||
<span class="page-num">第 {{.page}} / {{if .totalPages}}{{.totalPages}}{{else}}1{{end}} 页</span>
|
||||
<div class="pager">
|
||||
{{if gt .page 1}}
|
||||
<a class="page-btn" href="/inbox?page={{sub .page 1}}">
|
||||
<svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><polyline points="15 18 9 12 15 6"/></svg>
|
||||
上一页
|
||||
</a>
|
||||
<div class="content">
|
||||
<div class="card">
|
||||
<h2 style="margin-bottom:16px;">收件箱</h2>
|
||||
{{if not .messages}}
|
||||
<p style="color:#7f8c8d;text-align:center;padding:40px 0;">暂无邮件</p>
|
||||
{{else}}
|
||||
<span class="page-btn disabled">上一页</span>
|
||||
{{end}}
|
||||
{{if lt .page .totalPages}}
|
||||
<a class="page-btn" href="/inbox?page={{add .page 1}}">
|
||||
下一页
|
||||
<svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><polyline points="9 18 15 12 9 6"/></svg>
|
||||
</a>
|
||||
{{else}}
|
||||
<span class="page-btn disabled">下一页</span>
|
||||
<table>
|
||||
<thead>
|
||||
<tr>
|
||||
<th style="width:25%;">发件人</th>
|
||||
<th style="width:45%;">主题</th>
|
||||
<th style="width:20%;">时间</th>
|
||||
<th style="width:10%;">操作</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{{range .messages}}
|
||||
<tr class="{{if not .IsRead}}unread{{end}}">
|
||||
<td>{{decodeHeader .FromAddr}}</td>
|
||||
<td>
|
||||
<a href="/inbox/{{.ID}}" class="message-subject">
|
||||
{{if .Subject}}{{.Subject}}{{else}}(无主题){{end}}
|
||||
</a>
|
||||
</td>
|
||||
<td>{{.Date.Format "2006-01-02 15:04"}}</td>
|
||||
<td>
|
||||
{{if not .IsRead}}
|
||||
<form method="POST" action="/mail/read/{{.ID}}" style="display:inline;">
|
||||
<button type="submit" class="btn btn-primary btn-sm">已读</button>
|
||||
</form>
|
||||
{{end}}
|
||||
</td>
|
||||
</tr>
|
||||
{{end}}
|
||||
</tbody>
|
||||
</table>
|
||||
{{end}}
|
||||
</div>
|
||||
{{if .totalPages}}
|
||||
<div class="pagination">
|
||||
{{if gt .page 1}}
|
||||
<a href="/inbox?page={{sub .page 1}}">上一页</a>
|
||||
{{end}}
|
||||
<span>第 {{.page}} / {{.totalPages}} 页</span>
|
||||
{{if lt .page .totalPages}}
|
||||
<a href="/inbox?page={{add .page 1}}">下一页</a>
|
||||
{{end}}
|
||||
</div>
|
||||
{{end}}
|
||||
</div>
|
||||
</main>
|
||||
</div>
|
||||
</div>
|
||||
<script>
|
||||
(function () {
|
||||
var searchInput = document.getElementById('mail-search');
|
||||
var rows = Array.prototype.slice.call(document.querySelectorAll('.mail-row'));
|
||||
var selectAll = document.getElementById('select-all');
|
||||
var btnDelete = document.getElementById('btn-delete');
|
||||
|
||||
// 行点击跳转(复选框除外)
|
||||
rows.forEach(function (row) {
|
||||
row.addEventListener('click', function (e) {
|
||||
if (e.target.closest('.cell-check')) return;
|
||||
window.location.href = row.querySelector('.cell-subject').getAttribute('href');
|
||||
});
|
||||
});
|
||||
|
||||
// 全选
|
||||
selectAll && selectAll.addEventListener('change', function () {
|
||||
rows.forEach(function (row) {
|
||||
var cb = row.querySelector('.row-check');
|
||||
cb.checked = selectAll.checked;
|
||||
row.classList.toggle('selected', cb.checked);
|
||||
});
|
||||
updateDeleteState();
|
||||
});
|
||||
rows.forEach(function (row) {
|
||||
var cb = row.querySelector('.row-check');
|
||||
cb.addEventListener('change', function () {
|
||||
row.classList.toggle('selected', cb.checked);
|
||||
if (!cb.checked && selectAll) selectAll.checked = false;
|
||||
updateDeleteState();
|
||||
});
|
||||
});
|
||||
|
||||
function updateDeleteState() {
|
||||
if (!btnDelete) return;
|
||||
var n = rows.filter(function (r) { return r.querySelector('.row-check').checked; }).length;
|
||||
btnDelete.disabled = n === 0;
|
||||
}
|
||||
|
||||
// 批量删除
|
||||
btnDelete && btnDelete.addEventListener('click', function () {
|
||||
var ids = rows.filter(function (r) { return r.querySelector('.row-check').checked; })
|
||||
.map(function (r) { return r.dataset.id; });
|
||||
if (!ids.length) return;
|
||||
if (!confirm('确定要删除选中的 ' + ids.length + ' 封邮件吗?')) return;
|
||||
var done = 0;
|
||||
ids.forEach(function (id) {
|
||||
var fd = new FormData();
|
||||
fd.append('_method', 'DELETE');
|
||||
fetch('/mail/delete/' + id, { method: 'POST', body: fd })
|
||||
.then(function () { if (++done === ids.length) window.location.reload(); })
|
||||
.catch(function () { if (++done === ids.length) window.location.reload(); });
|
||||
});
|
||||
});
|
||||
|
||||
// 刷新
|
||||
var btnRefresh = document.getElementById('btn-refresh');
|
||||
btnRefresh && btnRefresh.addEventListener('click', function () { window.location.reload(); });
|
||||
|
||||
// 搜索过滤(发件人 / 主题 / 摘要)
|
||||
searchInput && searchInput.addEventListener('input', function () {
|
||||
var q = searchInput.value.trim().toLowerCase();
|
||||
rows.forEach(function (row) {
|
||||
var text = row.textContent.toLowerCase();
|
||||
row.style.display = (!q || text.indexOf(q) !== -1) ? '' : 'none';
|
||||
});
|
||||
});
|
||||
})();
|
||||
</script>
|
||||
</body>
|
||||
</html>
|
||||
{{end}}
|
||||
@@ -3,55 +3,54 @@
|
||||
<html lang="zh-CN">
|
||||
<head>
|
||||
<meta charset="UTF-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0, viewport-fit=cover">
|
||||
<title>登录 - MailGo 邮箱</title>
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||||
<title>登录 - MailGo</title>
|
||||
{{template "styles" .}}
|
||||
</head>
|
||||
<body class="login-page">
|
||||
<div class="login-card">
|
||||
<div class="login-logo">
|
||||
<span class="logo-icon" style="width:44px;height:44px;font-size:22px;border-radius:12px;">✉</span>
|
||||
<span style="font-size:26px;font-weight:700;color:var(--primary);">MailGo<em style="font-style:normal;font-weight:400;font-size:15px;color:var(--text-2);margin-left:4px;">邮箱</em></span>
|
||||
<body>
|
||||
{{template "navbar" .}}
|
||||
<div class="container">
|
||||
<div style="max-width:400px;margin:80px auto;">
|
||||
<div class="card">
|
||||
<h2 style="text-align:center;margin-bottom:24px;">MailGo 登录</h2>
|
||||
{{if .error}}<div class="alert alert-error">{{.error}}</div>{{end}}
|
||||
<form method="POST" action="/login">
|
||||
<div class="form-group">
|
||||
<label>邮箱地址</label>
|
||||
<input type="email" name="email" required autofocus placeholder="admin@example.com">
|
||||
</div>
|
||||
<div class="form-group">
|
||||
<label>密码</label>
|
||||
<input type="password" name="password" required placeholder="请输入密码">
|
||||
</div>
|
||||
<button type="submit" class="btn btn-primary" style="width:100%;">登录</button>
|
||||
</form>
|
||||
|
||||
{{if or .oauth2Enabled .ldapEnabled}}
|
||||
<div style="text-align:center;margin:16px 0;color:#7f8c8d;">─── 或 ───</div>
|
||||
{{end}}
|
||||
|
||||
{{if .ldapEnabled}}
|
||||
<form method="POST" action="/login/ldap">
|
||||
<div class="form-group">
|
||||
<label>LDAP 用户名</label>
|
||||
<input type="text" name="username" placeholder="LDAP 用户名">
|
||||
</div>
|
||||
<div class="form-group">
|
||||
<label>LDAP 密码</label>
|
||||
<input type="password" name="password" placeholder="LDAP 密码">
|
||||
</div>
|
||||
<button type="submit" class="btn" style="width:100%;background:#8e44ad;color:#fff;">LDAP 登录</button>
|
||||
</form>
|
||||
{{end}}
|
||||
|
||||
{{if .oauth2Enabled}}
|
||||
<a href="/auth/oauth2" class="btn" style="width:100%;background:#3498db;color:#fff;text-align:center;display:block;margin-top:8px;">
|
||||
{{if eq .oauth2Provider "google"}}Google{{else if eq .oauth2Provider "github"}}GitHub{{else}}OAuth2{{end}} 登录
|
||||
</a>
|
||||
{{end}}
|
||||
</div>
|
||||
</div>
|
||||
<div class="login-sub">登录您的邮箱账户</div>
|
||||
|
||||
{{if .error}}<div class="alert alert-error">{{.error}}</div>{{end}}
|
||||
|
||||
<form method="POST" action="/login">
|
||||
<div class="form-group">
|
||||
<label>邮箱地址</label>
|
||||
<input type="email" name="email" required autofocus placeholder="user@example.com" style="padding:11px 14px;border-radius:8px;">
|
||||
</div>
|
||||
<div class="form-group">
|
||||
<label>密码</label>
|
||||
<input type="password" name="password" required placeholder="请输入密码" style="padding:11px 14px;border-radius:8px;">
|
||||
</div>
|
||||
<button type="submit" class="btn btn-primary" style="width:100%;padding:11px 16px;font-size:15px;border-radius:8px;">登 录</button>
|
||||
</form>
|
||||
|
||||
{{if or .oauth2Enabled .ldapEnabled}}
|
||||
<div class="divider">或</div>
|
||||
{{end}}
|
||||
|
||||
{{if .ldapEnabled}}
|
||||
<form method="POST" action="/login/ldap" style="margin-bottom:10px;">
|
||||
<div class="form-group">
|
||||
<label>LDAP 用户名</label>
|
||||
<input type="text" name="username" placeholder="LDAP 用户名">
|
||||
</div>
|
||||
<div class="form-group">
|
||||
<label>LDAP 密码</label>
|
||||
<input type="password" name="password" placeholder="LDAP 密码">
|
||||
</div>
|
||||
<button type="submit" class="btn" style="width:100%;background:#7b5cd6;color:#fff;">LDAP 登录</button>
|
||||
</form>
|
||||
{{end}}
|
||||
|
||||
{{if .oauth2Enabled}}
|
||||
<a href="/auth/oauth2" class="btn btn-primary" style="width:100%;text-align:center;display:block;margin-top:4px;">
|
||||
{{if eq .oauth2Provider "google"}}Google{{else if eq .oauth2Provider "github"}}GitHub{{else}}OAuth2{{end}} 登录
|
||||
</a>
|
||||
{{end}}
|
||||
</div>
|
||||
</body>
|
||||
</html>
|
||||
|
||||
@@ -3,152 +3,72 @@
|
||||
<html lang="zh-CN">
|
||||
<head>
|
||||
<meta charset="UTF-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0, viewport-fit=cover">
|
||||
<title>已发送 - MailGo</title>
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||||
<title>发件箱 - MailGo</title>
|
||||
{{template "styles" .}}
|
||||
</head>
|
||||
<body class="page-list">
|
||||
<body>
|
||||
{{template "navbar" .}}
|
||||
<div class="app-body">
|
||||
{{template "sidebar" .}}
|
||||
<main class="mail-main">
|
||||
<div class="list-toolbar">
|
||||
<label class="check-all" title="全选/取消全选">
|
||||
<input type="checkbox" id="select-all">
|
||||
全选
|
||||
</label>
|
||||
<button type="button" class="tb-btn" id="btn-refresh" title="刷新">
|
||||
<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><polyline points="23 4 23 10 17 10"/><path d="M20.49 15a9 9 0 1 1-2.12-9.36L23 10"/></svg>
|
||||
刷新
|
||||
</button>
|
||||
<button type="button" class="tb-btn danger" id="btn-delete" disabled>
|
||||
<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><polyline points="3 6 5 6 21 6"/><path d="M19 6v14a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2V6m3 0V4a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v2"/></svg>
|
||||
删除
|
||||
</button>
|
||||
<div class="toolbar-spacer"></div>
|
||||
<span class="page-info">共 {{.total}} 封</span>
|
||||
<div class="container">
|
||||
<div class="clearfix">
|
||||
<div class="sidebar">
|
||||
<a href="/inbox" class="{{if eq .activeFolder `inbox`}}active{{end}}">收件箱</a>
|
||||
<a href="/drafts" class="{{if eq .activeFolder `drafts`}}active{{end}}">草稿箱</a>
|
||||
<a href="/sent" class="{{if eq .activeFolder `sent`}}active{{end}}">发件箱</a>
|
||||
<a href="/compose" class="{{if eq .activeFolder `compose`}}active{{end}}">撰写邮件</a>
|
||||
<a href="/settings" class="{{if eq .activeFolder `settings`}}active{{end}}">设置</a>
|
||||
</div>
|
||||
|
||||
{{if not .messages}}
|
||||
<div class="mail-list">
|
||||
<div class="empty-tip"><span class="empty-icon">📤</span>已发送暂无邮件</div>
|
||||
</div>
|
||||
{{else}}
|
||||
<ul class="mail-list">
|
||||
{{range .messages}}
|
||||
<li class="mail-row" data-id="{{.ID}}">
|
||||
<label class="cell-check" onclick="event.stopPropagation()">
|
||||
<input type="checkbox" class="row-check" data-id="{{.ID}}">
|
||||
</label>
|
||||
<span class="cell-avatar">
|
||||
<span class="avatar" style="{{avatarStyle .ToAddr}}">{{initial (mailName .ToAddr)}}</span>
|
||||
</span>
|
||||
<span class="cell-from" title="收件人:{{.ToAddr}}">{{mailName .ToAddr}}</span>
|
||||
<span class="cell-subject-wrap">
|
||||
<a class="cell-subject" href="/sent/{{.ID}}">
|
||||
{{if .Subject}}{{.Subject}}{{else}}(无主题){{end}}
|
||||
</a>
|
||||
</span>
|
||||
<span class="cell-snippet">
|
||||
{{if .TextBody}}{{truncate .TextBody 80}}{{else if .HtmlBody}}[HTML 邮件]{{end}}
|
||||
</span>
|
||||
<span class="cell-date">{{shortDate .Date}}</span>
|
||||
<form method="POST" action="/mail/delete/{{.ID}}" class="row-del"
|
||||
onsubmit="return confirm('确定要删除这封邮件吗?');">
|
||||
<button type="submit" class="icon-btn" title="删除">
|
||||
<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><polyline points="3 6 5 6 21 6"/><path d="M19 6v14a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2V6m3 0V4a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v2"/></svg>
|
||||
</button>
|
||||
</form>
|
||||
</li>
|
||||
{{end}}
|
||||
</ul>
|
||||
{{end}}
|
||||
|
||||
<div class="list-footer">
|
||||
<span class="page-num">第 {{.page}} / {{if .totalPages}}{{.totalPages}}{{else}}1{{end}} 页</span>
|
||||
<div class="pager">
|
||||
{{if gt .page 1}}
|
||||
<a class="page-btn" href="/sent?page={{sub .page 1}}">
|
||||
<svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><polyline points="15 18 9 12 15 6"/></svg>
|
||||
上一页
|
||||
</a>
|
||||
<div class="content">
|
||||
<div class="card">
|
||||
<h2 style="margin-bottom:16px;">发件箱</h2>
|
||||
{{if not .messages}}
|
||||
<p style="color:#7f8c8d;text-align:center;padding:40px 0;">暂无已发送邮件</p>
|
||||
{{else}}
|
||||
<span class="page-btn disabled">上一页</span>
|
||||
{{end}}
|
||||
{{if lt .page .totalPages}}
|
||||
<a class="page-btn" href="/sent?page={{add .page 1}}">
|
||||
下一页
|
||||
<svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><polyline points="9 18 15 12 9 6"/></svg>
|
||||
</a>
|
||||
{{else}}
|
||||
<span class="page-btn disabled">下一页</span>
|
||||
<table>
|
||||
<thead>
|
||||
<tr>
|
||||
<th style="width:25%;">收件人</th>
|
||||
<th style="width:45%;">主题</th>
|
||||
<th style="width:20%;">时间</th>
|
||||
<th style="width:10%;">操作</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{{range .messages}}
|
||||
<tr>
|
||||
<td>{{.ToAddr}}</td>
|
||||
<td>
|
||||
<a href="/sent/{{.ID}}" class="message-subject">
|
||||
{{if .Subject}}{{.Subject}}{{else}}(无主题){{end}}
|
||||
</a>
|
||||
</td>
|
||||
<td>{{.Date.Format "2006-01-02 15:04"}}</td>
|
||||
<td>
|
||||
<form method="POST" action="/mail/delete/{{.ID}}" style="display:inline;"
|
||||
onsubmit="return confirm('确定要删除这封邮件吗?');">
|
||||
<button type="submit" class="btn btn-danger btn-sm">删除</button>
|
||||
</form>
|
||||
</td>
|
||||
</tr>
|
||||
{{end}}
|
||||
</tbody>
|
||||
</table>
|
||||
{{end}}
|
||||
</div>
|
||||
{{if .totalPages}}
|
||||
<div class="pagination">
|
||||
{{if gt .page 1}}
|
||||
<a href="/sent?page={{sub .page 1}}">上一页</a>
|
||||
{{end}}
|
||||
<span>第 {{.page}} / {{.totalPages}} 页</span>
|
||||
{{if lt .page .totalPages}}
|
||||
<a href="/sent?page={{add .page 1}}">下一页</a>
|
||||
{{end}}
|
||||
</div>
|
||||
{{end}}
|
||||
</div>
|
||||
</main>
|
||||
</div>
|
||||
</div>
|
||||
<script>
|
||||
(function () {
|
||||
var searchInput = document.getElementById('mail-search');
|
||||
var rows = Array.prototype.slice.call(document.querySelectorAll('.mail-row'));
|
||||
var selectAll = document.getElementById('select-all');
|
||||
var btnDelete = document.getElementById('btn-delete');
|
||||
|
||||
rows.forEach(function (row) {
|
||||
row.addEventListener('click', function (e) {
|
||||
if (e.target.closest('.cell-check') || e.target.closest('.row-del')) return;
|
||||
window.location.href = row.querySelector('.cell-subject').getAttribute('href');
|
||||
});
|
||||
});
|
||||
|
||||
selectAll && selectAll.addEventListener('change', function () {
|
||||
rows.forEach(function (row) {
|
||||
var cb = row.querySelector('.row-check');
|
||||
cb.checked = selectAll.checked;
|
||||
row.classList.toggle('selected', cb.checked);
|
||||
});
|
||||
updateDeleteState();
|
||||
});
|
||||
rows.forEach(function (row) {
|
||||
var cb = row.querySelector('.row-check');
|
||||
cb.addEventListener('change', function () {
|
||||
row.classList.toggle('selected', cb.checked);
|
||||
if (!cb.checked && selectAll) selectAll.checked = false;
|
||||
updateDeleteState();
|
||||
});
|
||||
});
|
||||
|
||||
function updateDeleteState() {
|
||||
if (!btnDelete) return;
|
||||
var n = rows.filter(function (r) { return r.querySelector('.row-check').checked; }).length;
|
||||
btnDelete.disabled = n === 0;
|
||||
}
|
||||
|
||||
btnDelete && btnDelete.addEventListener('click', function () {
|
||||
var ids = rows.filter(function (r) { return r.querySelector('.row-check').checked; })
|
||||
.map(function (r) { return r.dataset.id; });
|
||||
if (!ids.length) return;
|
||||
if (!confirm('确定要删除选中的 ' + ids.length + ' 封邮件吗?')) return;
|
||||
var done = 0;
|
||||
ids.forEach(function (id) {
|
||||
fetch('/mail/delete/' + id, { method: 'POST', body: new FormData() })
|
||||
.then(function () { if (++done === ids.length) window.location.reload(); })
|
||||
.catch(function () { if (++done === ids.length) window.location.reload(); });
|
||||
});
|
||||
});
|
||||
|
||||
var btnRefresh = document.getElementById('btn-refresh');
|
||||
btnRefresh && btnRefresh.addEventListener('click', function () { window.location.reload(); });
|
||||
|
||||
searchInput && searchInput.addEventListener('input', function () {
|
||||
var q = searchInput.value.trim().toLowerCase();
|
||||
rows.forEach(function (row) {
|
||||
var text = row.textContent.toLowerCase();
|
||||
row.style.display = (!q || text.indexOf(q) !== -1) ? '' : 'none';
|
||||
});
|
||||
});
|
||||
})();
|
||||
</script>
|
||||
</body>
|
||||
</html>
|
||||
{{end}}
|
||||
@@ -3,78 +3,46 @@
|
||||
<html lang="zh-CN">
|
||||
<head>
|
||||
<meta charset="UTF-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0, viewport-fit=cover">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||||
<title>设置 - MailGo</title>
|
||||
{{template "styles" .}}
|
||||
</head>
|
||||
<body class="page-settings">
|
||||
<body>
|
||||
{{template "navbar" .}}
|
||||
<div class="app-body">
|
||||
{{template "sidebar" .}}
|
||||
<main class="mail-main settings-main">
|
||||
{{if .error}}<div class="alert alert-error">{{.error}}</div>{{end}}
|
||||
{{if .success}}<div class="alert alert-success">{{.success}}</div>{{end}}
|
||||
|
||||
<div class="card" style="max-width:720px;">
|
||||
<h2 style="font-size:17px;margin-bottom:18px;display:flex;align-items:center;gap:10px;">
|
||||
<svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="#1677ff" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><circle cx="12" cy="12" r="3"/><path d="M19.4 15a1.65 1.65 0 0 0 .33 1.82l.06.06a2 2 0 0 1 0 2.83 2 2 0 0 1-2.83 0l-.06-.06a1.65 1.65 0 0 0-1.82-.33 1.65 1.65 0 0 0-1 1.51V21a2 2 0 0 1-2 2 2 2 0 0 1-2-2v-.09A1.65 1.65 0 0 0 9 19.4a1.65 1.65 0 0 0-1.82.33l-.06.06a2 2 0 0 1-2.83 0 2 2 0 0 1 0-2.83l.06-.06a1.65 1.65 0 0 0 .33-1.82 1.65 1.65 0 0 0-1.51-1H3a2 2 0 0 1-2-2 2 2 0 0 1 2-2h.09A1.65 1.65 0 0 0 4.6 9a1.65 1.65 0 0 0-.33-1.82l-.06-.06a2 2 0 0 1 0-2.83 2 2 0 0 1 2.83 0l.06.06a1.65 1.65 0 0 0 1.82.33H9a1.65 1.65 0 0 0 1-1.51V3a2 2 0 0 1 2-2 2 2 0 0 1 2 2v.09a1.65 1.65 0 0 0 1 1.51 1.65 1.65 0 0 0 1.82-.33l.06-.06a2 2 0 0 1 2.83 0 2 2 0 0 1 0 2.83l-.06.06a1.65 1.65 0 0 0-.33 1.82V9a1.65 1.65 0 0 0 1.51 1H21a2 2 0 0 1 2 2 2 2 0 0 1-2 2h-.09a1.65 1.65 0 0 0-1.51 1z"/></svg>
|
||||
账号信息
|
||||
</h2>
|
||||
<div style="display:flex;align-items:center;gap:14px;margin-bottom:20px;">
|
||||
<span class="avatar" style="width:52px;height:52px;font-size:22px;{{avatarStyle .currentUser.Username}}">{{initial .currentUser.Username}}</span>
|
||||
<div>
|
||||
<div style="font-size:16px;font-weight:600;">{{.currentUser.Username}}@{{.currentUser.Domain.Name}}</div>
|
||||
<div style="color:var(--text-3);font-size:12.5px;margin-top:3px;">
|
||||
已用 {{formatBytes .currentUser.UsedBytes}} / 配额 {{formatBytes .currentUser.QuotaBytes}}
|
||||
{{if .currentUser.IsAdmin}} · 管理员{{end}}
|
||||
<div class="container">
|
||||
<div class="clearfix">
|
||||
<div class="sidebar">
|
||||
<a href="/inbox" class="{{if eq .activeFolder `inbox`}}active{{end}}">收件箱</a>
|
||||
<a href="/drafts" class="{{if eq .activeFolder `drafts`}}active{{end}}">草稿箱</a>
|
||||
<a href="/sent" class="{{if eq .activeFolder `sent`}}active{{end}}">发件箱</a>
|
||||
<a href="/compose" class="{{if eq .activeFolder `compose`}}active{{end}}">撰写邮件</a>
|
||||
<a href="/settings" class="{{if eq .activeFolder `settings`}}active{{end}}">设置</a>
|
||||
</div>
|
||||
<div class="content">
|
||||
<div class="card">
|
||||
<h2 style="margin-bottom:16px;">设置</h2>
|
||||
{{if .error}}<div class="alert alert-error">{{.error}}</div>{{end}}
|
||||
{{if .success}}<div class="alert alert-success">{{.success}}</div>{{end}}
|
||||
<h3 style="margin-bottom:12px;">修改密码</h3>
|
||||
<form method="POST" action="/settings">
|
||||
<div class="form-group">
|
||||
<label>当前密码</label>
|
||||
<input type="password" name="old_password" required placeholder="请输入当前密码">
|
||||
</div>
|
||||
</div>
|
||||
<div class="form-group">
|
||||
<label>新密码</label>
|
||||
<input type="password" name="new_password" required placeholder="请输入新密码">
|
||||
</div>
|
||||
<div class="form-group">
|
||||
<label>确认新密码</label>
|
||||
<input type="password" name="confirm_password" required placeholder="请再次输入新密码">
|
||||
</div>
|
||||
<button type="submit" class="btn btn-primary">修改密码</button>
|
||||
</form>
|
||||
</div>
|
||||
<div class="quota-bar" style="width:100%;" data-used="{{.currentUser.UsedBytes}}" data-quota="{{.currentUser.QuotaBytes}}"><i></i></div>
|
||||
</div>
|
||||
|
||||
<div class="card" style="max-width:720px;">
|
||||
<h2 style="font-size:17px;margin-bottom:18px;">修改密码</h2>
|
||||
<form method="POST" action="/settings" style="max-width:420px;">
|
||||
<div class="form-group">
|
||||
<label>当前密码</label>
|
||||
<input type="password" name="old_password" required placeholder="请输入当前密码" autocomplete="current-password">
|
||||
</div>
|
||||
<div class="form-group">
|
||||
<label>新密码</label>
|
||||
<input type="password" name="new_password" required placeholder="请输入新密码" autocomplete="new-password">
|
||||
</div>
|
||||
<div class="form-group">
|
||||
<label>确认新密码</label>
|
||||
<input type="password" name="confirm_password" required placeholder="请再次输入新密码" autocomplete="new-password">
|
||||
</div>
|
||||
<button type="submit" class="btn btn-primary">修改密码</button>
|
||||
</form>
|
||||
</div>
|
||||
|
||||
<div class="card" style="max-width:720px;">
|
||||
<h2 style="font-size:17px;margin-bottom:10px;">帮助</h2>
|
||||
<p style="color:var(--text-2);font-size:13.5px;line-height:1.9;">
|
||||
客户端收发信(IMAP / SMTP)配置:<br>
|
||||
IMAP 服务器:{{.currentUser.Domain.Name}} 端口 143 / SSL 993<br>
|
||||
SMTP 服务器:{{.currentUser.Domain.Name}} 端口 587(提交)/ SSL 465
|
||||
</p>
|
||||
</div>
|
||||
</main>
|
||||
</div>
|
||||
</div>
|
||||
<script>
|
||||
(function () {
|
||||
var bar = document.querySelector('.quota-bar[data-quota]');
|
||||
if (bar) {
|
||||
var used = parseInt(bar.dataset.used, 10) || 0;
|
||||
var quota = parseInt(bar.dataset.quota, 10) || 1;
|
||||
var pct = Math.min(100, Math.round(used / quota * 100));
|
||||
bar.querySelector('i').style.width = pct + '%';
|
||||
if (pct >= 90) bar.classList.add('warn');
|
||||
if (pct >= 100) bar.classList.add('over');
|
||||
}
|
||||
})();
|
||||
</script>
|
||||
</body>
|
||||
</html>
|
||||
{{end}}
|
||||
@@ -3,86 +3,70 @@
|
||||
<html lang="zh-CN">
|
||||
<head>
|
||||
<meta charset="UTF-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0, viewport-fit=cover">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||||
<title>查看邮件 - MailGo</title>
|
||||
{{template "styles" .}}
|
||||
<style>
|
||||
.mail-body-iframe {
|
||||
width: 100%;
|
||||
min-height: 300px;
|
||||
border: 1px solid #e0e0e0;
|
||||
border-radius: 4px;
|
||||
background: #fff;
|
||||
}
|
||||
</style>
|
||||
</head>
|
||||
<body class="page-view">
|
||||
<body>
|
||||
{{template "navbar" .}}
|
||||
<div class="app-body">
|
||||
{{template "sidebar" .}}
|
||||
<main class="mail-main">
|
||||
<div class="view-toolbar">
|
||||
<a href="javascript:history.back()" class="tb-btn">
|
||||
<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><line x1="19" y1="12" x2="5" y2="12"/><polyline points="12 19 5 12 12 5"/></svg>
|
||||
返回
|
||||
</a>
|
||||
<a href="/compose?to={{mailEmail .message.FromAddr}}&subject={{if .message.Subject}}Re: {{.message.Subject}}{{end}}" class="tb-btn">
|
||||
<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><polyline points="9 17 4 12 9 7"/><path d="M20 18v-2a4 4 0 0 0-4-4H4"/></svg>
|
||||
回复
|
||||
</a>
|
||||
<form method="POST" action="/mail/delete/{{.message.ID}}" style="display:inline;"
|
||||
onsubmit="return confirm('确定要删除这封邮件吗?');">
|
||||
<button type="submit" class="tb-btn danger">
|
||||
<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><polyline points="3 6 5 6 21 6"/><path d="M19 6v14a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2V6m3 0V4a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v2"/></svg>
|
||||
删除
|
||||
</button>
|
||||
</form>
|
||||
<div class="container">
|
||||
<div class="clearfix">
|
||||
<div class="sidebar">
|
||||
<a href="/inbox" class="{{if eq .activeFolder `inbox`}}active{{end}}">收件箱</a>
|
||||
<a href="/drafts" class="{{if eq .activeFolder `drafts`}}active{{end}}">草稿箱</a>
|
||||
<a href="/sent" class="{{if eq .activeFolder `sent`}}active{{end}}">发件箱</a>
|
||||
<a href="/compose" class="{{if eq .activeFolder `compose`}}active{{end}}">撰写邮件</a>
|
||||
<a href="/settings" class="{{if eq .activeFolder `settings`}}active{{end}}">设置</a>
|
||||
</div>
|
||||
|
||||
<div class="mail-head">
|
||||
<h1 class="mail-title">{{if .message.Subject}}{{.message.Subject}}{{else}}(无主题){{end}}</h1>
|
||||
<div class="mail-from-row">
|
||||
<span class="avatar" style="{{avatarStyle .message.FromAddr}}">{{initial (mailName (decodeHeader .message.FromAddr))}}</span>
|
||||
<div>
|
||||
<div class="mail-from-name">{{mailName (decodeHeader .message.FromAddr)}}</div>
|
||||
<div class="mail-from-addr" title="{{decodeHeader .message.FromAddr}}">{{mailEmail .message.FromAddr}}</div>
|
||||
<div class="content">
|
||||
<div class="card">
|
||||
<div style="margin-bottom:16px;">
|
||||
<a href="javascript:history.back()" class="btn" style="background:#bdc3c7;color:#fff;">返回</a>
|
||||
</div>
|
||||
<h2>{{if .message.Subject}}{{.message.Subject}}{{else}}(无主题){{end}}</h2>
|
||||
<div class="mail-meta" style="margin-top:12px;">
|
||||
<p><strong>发件人:</strong> {{decodeHeader .message.FromAddr}}</p>
|
||||
<p><strong>收件人:</strong> {{.message.ToAddr}}</p>
|
||||
{{if .message.CcAddr}}<p><strong>抄送:</strong> {{.message.CcAddr}}</p>{{end}}
|
||||
<p><strong>时间:</strong> {{.message.Date.Format "2006-01-02 15:04:05"}}</p>
|
||||
</div>
|
||||
<div class="mail-body">
|
||||
{{if .message.HtmlBody}}
|
||||
<iframe class="mail-body-iframe" srcdoc="{{.message.HtmlBody | safeJS}}" sandbox="allow-same-origin" onload="this.style.height=this.contentDocument.body.scrollHeight+20+'px'"></iframe>
|
||||
{{else}}
|
||||
<pre style="white-space:pre-wrap;font-family:inherit;">{{.message.TextBody}}</pre>
|
||||
{{end}}
|
||||
</div>
|
||||
{{if .attachments}}
|
||||
<div class="attachment-list">
|
||||
<h4 style="margin-bottom:8px;">附件</h4>
|
||||
{{range .attachments}}
|
||||
<div class="attachment-item">
|
||||
📎 <a href="/attachment/{{.ID}}">{{.FileName}}</a>
|
||||
<span style="color:#7f8c8d;font-size:12px;">({{formatBytes .FileSize}})</span>
|
||||
</div>
|
||||
{{end}}
|
||||
</div>
|
||||
<span class="mail-date">{{.message.Date.Format "2006-01-02 15:04:05"}}</span>
|
||||
</div>
|
||||
{{if .message.CcAddr}}
|
||||
<div class="mail-from-addr" style="margin:-8px 0 16px 48px;">
|
||||
抄送:{{.message.CcAddr}}
|
||||
</div>
|
||||
{{end}}
|
||||
</div>
|
||||
|
||||
<div class="mail-body-wrap">
|
||||
<div class="mail-body">
|
||||
{{if .message.HtmlBody}}
|
||||
<iframe class="mail-body-iframe" srcdoc="{{.message.HtmlBody | safeJS}}" sandbox="allow-same-origin" onload="this.style.height=this.contentDocument.body.scrollHeight+20+'px'"></iframe>
|
||||
{{else}}
|
||||
<pre>{{.message.TextBody}}</pre>
|
||||
{{end}}
|
||||
<div style="margin-top:20px;padding-top:16px;border-top:1px solid #eee;">
|
||||
<form method="POST" action="/mail/delete/{{.message.ID}}" style="display:inline;"
|
||||
onsubmit="return confirm('确定要删除这封邮件吗?');">
|
||||
<button type="submit" class="btn btn-danger">删除邮件</button>
|
||||
</form>
|
||||
<a href="/compose?to={{decodeHeader .message.FromAddr}}&subject={{if .message.Subject}}Re: {{.message.Subject}}{{end}}" class="btn btn-primary" style="margin-left:8px;">回复</a>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{{if .attachments}}
|
||||
<div class="attachment-list">
|
||||
{{range .attachments}}
|
||||
<span class="attachment-item">
|
||||
<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M21.44 11.05l-9.19 9.19a6 6 0 0 1-8.49-8.49l9.19-9.19a4 4 0 0 1 5.66 5.66l-9.2 9.19a2 2 0 0 1-2.83-2.83l8.49-8.48"/></svg>
|
||||
<a href="/attachment/{{.ID}}">{{.FileName}}</a>
|
||||
<span style="color:var(--text-3);font-size:12px;">({{formatBytes .FileSize}})</span>
|
||||
</span>
|
||||
{{end}}
|
||||
</div>
|
||||
{{end}}
|
||||
</div>
|
||||
|
||||
<div class="view-actions">
|
||||
<a href="/compose?to={{mailEmail .message.FromAddr}}&subject={{if .message.Subject}}Re: {{.message.Subject}}{{end}}" class="btn btn-primary">
|
||||
<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" style="vertical-align:-2px;margin-right:4px;"><polyline points="9 17 4 12 9 7"/><path d="M20 18v-2a4 4 0 0 0-4-4H4"/></svg>
|
||||
回复
|
||||
</a>
|
||||
<form method="POST" action="/mail/delete/{{.message.ID}}" style="display:inline;"
|
||||
onsubmit="return confirm('确定要删除这封邮件吗?');">
|
||||
<button type="submit" class="btn btn-danger">
|
||||
<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" style="vertical-align:-2px;margin-right:4px;"><polyline points="3 6 5 6 21 6"/><path d="M19 6v14a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2V6m3 0V4a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v2"/></svg>
|
||||
删除邮件
|
||||
</button>
|
||||
</form>
|
||||
</div>
|
||||
</main>
|
||||
</div>
|
||||
</div>
|
||||
</body>
|
||||
</html>
|
||||
|
||||
@@ -12,7 +12,6 @@ import (
|
||||
"net"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"mail_go/config"
|
||||
@@ -23,7 +22,6 @@ import (
|
||||
"mail_go/internal/smtp_server"
|
||||
"mail_go/internal/storage"
|
||||
"mail_go/internal/store"
|
||||
"mail_go/internal/tlsutil"
|
||||
"mail_go/internal/web"
|
||||
|
||||
"golang.org/x/crypto/bcrypt"
|
||||
@@ -37,7 +35,7 @@ func applyDomainTLSConfig(stores *store.Stores, cfg *config.Config) {
|
||||
|
||||
applied := applyTLSCertPaths(cfg, domain.TlsCertPath, domain.TlsKeyPath)
|
||||
if applied {
|
||||
log.Printf("使用域名 %s 的 TLS 证书;证书更新后自动热加载,无需重启服务", domain.Name)
|
||||
log.Printf("使用域名 %s 的 TLS 证书;更新证书后需重启服务生效", domain.Name)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -61,49 +59,6 @@ func applyTLSCertPaths(cfg *config.Config, certPath, keyPath string) bool {
|
||||
return applied
|
||||
}
|
||||
|
||||
// tlsSource 返回证书路径来源:协议在 toml 中显式配置的证书优先;
|
||||
// 否则取第一个启用 TLS 且有证书的域名(管理后台一键导入证书后自动
|
||||
// 切换,无需重启)。结果缓存 10 秒,避免每次握手都查询数据库。
|
||||
func tlsSource(explicitCert, explicitKey string, stores *store.Stores) tlsutil.Source {
|
||||
var (
|
||||
mu sync.Mutex
|
||||
lastCheck time.Time
|
||||
cachedCert string
|
||||
cachedKey string
|
||||
)
|
||||
return func() (string, string) {
|
||||
mu.Lock()
|
||||
defer mu.Unlock()
|
||||
if time.Since(lastCheck) < 10*time.Second {
|
||||
return cachedCert, cachedKey
|
||||
}
|
||||
lastCheck = time.Now()
|
||||
if explicitCert != "" && explicitKey != "" {
|
||||
cachedCert, cachedKey = explicitCert, explicitKey
|
||||
} else if d, err := stores.Domains.GetFirstTLSEnabledWithCert(); err == nil {
|
||||
cachedCert, cachedKey = d.TlsCertPath, d.TlsKeyPath
|
||||
} else {
|
||||
cachedCert, cachedKey = "", ""
|
||||
}
|
||||
return cachedCert, cachedKey
|
||||
}
|
||||
}
|
||||
|
||||
// newTLSCertLoader 创建带热加载的 TLS 证书加载器(每次握手自动重载)。
|
||||
// 初始路径取显式配置或启动时填充的路径;source 允许后续动态切换
|
||||
// 证书来源。加载失败返回 nil,对应协议将不启用 TLS。
|
||||
func newTLSCertLoader(explicitCert, explicitKey, initCert, initKey string, stores *store.Stores, proto string) *tlsutil.Loader {
|
||||
if initCert == "" || initKey == "" {
|
||||
initCert, initKey = explicitCert, explicitKey
|
||||
}
|
||||
loader, err := tlsutil.NewLoader(initCert, initKey, tlsSource(explicitCert, explicitKey, stores), log.Printf)
|
||||
if err != nil {
|
||||
log.Printf("%s TLS 证书初始化失败: %v(该协议将不启用 TLS)", proto, err)
|
||||
return nil
|
||||
}
|
||||
return loader
|
||||
}
|
||||
|
||||
func ensureSelfSignedTLSConfig(cfg *config.Config) {
|
||||
if cfg.SMTP.TLSCert != "" && cfg.SMTP.TLSKey != "" && cfg.IMAP.TLSCert != "" && cfg.IMAP.TLSKey != "" && cfg.POP3.TLSCert != "" && cfg.POP3.TLSKey != "" {
|
||||
return
|
||||
@@ -213,21 +168,9 @@ func main() {
|
||||
|
||||
// 5. Initialize attachment storage
|
||||
attStorage := storage.NewAttachmentStorage(cfg.Storage.AttachDir)
|
||||
|
||||
// 记录 toml 中显式配置的证书路径;此后 applyDomainTLSConfig 会用
|
||||
// 域名证书填充空值,需要原始值来判断“显式配置优先”。
|
||||
explicitSMTPCert, explicitSMTPKey := cfg.SMTP.TLSCert, cfg.SMTP.TLSKey
|
||||
explicitIMAPCert, explicitIMAPKey := cfg.IMAP.TLSCert, cfg.IMAP.TLSKey
|
||||
explicitPOP3Cert, explicitPOP3Key := cfg.POP3.TLSCert, cfg.POP3.TLSKey
|
||||
|
||||
applyDomainTLSConfig(stores, cfg)
|
||||
ensureSelfSignedTLSConfig(cfg)
|
||||
|
||||
// 证书热加载器:每次 TLS 握手自动重载证书文件,证书更新后无需重启
|
||||
smtpTLS := newTLSCertLoader(explicitSMTPCert, explicitSMTPKey, cfg.SMTP.TLSCert, cfg.SMTP.TLSKey, stores, "SMTP")
|
||||
imapTLS := newTLSCertLoader(explicitIMAPCert, explicitIMAPKey, cfg.IMAP.TLSCert, cfg.IMAP.TLSKey, stores, "IMAP")
|
||||
pop3TLS := newTLSCertLoader(explicitPOP3Cert, explicitPOP3Key, cfg.POP3.TLSCert, cfg.POP3.TLSKey, stores, "POP3")
|
||||
|
||||
// 6. Outbound delivery manager (external mail queue + worker)
|
||||
outboundMgr := outbound.NewManager(cfg.Outbound, cfg.SMTP.Domain, stores)
|
||||
if outboundMgr.Enabled() {
|
||||
@@ -238,7 +181,7 @@ func main() {
|
||||
}
|
||||
|
||||
// 7. Start SMTP server
|
||||
smtpSrv := smtp_server.NewSMTPServer(cfg.SMTP, stores, attStorage, outboundMgr, smtpTLS)
|
||||
smtpSrv := smtp_server.NewSMTPServer(cfg.SMTP, stores, attStorage, outboundMgr)
|
||||
go func() {
|
||||
if err := smtpSrv.Start(); err != nil {
|
||||
log.Printf("SMTP 服务启动失败: %v", err)
|
||||
@@ -259,7 +202,7 @@ func main() {
|
||||
}
|
||||
|
||||
// 7. Start IMAP server
|
||||
imapSrv := imap_server.NewIMAPServer(cfg.IMAP, stores, imapTLS)
|
||||
imapSrv := imap_server.NewIMAPServer(cfg.IMAP, stores)
|
||||
go func() {
|
||||
if err := imapSrv.Start(); err != nil {
|
||||
log.Printf("IMAP 服务启动失败: %v", err)
|
||||
@@ -275,7 +218,7 @@ func main() {
|
||||
}
|
||||
|
||||
// 8. Start POP3 server
|
||||
pop3Srv := pop3_server.NewPOP3Server(cfg.POP3, stores, pop3TLS)
|
||||
pop3Srv := pop3_server.NewPOP3Server(cfg.POP3, stores)
|
||||
go func() {
|
||||
if err := pop3Srv.Start(); err != nil {
|
||||
log.Printf("POP3 服务启动失败: %v", err)
|
||||
@@ -291,7 +234,7 @@ func main() {
|
||||
}
|
||||
|
||||
// 10. Start Web server
|
||||
webServer := web.NewWebServer(cfg.Web, stores, attStorage, cfg.Storage, cfg.Auth, cfg.Ban, cfg.Caddy, outboundMgr)
|
||||
webServer := web.NewWebServer(cfg.Web, stores, attStorage, cfg.Storage, cfg.Auth, cfg.Ban, outboundMgr)
|
||||
fmt.Printf("Web 服务启动在 %s\n", cfg.Web.Addr)
|
||||
go func() {
|
||||
if err := webServer.Start(); err != nil {
|
||||
|
||||
Reference in New Issue
Block a user