Skip to content

BillionMail gives you open-source MailServer, NewsLetter, Email Marketing — fully self-hosted, dev-friendly, and free from monthly fees. Join the discord: https://discord.gg/asfXzBUhZr

取消忽略文件夹

lotk4f12087ee68f
diff --git a/core/api/subscribe_list/subscribe_list.go b/core/api/subscribe_list/subscribe_list.go
new file mode 100644
index 00000000..19ea9b1b
--- /dev/null
+++ b/core/api/subscribe_list/subscribe_list.go
@@ -0,0 +1,16 @@
+// =================================================================================
+// Code generated and maintained by GoFrame CLI tool. DO NOT EDIT.
+// =================================================================================
+
+package subscribe_list
+
+import (
+ "context"
+
+ "billionmail-core/api/subscribe_list/v1"
+)
+
+type ISubscribeListV1 interface {
+ SubscribeSubmit(ctx context.Context, req *v1.SubscribeSubmitReq) (res *v1.SubscribeSubmitRes, err error)
+ SubscribeConfirm(ctx context.Context, req *v1.SubscribeConfirmReq) (res *v1.SubscribeConfirmRes, err error)
+}
diff --git a/core/api/subscribe_list/v1/subscribe_list.go b/core/api/subscribe_list/v1/subscribe_list.go
new file mode 100644
index 00000000..19cca66f
--- /dev/null
+++ b/core/api/subscribe_list/v1/subscribe_list.go
@@ -0,0 +1,63 @@
+package v1
+
+import (
+ "billionmail-core/utility/types/api_v1"
+ "github.com/gogf/gf/v2/frame/g"
+)
+
+type ContactGroup struct {
+ Id int `json:"id" dc:"Group ID"`
+ Name string `json:"name" dc:"Group Name"`
+ Description string `json:"description" dc:"Description"`
+ CreateTime int `json:"create_time" dc:"Create Time"`
+ UpdateTime int `json:"update_time" dc:"Update Time"`
+ Token string `json:"token" dc:"Subscription Token"`
+ DoubleOptin int `json:"double_optin" dc:"Double Opt-in Status(0: Single Opt-in 1: Double Opt-in)"`
+
+ WelcomeHtml string `json:"welcome_mail_html" dc:"Welcome Email Html"`
+ WelcomeDrag string `json:"welcome_mail_drag" dc:"Welcome Email Drag"`
+
+ WelcomeSubject string `json:"welcome_subject" dc:"Welcome Email Subject"`
+ SendWelcomeEmail int `json:"send_welcome_email" dc:"Whether to send a welcome email"`
+ ConfirmSubject string `json:"confirm_subject" dc:"Confirmation Email Subject"`
+
+ ConfirmHtml string `json:"confirm_mail_html" dc:"Confirmation Email Html"`
+ ConfirmDrag string `json:"confirm_mail_drag" dc:"Confirmation Email Drag"`
+ SuccessUrl string `json:"success_url" dc:"Success URL"`
+ ConfirmUrl string `json:"confirm_url" dc:"Confirmation URL"`
+ AlreadyUrl string `json:"already_url" dc:"Already Subscribed URL"`
+ SubscribeForm string `json:"subscribe_form" dc:"Subscription Form HTML"`
+}
+type Contact struct {
+ Id int `json:"id" dc:"Contact ID"`
+ Email string `json:"email" dc:"Email Address"`
+ GroupId int `json:"group_id" dc:"Group ID"`
+ Active int `json:"active" dc:"Status(1:Subscribed 0:Unsubscribed)"`
+ TaskId int `json:"task_id" dc:"Bulk Mail Task ID"`
+ CreateTime int `json:"create_time" dc:"Create Time"`
+ Status int `json:"status" dc:"Status( 1:Confirmed 0:Unconfirmed)"`
+ Attribs map[string]string `json:"attribs"`
+}
+
+// 订阅表单提交
+type SubscribeSubmitReq struct {
+ g.Meta `path:"/subscribe/submit" tags:"Subscribe" method:"post" summary:"Subscribe to the service"`
+ Email string `json:"email" dc:"Email address for subscription"`
+ Token string `json:"token" dc:"Subscription token"`
+ Attribs map[string]string `json:"attribs" dc:"Additional attributes for subscription, e.g., {'name': 'John Doe', 'phone': '1234567890'}"`
+}
+
+type SubscribeSubmitRes struct {
+ api_v1.StandardRes
+}
+
+// 确认链接 /subscribe/confirm
+type SubscribeConfirmReq struct {
+ g.Meta `path:"/subscribe/confirm" tags:"Subscribe" method:"get" summary:"Confirm subscription"`
+ Token string `json:"token" dc:"Subscription token"`
+ Email string `json:"email" dc:"Email address for subscription"`
+}
+
+type SubscribeConfirmRes struct {
+ api_v1.StandardRes
+}
diff --git a/core/internal/controller/batch_mail/batch_mail_v1_api_mail_batch_send.go b/core/internal/controller/batch_mail/batch_mail_v1_api_mail_batch_send.go
new file mode 100644
index 00000000..77d9f31e
--- /dev/null
+++ b/core/internal/controller/batch_mail/batch_mail_v1_api_mail_batch_send.go
@@ -0,0 +1,122 @@
+package batch_mail
+
+import (
+ "billionmail-core/internal/service/mail_service"
+ "billionmail-core/internal/service/public"
+ "context"
+ "github.com/gogf/gf/v2/errors/gerror"
+ "github.com/gogf/gf/v2/frame/g"
+ "strings"
+ "time"
+
+ "billionmail-core/api/batch_mail/v1"
+)
+
+func (c *ControllerV1) ApiMailBatchSend(ctx context.Context, req *v1.ApiMailBatchSendReq) (res *v1.ApiMailBatchSendRes, err error) {
+ res = &v1.ApiMailBatchSendRes{}
+ clientIP := g.RequestFromCtx(ctx).GetClientIp()
+
+ // 1. 校验API Key
+ apiTemplate, err := getApiTemplateByKey(ctx, req.ApiKey, clientIP)
+ if err != nil {
+ res.Code = 1001
+ res.SetError(gerror.New(public.LangCtx(ctx, err.Error())))
+ return res, nil
+ }
+
+ // 2. 校验IP
+ err = CheckClientIP(ctx, apiTemplate.Id, clientIP)
+ if err != nil {
+ res.Code = 1002
+ res.SetError(gerror.New(public.LangCtx(ctx, err.Error())))
+ return res, nil
+ }
+
+ // 3. 校验邮件模板
+ _, err = getEmailTemplateById(ctx, apiTemplate.TemplateId)
+ if err != nil {
+ res.Code = 1004
+ res.SetError(gerror.New(public.LangCtx(ctx, "Email template does not exist")))
+ return res, nil
+ }
+
+ // 4. 校验收件人
+ if len(req.Recipients) == 0 {
+ res.Code = 1003
+ res.SetError(gerror.New(public.LangCtx(ctx, "Recipients cannot be empty")))
+ return res, nil
+ }
+
+ validRecipients := make([]string, 0, len(req.Recipients))
+ for _, recipient := range req.Recipients {
+ if recipient != "" && strings.Contains(recipient, "@") {
+ validRecipients = append(validRecipients, recipient)
+ }
+ }
+ if len(validRecipients) == 0 {
+ res.Code = 1003
+ res.SetError(gerror.New(public.LangCtx(ctx, "No valid recipients")))
+ return res, nil
+ }
+
+ // 5. 处理发件人
+ addresser := req.Addresser
+ if addresser == "" {
+ addresser = apiTemplate.Addresser
+ }
+
+ // 6. 批量处理联系人和日志数据
+ batchData := make([]g.Map, 0, len(validRecipients))
+ now := int(time.Now().Unix())
+ for _, recipient := range validRecipients {
+ // 处理联系人和分组
+ _, err = ensureContactAndGroup(ctx, recipient, apiTemplate.Id)
+ if err != nil {
+ // 某个收件人失败,跳过
+ continue
+ }
+ // 生成messageId
+ sender, err := mail_service.NewEmailSenderWithLocal(addresser)
+ if err != nil {
+ continue
+ }
+ messageId := sender.GenerateMessageID()
+ sender.Close()
+ messageId = strings.Trim(messageId, "<>")
+ batchData = append(batchData, g.Map{
+ "api_id": apiTemplate.Id,
+ "recipient": recipient,
+ "message_id": messageId,
+ "addresser": addresser,
+ "status": 0, // 待发送
+ "error_message": "",
+ "send_time": 0,
+ "create_time": now,
+ "attribs": req.Attribs,
+ })
+ }
+
+ if len(batchData) == 0 {
+ res.Code = 1003
+ res.SetError(gerror.New(public.LangCtx(ctx, "No valid recipients to insert")))
+ return res, nil
+ }
+
+ // 7. 批量插入日志表,分批处理
+ batchSize := 1000
+ for i := 0; i < len(batchData); i += batchSize {
+ end := i + batchSize
+ if end > len(batchData) {
+ end = len(batchData)
+ }
+ _, err = g.DB().Model("api_mail_logs").Batch(batchSize).Insert(batchData[i:end])
+ if err != nil {
+ res.Code = 1005
+ res.SetError(gerror.New(public.LangCtx(ctx, "Failed to record email log: {}", err.Error())))
+ return res, nil
+ }
+ }
+
+ res.SetSuccess(public.LangCtx(ctx, "Batch email send request accepted, {} emails queued", len(batchData)))
+ return res, nil
+}
diff --git a/core/internal/controller/contact/contact_v1_get_group_info.go b/core/internal/controller/contact/contact_v1_get_group_info.go
new file mode 100644
index 00000000..b0e48ba7
--- /dev/null
+++ b/core/internal/controller/contact/contact_v1_get_group_info.go
@@ -0,0 +1,96 @@
+package contact
+
+import (
+ "context"
+
+ "github.com/gogf/gf/v2/errors/gerror"
+
+ "billionmail-core/api/contact/v1"
+ "billionmail-core/internal/controller/subscribe_list"
+ "billionmail-core/internal/service/contact"
+ "billionmail-core/internal/service/public"
+ "github.com/gogf/gf/v2/frame/g"
+)
+
+func (c *ControllerV1) GetGroupInfo(ctx context.Context, req *v1.GetGroupInfoReq) (res *v1.GetGroupInfoRes, err error) {
+ res = &v1.GetGroupInfoRes{}
+
+ group, err := contact.GetGroup(ctx, req.GroupId)
+ if err != nil || group == nil {
+ res.Code = 404
+ res.SetError(gerror.New(public.LangCtx(ctx, "Group not found")))
+ return res, nil
+ }
+
+ hostUrl := public.GethostUrl()
+
+ if group.Token == "" {
+ token := GfMd5Short()
+ group.Token = token
+ _, err := g.DB().Model("bm_contact_groups").
+ Data(g.Map{"token": token}).
+ Where("id", group.Id).
+ Update()
+ if err != nil {
+ g.Log().Error(ctx, "Failed to update the group token: %v", err)
+ }
+ }
+ if group.WelcomeHtml == "" {
+ html, drag := subscribe_list.GetDefaultTemplate(1)
+ group.WelcomeHtml = html
+ group.WelcomeDrag = drag
+ }
+ if group.ConfirmHtml == "" {
+ html, drag := subscribe_list.GetDefaultTemplate(2)
+ group.ConfirmHtml = html
+ group.ConfirmDrag = drag
+ }
+ if group.SuccessUrl == "" {
+ group.SuccessUrl = hostUrl + "/subscribe_success.html"
+ }
+ if group.ConfirmUrl == "" {
+ group.ConfirmUrl = hostUrl + "/subscribe_confirm.html"
+ }
+ if group.AlreadyUrl == "" {
+ group.AlreadyUrl = hostUrl + "/already_subscribed.html"
+ }
+ if group.SubscribeForm == "" {
+ group.SubscribeForm = subscribe_list.GetSubscribeFormCode(group.Token)
+ }
+ if group.WelcomeSubject == "" {
+ group.WelcomeSubject = "默认主题"
+ }
+ if group.ConfirmSubject == "" {
+ group.ConfirmSubject = "默认主题"
+ }
+
+ contactGroup := v1.ContactGroup{
+ Id: group.Id,
+ Name: group.Name,
+ Description: group.Description,
+ CreateTime: group.CreateTime,
+ UpdateTime: group.UpdateTime,
+ Token: group.Token,
+ DoubleOptin: group.DoubleOptin,
+ WelcomeHtml: group.WelcomeHtml,
+ WelcomeDrag: group.WelcomeDrag,
+ ConfirmHtml: group.ConfirmHtml,
+ ConfirmDrag: group.ConfirmDrag,
+ SuccessUrl: group.SuccessUrl,
+ ConfirmUrl: group.ConfirmUrl,
+ AlreadyUrl: group.AlreadyUrl,
+ SubscribeForm: group.SubscribeForm,
+ ConfirmSubject: group.ConfirmSubject,
+ WelcomeSubject: group.WelcomeSubject,
+ SendWelcomeEmail: group.SendWelcomeEmail,
+ }
+
+ groupInfo := &v1.ContactGroupInfo{
+ ContactGroup: contactGroup,
+ SubscribeLink: hostUrl + "/subscribe_form.html?token=" + group.Token,
+ }
+
+ res.Data = groupInfo
+ res.SetSuccess(public.LangCtx(ctx, "Group info retrieved successfully"))
+ return res, nil
+}
diff --git a/core/internal/controller/subscribe_list/subscribe_list.go b/core/internal/controller/subscribe_list/subscribe_list.go
new file mode 100644
index 00000000..b2cc23ed
--- /dev/null
+++ b/core/internal/controller/subscribe_list/subscribe_list.go
@@ -0,0 +1,396 @@
+// =================================================================================
+// This is auto-generated by GoFrame CLI tool only once. Fill this file as you wish.
+// =================================================================================
+
+package subscribe_list
+
+import (
+ mail_v1 "billionmail-core/api/mail_boxes/v1"
+ "billionmail-core/internal/model/entity"
+ "billionmail-core/internal/service/batch_mail"
+ "billionmail-core/internal/service/domains"
+ "billionmail-core/internal/service/mail_boxes"
+ "billionmail-core/internal/service/mail_service"
+ "billionmail-core/internal/service/maillog_stat"
+ "billionmail-core/internal/service/public"
+ "context"
+ "database/sql"
+ "fmt"
+ "github.com/gogf/gf/util/grand"
+ "github.com/gogf/gf/v2/errors/gerror"
+ "github.com/gogf/gf/v2/frame/g"
+ "github.com/gogf/gf/v2/os/gfile"
+ "os"
+ "path/filepath"
+ "strings"
+)
+
+//// 联系人结构体
+//type Contact struct {
+// Id int
+// Email string
+// Status int
+// // ...其他字段
+//}
+
+// 订阅组结构体
+type Group struct {
+ Id int
+ Name string
+ Token string
+ DoubleOptin int
+ WelcomeMailId int
+ ConfirmMailId int
+ SuccessUrl string
+ ConfirmUrl string
+ AlreadyUrl string
+ // ...其他字段
+}
+
+// 查找组
+func getGroupByToken(token string) (*entity.ContactGroup, error) {
+ var group entity.ContactGroup
+ err := g.DB().Model("bm_contact_groups").Where("token", token).Scan(&group)
+ if err != nil && err == sql.ErrNoRows {
+ err = nil
+ }
+ return &group, err
+}
+
+// 查找联系人
+func getContactByEmailAndGroup(email string, groupId int) (*entity.Contact, error) {
+ // 查询数据库 bm_contacts where email=? and group_id=?
+ var contact entity.Contact
+ err := g.DB().Model("bm_contacts").
+ Where("group_id", groupId).
+ Where("email", email).
+ Scan(&contact)
+ if err != nil && err == sql.ErrNoRows {
+ err = nil
+ }
+
+ return &contact, err
+}
+
+// 添加/更新联系人
+func addOrUpdateContact(email string, groupId int, attribs map[string]string, status int) error {
+
+ // 处理旧数据 已经在联系人表 但不在当前组的 也不用确认
+ count, err := g.DB().Model("bm_contacts").
+ Where("email", email).
+ Count()
+ if err == nil && count > 0 {
+ status = 1 // 已经存在联系人,直接设置为已确认状态
+ }
+
+ // 如果已存在则更新,否则插入
+ var contact entity.Contact
+ err = g.DB().Model("bm_contacts").
+ Where("email", email).
+ Where("group_id", groupId).
+ Scan(&contact)
+
+ if err != nil && err == sql.ErrNoRows {
+ err = nil
+ }
+
+ if err != nil {
+ return err
+ }
+
+ if g.IsEmpty(contact) {
+ // 插入新联系人
+ contact = entity.Contact{
+ Email: email,
+ GroupId: groupId,
+ Status: status,
+ Attribs: attribs,
+ }
+ _, err = g.DB().Model("bm_contacts").Data(contact).OmitEmpty().Insert()
+ if err != nil {
+ return err
+ }
+ }
+
+ // 更新现有联系人
+ contact.Status = status
+ contact.Attribs = attribs
+ _, err = g.DB().Model("bm_contacts").Data(contact).Where("id", contact.Id).Update()
+ if err != nil {
+ return err
+ }
+
+ return nil
+}
+
+// 更新联系人状态 确认(0,1) 订阅1
+func updateContactStatus(email string, groupId int, status int) error {
+ // update bm_contacts set status=? where email=? and group_id=?
+
+ _, err := g.DB().Model("bm_contacts").
+ Data(g.Map{"status": status, "active": 1}).
+ Where("email", email).
+ Where("group_id", groupId).
+ Update()
+
+ return err
+}
+
+func readTemplateFiles(baseFilename string) (htmlContent string, txtContent string, err error) {
+ hostwork := public.HostWorkDir
+
+ // 构造两个文件路径(自动处理不同操作系统分隔符)
+ htmlPath := filepath.Join(hostwork, "core", "data", baseFilename+".html")
+ txtPath := filepath.Join(hostwork, "core", "data", baseFilename+".txt")
+
+ // 安全检查(防止目录遍历)
+ cleanDir := filepath.Clean(filepath.Join(hostwork, "core", "data"))
+ if !strings.HasPrefix(filepath.Clean(htmlPath), cleanDir) ||
+ !strings.HasPrefix(filepath.Clean(txtPath), cleanDir) {
+ return "", "", fmt.Errorf("非法路径访问: %s", baseFilename)
+ }
+
+ // 读取HTML文件
+ htmlBytes, err := os.ReadFile(htmlPath)
+ if err != nil {
+ return "", "", fmt.Errorf("读取HTML模板失败: %w", err)
+ }
+
+ // 读取TXT文件(允许不存在)
+ txtBytes, err := os.ReadFile(txtPath)
+ if err != nil {
+ if !os.IsNotExist(err) {
+ g.Log().Warningf(context.Background(),
+ "读取TXT模板失败: %v, 路径: %s", err, txtPath)
+ }
+ txtBytes = []byte("") // 不存在时返回空内容
+ }
+
+ return string(htmlBytes), string(txtBytes), nil
+}
+
+func GetDefaultTemplate(emailType int) (html string, txt string) {
+ var (
+ defaultHtml string
+ defaultTxt string
+ basePath string
+ )
+
+ switch emailType {
+ case 1: // 欢迎邮件
+ basePath = "default_welcome_email/welcome_email"
+ defaultHtml = "<p>Welcome to subscribe!</p>"
+ defaultTxt = ""
+ case 2: // 确认邮件
+ basePath = "default_confirm_email/confirm_email"
+ defaultHtml = "<p>Please confirm your subscription.</p>"
+ defaultTxt = ""
+ default:
+ return "<p>Welcome to subscribe!</p>", ""
+ }
+
+ htmlContent, txtContent, err := readTemplateFiles(basePath)
+ if err != nil {
+ g.Log().Errorf(context.Background(),
+ "获取模板失败,使用默认内容。错误: %v, 路径: %s",
+ err, basePath)
+ return defaultHtml, defaultTxt
+ }
+
+ return htmlContent, txtContent
+}
+
+// 发送邮件
+func sendMail(ctx context.Context, emailHtml, email, subject, confirmUrl string) error {
+ // 1. 获取模板
+ if emailHtml == "" {
+ return gerror.New(public.LangCtx(ctx, "邮件模板ID不能为空"))
+ }
+
+ // 如果存在{{ ConfirmURL . }}变量,则替换为确认链接
+ if strings.Contains(emailHtml, "{{ ConfirmURL . }}") {
+ if confirmUrl == "" {
+ return gerror.New(public.LangCtx(ctx, "确认邮件需要提供确认链接"))
+ }
+ emailHtml = strings.ReplaceAll(emailHtml, "{{ ConfirmURL . }}", confirmUrl)
+ }
+
+ // 2. 获取联系人(用于变量替换)
+ var contact entity.Contact
+ _ = g.DB().Model("bm_contacts").Where("email", email).Scan(&contact)
+
+ // 3. 退订链接处理
+ content := emailHtml
+ //if !strings.Contains(content, "{{ UnsubscribeURL . }}") {
+ // content = public.AddUnsubscribeButton(content)
+ //}
+
+ //// 4. 生成退订jwt和链接
+ //jwtToken, _ := batch_mail.GenerateUnsubscribeJWT(email, templateId, 0)
+ //domain := domains.GetBaseURL()
+ //unsubscribeURL := fmt.Sprintf("%s/api/unsubscribe", domain)
+ //groupURL := fmt.Sprintf("%s/api/unsubscribe/user_group", domain)
+ //unsubscribeJumpURL := fmt.Sprintf("%s/unsubscribe.html?jwt=%s&email=%s&url_type=%s&url_unsubscribe=%s",
+ // domain, jwtToken, email, groupURL, unsubscribeURL)
+
+ // 5. 渲染内容和主题
+ engine := batch_mail.GetTemplateEngine()
+
+ personalizedContent, err := engine.RenderEmailTemplate(ctx, content, &contact, nil, "")
+ if err != nil {
+ return gerror.New(public.LangCtx(ctx, "渲染邮件内容失败"))
+ }
+ g.Log().Errorf(context.Background(), "主题:22 %v", subject)
+ personalizedSubject, err := engine.RenderEmailTemplate(ctx, subject, &contact, nil, "")
+ if err != nil {
+ return gerror.New(public.LangCtx(ctx, "渲染邮件主题失败"))
+ }
+ g.Log().Errorf(context.Background(), "主题: 33%v", personalizedSubject)
+ //address := "[email protected]"
+ DefaultDomain, err := getDefaultDomain()
+ if err != nil {
+ return gerror.New(public.LangCtx(ctx, "获取默认发件域名失败: {}", err))
+ }
+ address, err := createNoreplyEmail(DefaultDomain)
+ if err != nil {
+ return gerror.New(public.LangCtx(ctx, "查找noreply邮箱失败: {}", err))
+ }
+
+ // 6. 创建发件人
+ sender, err := mail_service.NewEmailSenderWithLocal(address)
+ if err != nil {
+ return gerror.New(public.LangCtx(ctx, "创建发件人失败"))
+ }
+ defer sender.Close()
+ messageId := sender.GenerateMessageID()
+
+ //Tracking emails
+ baseURL := domains.GetBaseURLBySender(address)
+ mail_tracker := maillog_stat.NewMailTracker(personalizedContent, -1, messageId, email, baseURL)
+ mail_tracker.TrackLinks()
+ mail_tracker.AppendTrackingPixel()
+ renderedContent := mail_tracker.GetHTML()
+
+ // 7. 创建消息
+ message := mail_service.NewMessage(personalizedSubject, renderedContent)
+ message.SetMessageID(messageId)
+ message.SetRealName("noreply")
+
+ // 8. 发送邮件
+ err = sender.Send(message, []string{email})
+ if err != nil {
+ return gerror.New(public.LangCtx(ctx, "发送邮件失败: {}", err))
+ }
+
+ return nil
+}
+
+// 生成token
+func generateConfirmToken(email, groupToken string) string {
+ token, err := batch_mail.GenerateSubscribeConfirmJWT(email, groupToken)
+ if err != nil {
+ g.Log().Errorf(context.Background(), "生成订阅确认token失败: %v", err)
+ return ""
+ }
+ return token
+}
+
+// 取token中的email groupToken
+func getEmailFromToken(token string) (string, string, error) {
+ claims, err := batch_mail.ParseSubscribeConfirmJWT(token)
+ if err != nil {
+ return "", "", gerror.New("解析订阅确认token失败: " + err.Error())
+ }
+ return claims.Email, claims.GroupToken, nil
+}
+
+// 构建确认链接
+func buildConfirmUrl(token string) string {
+ hostUrl := public.GethostUrl()
+ return fmt.Sprintf("%s/api/subscribe/confirm?token=%s", hostUrl, token)
+}
+
+// 查询发件邮箱是否存 创建
+func createNoreplyEmail(domain string) (string, error) {
+ noreplyEmail := "noreply@" + domain
+ count, err := g.DB().Model("mailbox").Where("username", noreplyEmail).Count()
+ if err != nil {
+ return "", gerror.New("查询邮箱失败")
+ }
+ if count == 0 {
+ ctx := context.Background()
+ _ = mail_boxes.Add(ctx, &mail_v1.Mailbox{
+ Username: noreplyEmail,
+ Password: grand.S(16),
+ FullName: "noreply",
+ IsAdmin: 0,
+ Quota: 5242880,
+ LocalPart: "noreply",
+ Domain: domain,
+ Active: 1,
+ })
+ }
+ return noreplyEmail, nil
+}
+
+// 获取默认发件域名
+func getDefaultDomain() (string, error) {
+ ctx := context.Background()
+
+ configuredDomain, err := g.DB().Model("bm_options").
+ Where("name", "default_sender_domain").
+ Value("value")
+
+ if err == nil && configuredDomain != nil {
+ return configuredDomain.String(), nil
+ }
+
+ // 2. 获取最早创建的活跃域名
+
+ oldestDomain, err := g.DB().Model("domain").
+ Order("create_time", "asc").
+ Where("active", 1).
+ Limit(1).
+ Value("domain")
+ if err != nil || oldestDomain == nil {
+
+ return "", gerror.New("没有可用的活跃域名,请先添加域名")
+ }
+
+ // 3. 保存到配置表
+ _, err = g.DB().Model("bm_options").
+ Data(g.Map{
+ "name": "default_sender_domain",
+ "value": oldestDomain.String(),
+ }).
+ OnConflict("name").
+ Save()
+
+ if err != nil {
+ g.Log().Errorf(ctx, "保存默认域名失败: %v", err)
+ return "", gerror.Wrap(err, "保存默认发件域名配置失败")
+ }
+
+ return oldestDomain.String(), nil
+}
+
+// 获取订阅表单代码
+func GetSubscribeFormCode(groupToken string) string {
+ // D:\Billion-Mail\core\public\html
+ hostwork := public.HostWorkDir
+ filePath := filepath.Join(hostwork, "core", "public", "html", "subscribe_form_code.html")
+ content := gfile.GetContents(filePath)
+
+ if !strings.Contains(content, "{{ SubmitURL . }}") {
+ return ""
+ }
+ // 链接对应页面
+ var submitUrl string
+ hostUrl := public.GethostUrl()
+ submitUrl = hostUrl + "/api/subscribe/submit?token=" + groupToken
+
+ newContent := strings.ReplaceAll(content, "{{ SubmitURL . }}", submitUrl)
+
+ return newContent
+
+}
diff --git a/core/internal/controller/subscribe_list/subscribe_list_new.go b/core/internal/controller/subscribe_list/subscribe_list_new.go
new file mode 100644
index 00000000..f0dc7f43
--- /dev/null
+++ b/core/internal/controller/subscribe_list/subscribe_list_new.go
@@ -0,0 +1,15 @@
+// =================================================================================
+// This is auto-generated by GoFrame CLI tool only once. Fill this file as you wish.
+// =================================================================================
+
+package subscribe_list
+
+import (
+ "billionmail-core/api/subscribe_list"
+)
+
+type ControllerV1 struct{}
+
+func NewV1() subscribe_list.ISubscribeListV1 {
+ return &ControllerV1{}
+}
diff --git a/core/internal/controller/subscribe_list/subscribe_list_v1_subscribe_confirm.go b/core/internal/controller/subscribe_list/subscribe_list_v1_subscribe_confirm.go
new file mode 100644
index 00000000..2f2a6569
--- /dev/null
+++ b/core/internal/controller/subscribe_list/subscribe_list_v1_subscribe_confirm.go
@@ -0,0 +1,89 @@
+package subscribe_list
+
+import (
+ "billionmail-core/internal/service/public"
+ "context"
+ "fmt"
+ "github.com/gogf/gf/os/gtimer"
+ "github.com/gogf/gf/v2/errors/gerror"
+ "github.com/gogf/gf/v2/frame/g"
+ "time"
+
+ "billionmail-core/api/subscribe_list/v1"
+)
+
+func (c *ControllerV1) SubscribeConfirm(ctx context.Context, req *v1.SubscribeConfirmReq) (res *v1.SubscribeConfirmRes, err error) {
+ res = &v1.SubscribeConfirmRes{}
+
+ email, groupToken, err := getEmailFromToken(req.Token)
+ if err != nil {
+ res.SetError(gerror.New(public.LangCtx(ctx, "确认链接无效")))
+ return
+ }
+ if email == "" || groupToken == "" {
+ res.SetError(gerror.New(public.LangCtx(ctx, "确认链接无效")))
+ return
+ }
+
+ // 1. 查找订阅组
+ group, err := getGroupByToken(groupToken)
+ if err != nil {
+ res.SetError(gerror.New(public.LangCtx(ctx, "订阅组不存在")))
+ return
+ }
+
+ // 2. 查找联系人
+ contact, err := getContactByEmailAndGroup(req.Email, group.Id)
+ if err != nil || contact == nil {
+ res.SetError(gerror.New(public.LangCtx(ctx, "联系人不存在")))
+ return
+ }
+ hostUrl := public.GethostUrl()
+ if contact.Status == 1 {
+ // 已确认
+ if group.AlreadyUrl != "" {
+ res.Data = group.AlreadyUrl
+ } else {
+ res.Data = fmt.Sprintf("%s/already_subscribed.html", hostUrl)
+ }
+ res.SetSuccess(public.LangCtx(ctx, "已订阅"))
+ return
+ }
+
+ // 4. 更新联系人状态为已确认
+ err = updateContactStatus(req.Email, group.Id, 1)
+ if err != nil {
+ res.SetError(gerror.New(public.LangCtx(ctx, "更新联系人状态失败")))
+ return
+ }
+
+ // 5. 发送欢迎邮件
+ if group.SendWelcomeEmail == 1 {
+ if group.WelcomeHtml == "" {
+ // 取默认欢迎邮件模版
+ group.WelcomeHtml, _ = GetDefaultTemplate(1)
+ }
+ if group.WelcomeSubject == "" {
+ group.WelcomeSubject = "默认主题"
+ }
+ gtimer.AddOnce(500*time.Millisecond, func() {
+
+ err = sendMail(ctx, group.WelcomeHtml, req.Email, group.WelcomeSubject, "")
+ if err != nil {
+ g.Log().Error(ctx, "Failed to send welcome email: {}", err)
+ return
+ }
+
+ })
+ }
+
+
+ // 6. 跳转到订阅成功页面
+ if group.SuccessUrl != "" {
+ res.Data = group.SuccessUrl
+ } else {
+ res.Data = fmt.Sprintf("%s/subscribe_success.html", hostUrl)
+ }
+ res.SetSuccess(public.LangCtx(ctx, "订阅成功"))
+ return
+}
diff --git a/core/internal/controller/subscribe_list/subscribe_list_v1_subscribe_submit.go b/core/internal/controller/subscribe_list/subscribe_list_v1_subscribe_submit.go
new file mode 100644
index 00000000..749dae70
--- /dev/null
+++ b/core/internal/controller/subscribe_list/subscribe_list_v1_subscribe_submit.go
@@ -0,0 +1,138 @@
+package subscribe_list
+
+import (
+ "billionmail-core/api/subscribe_list/v1"
+ "billionmail-core/internal/service/public"
+ "context"
+ "fmt"
+ "github.com/gogf/gf/os/gtimer"
+ "github.com/gogf/gf/v2/errors/gerror"
+ "github.com/gogf/gf/v2/frame/g"
+ "time"
+)
+
+func (c *ControllerV1) SubscribeSubmit(ctx context.Context, req *v1.SubscribeSubmitReq) (res *v1.SubscribeSubmitRes, err error) {
+
+ res = &v1.SubscribeSubmitRes{}
+
+ // 1. 查找订阅组
+ group, err := getGroupByToken(req.Token)
+ if err != nil || group.Id == 0 {
+ res.SetError(gerror.New(public.LangCtx(ctx, "订阅组不存在")))
+ return
+ }
+
+ hostUrl := public.GethostUrl()
+
+ // 2. 查找联系人 存在联系人且已确认 -- 已订阅 存在联系人但未确认 -- 二次确认 不存在联系人 -- 一次确认
+ contact, err := getContactByEmailAndGroup(req.Email, group.Id)
+
+ if contact.Id != 0 {
+ if contact.Active == 0 {
+ // 存在联系人但退订,更新状态为1 改为已订阅
+ err = updateContactStatus(req.Email, group.Id, 1)
+ if err != nil {
+ res.SetError(gerror.New(public.LangCtx(ctx, "更新联系人状态失败")))
+ return
+ }
+
+ if group.SuccessUrl != "" {
+ res.Data = group.SuccessUrl
+ } else {
+ res.Data = fmt.Sprintf("%s/subscribe_success.html", hostUrl)
+
+ }
+ res.SetSuccess(public.LangCtx(ctx, "已订阅1"))
+ return
+ }
+ if contact.Status == 1 {
+ // 已订阅
+ if group.AlreadyUrl != "" {
+ res.Data = group.AlreadyUrl
+ } else {
+ res.Data = fmt.Sprintf("%s/already_subscribed.html", hostUrl)
+ }
+ res.SetSuccess(public.LangCtx(ctx, "已订阅2"))
+ return
+ } else {
+ // 存在联系人但未确认
+ }
+ }
+
+ // 3. 判断是否二次确认
+ if group.DoubleOptin == 1 {
+ // 二次确认
+ // 3.1 添加/更新联系人,status=0
+ err = addOrUpdateContact(req.Email, group.Id, req.Attribs, 0)
+ if err != nil {
+ res.SetError(gerror.New(public.LangCtx(ctx, "添加联系人失败")))
+ return
+ }
+
+ // 3.2 发送确认邮件
+ confirmToken := generateConfirmToken(req.Email, group.Token)
+ confirmUrl := buildConfirmUrl(confirmToken)
+
+ if group.ConfirmHtml == "" {
+ group.ConfirmHtml, _ = GetDefaultTemplate(2)
+ }
+ if group.ConfirmSubject == "" {
+ group.ConfirmSubject = "默认主题"
+ }
+ gtimer.AddOnce(500*time.Millisecond, func() {
+ err = sendMail(ctx, group.ConfirmHtml, req.Email, group.ConfirmSubject, confirmUrl)
+ if err != nil {
+ g.Log().Error(ctx, "Failed to send confirm email: {}", err)
+ return
+ }
+
+ })
+
+ // 3.3 跳转到订阅确认页面
+ if group.ConfirmUrl != "" {
+ res.Data = group.ConfirmUrl
+ } else {
+ res.Data = fmt.Sprintf("%s/subscribe_confirm.html", hostUrl)
+ }
+
+ res.SetError(gerror.New(public.LangCtx(ctx, "请检查您的邮箱进行确认订阅")))
+ return
+ } else {
+ // 一次确认
+ // 4.1 添加/更新联系人,status=1
+ err = addOrUpdateContact(req.Email, group.Id, req.Attribs, 1)
+ if err != nil {
+ res.SetError(gerror.New(public.LangCtx(ctx, "添加联系人失败")))
+ return
+ }
+ // 4.2 发送欢迎邮件 当组内允许发送时发送
+ if group.SendWelcomeEmail == 1 {
+ if group.WelcomeHtml == "" {
+ // 取默认欢迎邮件模版
+ group.WelcomeHtml, _ = GetDefaultTemplate(1)
+ }
+ if group.WelcomeSubject == "" {
+ group.WelcomeSubject = "默认主题"
+ }
+ gtimer.AddOnce(500*time.Millisecond, func() {
+
+ err = sendMail(ctx, group.WelcomeHtml, req.Email, group.WelcomeSubject, "")
+ if err != nil {
+ g.Log().Error(ctx, "Failed to send welcome email: {}", err)
+ return
+ }
+
+ })
+ }
+
+ // 4.3 跳转到订阅成功页面
+ if group.SuccessUrl != "" {
+ res.Data = group.SuccessUrl
+ } else {
+ res.Data = fmt.Sprintf("%s/subscribe_success.html", hostUrl)
+ }
+ res.SetSuccess(public.LangCtx(ctx, "Subscribe successfully"))
+ return
+
+ }
+}
diff --git a/core/internal/service/subscribe_list/subscribe_url.go b/core/internal/service/subscribe_list/subscribe_url.go
new file mode 100644
index 00000000..1de10e71
--- /dev/null
+++ b/core/internal/service/subscribe_list/subscribe_url.go
@@ -0,0 +1,34 @@
+package subscribe_list
+
+import (
+ "billionmail-core/internal/service/public"
+ "context"
+ "github.com/gogf/gf/v2/frame/g"
+ "github.com/gogf/gf/v2/os/gfile"
+ "path/filepath"
+ "strings"
+)
+
+func ReplaceSubmitUrl(ctx context.Context) {
+
+ hostwork := public.HostWorkDir
+ filePath := filepath.Join(hostwork, "/core/public/html/subscribe_form.html")
+ content := gfile.GetContents(filePath)
+
+ if !strings.Contains(content, "{{ SubmitURL . }}") {
+ return
+ }
+
+ var submitUrl string
+ hostUrl := public.GethostUrl()
+ submitUrl = hostUrl + "/api/subscribe/submit"
+
+ newContent := strings.ReplaceAll(content, "{{ SubmitURL . }}", submitUrl)
+
+ err := gfile.PutContents(filePath, newContent)
+ if err != nil {
+ g.Log().Errorf(ctx, "Failed to update subscribe form URL: %v", err)
+
+ }
+
+}
diff --git a/core/public/html/already_subscribed.html b/core/public/html/already_subscribed.html
new file mode 100644
index 00000000..1d689f15
--- /dev/null
+++ b/core/public/html/already_subscribed.html
@@ -0,0 +1,22 @@
+<!DOCTYPE html>
+<html lang="zh-CN">
+<head>
+ <meta charset="UTF-8">
+ <title>您已订阅</title>
+ <style>
+ body { font-family: Arial, sans-serif; background: #f7f7f7; padding: 40px; }
+ .container { background: #fff; max-width: 400px; margin: auto; border-radius: 8px; box-shadow: 0 2px 8px #eee; padding: 32px; text-align: center; }
+ .title { color: #2d8cf0; font-size: 22px; margin-bottom: 16px; }
+ .content { color: #333; font-size: 16px; }
+ </style>
+</head>
+<body>
+<div class="container">
+ <div class="title">您已订阅</div>
+ <div class="content">
+ 您已经订阅过我们的邮件,无需重复操作。<br>
+ 如有疑问请联系我们。
+ </div>
+</div>
+</body>
+</html>
\ No newline at end of file
diff --git a/core/public/html/subscribe_confirm.html b/core/public/html/subscribe_confirm.html
new file mode 100644
index 00000000..474bd5c7
--- /dev/null
+++ b/core/public/html/subscribe_confirm.html
@@ -0,0 +1,22 @@
+<!DOCTYPE html>
+<html lang="zh-CN">
+<head>
+ <meta charset="UTF-8">
+ <title>请前往邮箱确认订阅</title>
+ <style>
+ body { font-family: Arial, sans-serif; background: #f7f7f7; padding: 40px; }
+ .container { background: #fff; max-width: 400px; margin: auto; border-radius: 8px; box-shadow: 0 2px 8px #eee; padding: 32px; text-align: center; }
+ .title { color: #faad14; font-size: 22px; margin-bottom: 16px; }
+ .content { color: #333; font-size: 16px; }
+ </style>
+</head>
+<body>
+<div class="container">
+ <div class="title">请前往邮箱确认订阅</div>
+ <div class="content">
+ 我们已向您的邮箱发送了一封确认邮件,请点击邮件中的链接完成订阅。<br>
+ 如果未收到邮件,请检查垃圾箱或稍后重试。
+ </div>
+</div>
+</body>
+</html>
\ No newline at end of file
diff --git a/core/public/html/subscribe_form_code.html b/core/public/html/subscribe_form_code.html
new file mode 100644
index 00000000..af8e95b2
--- /dev/null
+++ b/core/public/html/subscribe_form_code.html
@@ -0,0 +1,33 @@
+<form id="subscribeForm" method="post" action="{{ SubmitURL . }}">
+ <label for="email">Email Address</label><br>
+ <input type="email" id="email" name="email" required placeholder="Please enter your email address"><br>
+
+ <label for="name">Name (Optional)</label><br>
+ <input type="text" id="name" name="name" placeholder="Please enter your name"><br>
+
+ <label for="name">Company (Optional)</label><br>
+ <label for="company"></label><input type="text" id="company" name="company" placeholder="Please enter your company"><br>
+
+ <!-- Extensible custom property fields, example: -->
+ <!-- <label for="name">Company (Optional)</label><br>-->
+ <!-- <label for="company"></label><input type="text" id="company" name="company" placeholder="Please enter your company"><br>-->
+
+ <input type="hidden" id="attribs" name="attribs" value="">
+ <button type="submit">Subscribe Now</button>
+</form>
+
+<script>
+document.getElementById('subscribeForm').onsubmit = function (e) {
+ var form = this;
+ var attribs = {};
+ var inputs = form.querySelectorAll('input');
+ for (var i = 0; i < inputs.length; i++) {
+ var input = inputs[i];
+ if (input.name === 'email' || input.name === 'attribs') continue;
+ if (input.name && input.value !== undefined) {
+ attribs[input.name] = input.value;
+ }
+ }
+ form.querySelector('input[name="attribs"]').value = JSON.stringify(attribs);
+};
+</script>
diff --git a/core/public/html/subscribe_success.html b/core/public/html/subscribe_success.html
new file mode 100644
index 00000000..e0df3354
--- /dev/null
+++ b/core/public/html/subscribe_success.html
@@ -0,0 +1,21 @@
+<!DOCTYPE html>
+<html lang="zh-CN">
+<head>
+ <meta charset="UTF-8">
+ <title>订阅成功</title>
+ <style>
+ body { font-family: Arial, sans-serif; background: #f7f7f7; padding: 40px; }
+ .container { background: #fff; max-width: 400px; margin: auto; border-radius: 8px; box-shadow: 0 2px 8px #eee; padding: 32px; text-align: center; }
+ .title { color: #52c41a; font-size: 22px; margin-bottom: 16px; }
+ .content { color: #333; font-size: 16px; }
+ </style>
+</head>
+<body>
+<div class="container">
+ <div class="title">订阅成功!</div>
+ <div class="content">
+ 感谢您的订阅,您将会第一时间收到我们的最新资讯。
+ </div>
+</div>
+</body>
+</html>
\ No newline at end of file