- 新增 internal/outbound 模块:MX 查询、SMTP 出站客户端(EHLO/STARTTLS/ MAIL/RCPT/DATA/QUIT)、4xx 临时失败与 5xx 永久失败分类、8BITMIME 支持 - 新增 outbound_messages 队列表与 OutboundStore,后台 worker 指数退避重试 - 永久失败/超限退信到发件人收件箱,包含原因与目标收件人 - 外发邮件使用域名 DKIM 私钥签名(go-msgauth) - SMTP 提交集成:认证用户可发外部收件人,MAIL FROM 必须等于登录用户邮箱, 未认证外部投递明确拒绝(防开放中继) - Web 发信集成:外部收件人自动入队,附件以 multipart/mixed + base64 编码 加入邮件正文 - 每用户每分钟/每日发送限速(max_per_day=0 可禁用外部投递) - 管理后台新增外发队列页面:状态统计、失败原因、手动重试/取消 - 新增 [outbound] 配置段并更新 README / todo.md
55 lines
1.5 KiB
Go
55 lines
1.5 KiB
Go
package db
|
|
|
|
import (
|
|
"fmt"
|
|
"os"
|
|
"path/filepath"
|
|
|
|
"mail_go/config"
|
|
|
|
"gorm.io/driver/mysql"
|
|
"gorm.io/driver/sqlite"
|
|
"gorm.io/gorm"
|
|
"gorm.io/gorm/logger"
|
|
)
|
|
|
|
// InitDB initializes the database connection and performs auto-migration.
|
|
// It selects the appropriate driver based on cfg.Driver and resolves
|
|
// the DSN path for SQLite relative to the storage base directory.
|
|
func InitDB(cfg config.DatabaseConfig, storageCfg config.StorageConfig) (*gorm.DB, error) {
|
|
var dialector gorm.Dialector
|
|
|
|
switch cfg.Driver {
|
|
case "sqlite":
|
|
dsn := cfg.DSN
|
|
// If the DSN is the default relative path, prepend the storage base directory
|
|
if dsn == config.DefaultDSNWin || dsn == config.DefaultDSNLinux {
|
|
dsn = filepath.Join(storageCfg.BaseDir, "mail.db")
|
|
}
|
|
// Ensure the parent directory exists for SQLite
|
|
dir := filepath.Dir(dsn)
|
|
if err := os.MkdirAll(dir, 0755); err != nil {
|
|
return nil, fmt.Errorf("创建数据库目录失败 %s: %w", dir, err)
|
|
}
|
|
dialector = sqlite.Open(dsn)
|
|
case "mysql":
|
|
dialector = mysql.Open(cfg.DSN)
|
|
default:
|
|
return nil, fmt.Errorf("不支持的数据库驱动: %s", cfg.Driver)
|
|
}
|
|
|
|
db, err := gorm.Open(dialector, &gorm.Config{
|
|
Logger: logger.Default.LogMode(logger.Warn),
|
|
})
|
|
if err != nil {
|
|
return nil, fmt.Errorf("连接数据库失败: %w", err)
|
|
}
|
|
|
|
// Auto-migrate all models
|
|
if err := db.AutoMigrate(&User{}, &Domain{}, &Message{}, &Attachment{}, &BanEntry{}, &OutboundMessage{}); err != nil {
|
|
return nil, fmt.Errorf("数据库迁移失败: %w", err)
|
|
}
|
|
|
|
return db, nil
|
|
}
|