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

Subscribe to list related features

lotkcbb3a6692df0
diff --git a/core/api/batch_mail/batch_mail.go b/core/api/batch_mail/batch_mail.go
index 8643196a..5fc41c58 100644
--- a/core/api/batch_mail/batch_mail.go
+++ b/core/api/batch_mail/batch_mail.go
@@ -17,6 +17,7 @@ type IBatchMailV1 interface {
ApiTemplatesUpdate(ctx context.Context, req *v1.ApiTemplatesUpdateReq) (res *v1.ApiTemplatesUpdateRes, err error)
ApiTemplatesDelete(ctx context.Context, req *v1.ApiTemplatesDeleteReq) (res *v1.ApiTemplatesDeleteRes, err error)
ApiMailSend(ctx context.Context, req *v1.ApiMailSendReq) (res *v1.ApiMailSendRes, err error)
+ ApiMailBatchSend(ctx context.Context, req *v1.ApiMailBatchSendReq) (res *v1.ApiMailBatchSendRes, err error)
ListTasks(ctx context.Context, req *v1.ListTasksReq) (res *v1.ListTasksRes, err error)
TaskInfo(ctx context.Context, req *v1.TaskInfoReq) (res *v1.TaskInfoRes, err error)
TaskOverview(ctx context.Context, req *v1.TaskOverviewReq) (res *v1.TaskOverviewRes, err error)
diff --git a/core/api/contact/contact.go b/core/api/contact/contact.go
index be18da7c..34cceb32 100644
--- a/core/api/contact/contact.go
+++ b/core/api/contact/contact.go
@@ -24,5 +24,6 @@ type IContactV1 interface {
UpdateContactsGroup(ctx context.Context, req *v1.UpdateContactsGroupReq) (res *v1.UpdateContactsGroupRes, err error)
GetContactsTrend(ctx context.Context, req *v1.GetContactsTrendReq) (res *v1.GetContactsTrendRes, err error)
GetGroupContactCount(ctx context.Context, req *v1.GetGroupContactCountReq) (res *v1.GetGroupContactCountRes, err error)
+ GetGroupInfo(ctx context.Context, req *v1.GetGroupInfoReq) (res *v1.GetGroupInfoRes, err error)
EditContacts(ctx context.Context, req *v1.EditContactsReq) (res *v1.EditContactsRes, err error)
}
diff --git a/core/api/contact/v1/contact.go b/core/api/contact/v1/contact.go
index 369eb079..af185e48 100644
--- a/core/api/contact/v1/contact.go
+++ b/core/api/contact/v1/contact.go
@@ -11,17 +11,32 @@ type ContactGroup struct {
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 ContactGroupInfo 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"`
+ ContactGroup
TotalCount int `json:"total_count" dc:"Total Contacts"`
ActiveCount int `json:"active_count" dc:"Subscribed Contacts"`
UnsubscribeCount int `json:"unsubscribe_count" dc:"Unsubscribed Contacts"`
+ SubscribeLink string `json:"subscribe_link" dc:"Subscription Link"`
+ Sender string `json:"sender" dc:"Sender"`
}
type GroupInfo struct {
@@ -50,7 +65,7 @@ type CreateGroupReq struct {
FileData string `json:"file_data" dc:"file data"`
FileType string `json:"file_type" v:"in:csv,excel,txt" dc:"file type, default:txt"`
CreateType int `json:"create_type" v:"required|in:1,2,3" dc:"Create type (1: Create group only 2: Create new group and import contacts 3: Import files into existing groups)"`
- Status int `json:"status" v:"in:0,1" dc:"Data confirmation (1:Confirmed 0:Unconfirmed) Default:0"`
+ DoubleOptin int `json:"double_optin" v:"in:0,1" dc:"Data confirmation ( 0: Single Opt-in, 1: Double Opt-in) Default:0"`
}
type CreateGroupRes struct {
@@ -115,6 +130,19 @@ type UpdateGroupReq struct {
GroupId int `json:"group_id" v:"required" dc:"Group ID"`
Name string `json:"name" dc:"Group Name"`
Description string `json:"description" dc:"Description"`
+ DoubleOptin int `json:"double_optin" v:"in:0,1" dc:"Double Opt-in Status(0: Single Opt-in 1: Double Opt-in) Default:0"`
+ WelcomeHtml string `json:"welcome_mail_html" dc:"Welcome Email Html"`
+ WelcomeDrag string `json:"welcome_mail_drag" dc:"Welcome Email Drag"`
+ 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"`
+
+ 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"`
}
type UpdateGroupRes struct {
@@ -211,6 +239,7 @@ type UpdateContactsGroupRes struct {
type GetContactsTrendReq struct {
g.Meta `path:"/contact/trend" method:"get" tags:"Contact" summary:"Get contact trend"`
Authorization string `json:"authorization" dc:"Authorization" in:"header"`
+ GroupId int `json:"group_id" dc:"Group ID"`
}
type MonthlyTrend struct {
@@ -245,6 +274,17 @@ type GetGroupContactCountRes struct {
} `json:"data" dc:"Data"`
}
+type GetGroupInfoReq struct {
+ g.Meta `path:"/contact/group/info" method:"get" tags:"Contact" summary:"Get group info"`
+ Authorization string `json:"authorization" dc:"Authorization" in:"header"`
+ GroupId int `json:"group_id" v:"required" dc:"Group ID"`
+}
+
+type GetGroupInfoRes struct {
+ api_v1.StandardRes
+ Data *ContactGroupInfo `json:"data" dc:"Group Info"`
+}
+
type EditContactsReq struct {
g.Meta `path:"/contact/edit" method:"post" tags:"Contact" summary:"Edit contact"`
Authorization string `json:"authorization" dc:"Authorization" in:"header"`
diff --git a/core/api/subscribe_list/v1/subscribe_list.go b/core/api/subscribe_list/v1/subscribe_list.go
index 19cca66f..6d563374 100644
--- a/core/api/subscribe_list/v1/subscribe_list.go
+++ b/core/api/subscribe_list/v1/subscribe_list.go
@@ -39,7 +39,6 @@ type Contact struct {
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"`
@@ -51,7 +50,6 @@ 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"`
diff --git a/core/internal/cmd/cmd.go b/core/internal/cmd/cmd.go
index b2826123..2cf86278 100644
--- a/core/internal/cmd/cmd.go
+++ b/core/internal/cmd/cmd.go
@@ -17,6 +17,7 @@ import (
"billionmail-core/internal/controller/rbac"
"billionmail-core/internal/controller/relay"
"billionmail-core/internal/controller/settings"
+ "billionmail-core/internal/controller/subscribe_list"
"billionmail-core/internal/service/database_initialization"
docker "billionmail-core/internal/service/dockerapi"
"billionmail-core/internal/service/maillog_stat"
@@ -233,6 +234,7 @@ var (
mail_services.NewV1(),
relay.NewV1(),
settings.NewV1(),
+ subscribe_list.NewV1(),
)
})
diff --git a/core/internal/controller/contact/contact.go b/core/internal/controller/contact/contact.go
index 5641fb21..aea79423 100644
--- a/core/internal/controller/contact/contact.go
+++ b/core/internal/controller/contact/contact.go
@@ -9,9 +9,12 @@ import (
"bytes"
"encoding/csv"
"fmt"
+ "github.com/gogf/gf/crypto/gmd5"
"github.com/gogf/gf/v2/errors/gerror"
"github.com/xuri/excelize/v2"
+ "math/rand"
"strings"
+ "time"
)
const (
@@ -361,3 +364,9 @@ func exportToExcel(contacts []*entity.Contact) ([]byte, error) {
return buf.Bytes(), nil
}
+
+// GfMd5Short generates a short MD5 hash based on the current time and a random number
+func GfMd5Short() string {
+ str := fmt.Sprintf("%s_%d_%d", time.Now().UnixNano(), rand.Intn(100000))
+ return gmd5.MustEncryptString(str)[:12]
+}
diff --git a/core/internal/controller/contact/contact_v1_create_group.go b/core/internal/controller/contact/contact_v1_create_group.go
index d9329c69..1959372f 100644
--- a/core/internal/controller/contact/contact_v1_create_group.go
+++ b/core/internal/controller/contact/contact_v1_create_group.go
@@ -28,7 +28,7 @@ func (c *ControllerV1) CreateGroup(ctx context.Context, req *v1.CreateGroupReq)
}
// create new group
- groupId, err = contact.CreateGroup(ctx, req.Name, req.Description)
+ groupId, err = contact.CreateGroup(ctx, req.Name, req.Description, req.DoubleOptin)
if err != nil {
res.Code = 500
res.SetError(gerror.New(public.LangCtx(ctx, "Failed to create group {}", err.Error())))
@@ -77,7 +77,7 @@ func (c *ControllerV1) CreateGroup(ctx context.Context, req *v1.CreateGroupReq)
// set group id
for _, contactInfo := range contacts {
contactInfo.GroupId = groupId
- contactInfo.Status = req.Status
+ contactInfo.Status = 1
}
err = contact.BatchCreateContacts(ctx, contacts)
diff --git a/core/internal/controller/contact/contact_v1_get_contacts_trend.go b/core/internal/controller/contact/contact_v1_get_contacts_trend.go
index 92608029..c65f87f1 100644
--- a/core/internal/controller/contact/contact_v1_get_contacts_trend.go
+++ b/core/internal/controller/contact/contact_v1_get_contacts_trend.go
@@ -15,7 +15,7 @@ func (c *ControllerV1) GetContactsTrend(ctx context.Context, req *v1.GetContacts
// Get trend data for the last 12 months
now := time.Now()
- trends, err := contact.GetContactsTrend(ctx, now.AddDate(0, -11, 0), now)
+ trends, err := contact.GetContactsTrend(ctx, now.AddDate(0, -11, 0), now, req.GroupId)
if err != nil {
res.Code = 500
res.SetError(gerror.New(public.LangCtx(ctx, "Failed to get contacts trend: {}", err.Error())))
diff --git a/core/internal/controller/contact/contact_v1_get_group_info.go b/core/internal/controller/contact/contact_v1_get_group_info.go
index b0e48ba7..02143865 100644
--- a/core/internal/controller/contact/contact_v1_get_group_info.go
+++ b/core/internal/controller/contact/contact_v1_get_group_info.go
@@ -58,36 +58,39 @@ func (c *ControllerV1) GetGroupInfo(ctx context.Context, req *v1.GetGroupInfoReq
group.SubscribeForm = subscribe_list.GetSubscribeFormCode(group.Token)
}
if group.WelcomeSubject == "" {
- group.WelcomeSubject = "默认主题"
+ group.WelcomeSubject = "Welcome Aboard!"
}
if group.ConfirmSubject == "" {
- group.ConfirmSubject = "默认主题"
+ group.ConfirmSubject = "Confirm Your Subscription"
}
+ DefaultDomain, err := subscribe_list.GetDefaultDomain()
+ noreplyEmail := "noreply@" + DefaultDomain
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,
+ 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,
+ Sender: noreplyEmail,
}
res.Data = groupInfo
diff --git a/core/internal/controller/contact/contact_v1_list_groups.go b/core/internal/controller/contact/contact_v1_list_groups.go
index 48089222..1df99019 100644
--- a/core/internal/controller/contact/contact_v1_list_groups.go
+++ b/core/internal/controller/contact/contact_v1_list_groups.go
@@ -2,10 +2,12 @@ package contact
import (
"billionmail-core/api/contact/v1"
+ "billionmail-core/internal/controller/subscribe_list"
"billionmail-core/internal/service/contact"
"billionmail-core/internal/service/public"
"context"
"github.com/gogf/gf/v2/errors/gerror"
+ "github.com/gogf/gf/v2/frame/g"
)
func (c *ControllerV1) ListGroups(ctx context.Context, req *v1.ListGroupsReq) (res *v1.ListGroupsRes, err error) {
@@ -29,7 +31,7 @@ func (c *ControllerV1) ListGroups(ctx context.Context, req *v1.ListGroupsReq) (r
res.SetError(gerror.New(public.LangCtx(ctx, "Failed to get group list {}", err.Error())))
return
}
-
+ hostUrl := public.GethostUrl()
// Convert group information
groupInfos := make([]*v1.ContactGroupInfo, 0, len(groups))
for _, group := range groups {
@@ -44,16 +46,76 @@ func (c *ControllerV1) ListGroups(ctx context.Context, req *v1.ListGroupsReq) (r
unsubscribeCount = 0
}
- // Convert to group information
- groupInfo := &v1.ContactGroupInfo{
+ // If the group token is empty, generate a new token
+ 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 = "Welcome Aboard!"
+ }
+ if group.ConfirmSubject == "" {
+ group.ConfirmSubject = "Confirm Your Subscription"
+ }
+
+ 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,
+ }
+
+ // Convert to group information
+ groupInfo := &v1.ContactGroupInfo{
+ ContactGroup: contactGroup,
TotalCount: activeCount + unsubscribeCount,
ActiveCount: activeCount,
UnsubscribeCount: unsubscribeCount,
+ SubscribeLink: hostUrl + "/subscribe_form.html?token=" + group.Token,
}
groupInfos = append(groupInfos, groupInfo)
}
diff --git a/core/internal/controller/contact/contact_v1_update_group.go b/core/internal/controller/contact/contact_v1_update_group.go
index 402f69b9..9c6c4b0c 100644
--- a/core/internal/controller/contact/contact_v1_update_group.go
+++ b/core/internal/controller/contact/contact_v1_update_group.go
@@ -5,6 +5,7 @@ import (
"billionmail-core/internal/service/contact"
"billionmail-core/internal/service/public"
"context"
+ "database/sql"
"github.com/gogf/gf/v2/errors/gerror"
"github.com/gogf/gf/v2/frame/g"
)
@@ -12,15 +13,62 @@ import (
func (c *ControllerV1) UpdateGroup(ctx context.Context, req *v1.UpdateGroupReq) (res *v1.UpdateGroupRes, err error) {
res = &v1.UpdateGroupRes{}
- data := g.Map{}
+ updateData := g.Map{}
if req.Name != "" {
- data["name"] = req.Name
+ updateData["name"] = req.Name
}
if req.Description != "" {
- data["description"] = req.Description
+ updateData["description"] = req.Description
}
+ updateData["double_optin"] = req.DoubleOptin
+ updateData["send_welcome_email"] = req.SendWelcomeEmail
- err = contact.UpdateGroup(ctx, req.GroupId, data)
+ if req.WelcomeHtml != "" {
+ updateData["welcome_mail_html"] = req.WelcomeHtml
+ }
+ if req.WelcomeDrag != "" {
+ updateData["welcome_mail_drag"] = req.WelcomeDrag
+ }
+ if req.ConfirmHtml != "" {
+ updateData["confirm_mail_html"] = req.ConfirmHtml
+ }
+ if req.ConfirmDrag != "" {
+ updateData["confirm_mail_drag"] = req.ConfirmDrag
+ }
+ if req.SuccessUrl != "" {
+ updateData["success_url"] = req.SuccessUrl
+ }
+ if req.ConfirmUrl != "" {
+ updateData["confirm_url"] = req.ConfirmUrl
+ }
+ if req.AlreadyUrl != "" {
+ updateData["already_url"] = req.AlreadyUrl
+ }
+ //if req.SubscribeForm != "" {
+ // updateData["subscribe_form"] = req.SubscribeForm
+ //}
+
+ if req.WelcomeSubject != "" {
+ updateData["welcome_subject"] = req.WelcomeSubject
+ }
+ if req.ConfirmSubject != "" {
+ updateData["confirm_subject"] = req.ConfirmSubject
+ }
+
+ if len(updateData) == 0 {
+ res.Code = 400
+ res.SetError(gerror.New(public.LangCtx(ctx, "No fields to update")))
+ return
+ }
+
+ _, err = contact.GetGroup(ctx, req.GroupId)
+ if err != nil && err != sql.ErrNoRows {
+ res.Code = 404
+ res.SetError(gerror.New(public.LangCtx(ctx, "Group not found")))
+ return
+ }
+
+ err = contact.UpdateGroup(ctx, req.GroupId, updateData)
if err != nil {
res.Code = 500
res.SetError(gerror.New(public.LangCtx(ctx, "Failed to update group: {}", err.Error())))
diff --git a/core/internal/controller/subscribe_list/subscribe_list.go b/core/internal/controller/subscribe_list/subscribe_list.go
index b2cc23ed..3dc95a5b 100644
--- a/core/internal/controller/subscribe_list/subscribe_list.go
+++ b/core/internal/controller/subscribe_list/subscribe_list.go
@@ -25,29 +25,6 @@ import (
"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)
@@ -57,9 +34,7 @@ func getGroupByToken(token string) (*entity.ContactGroup, error) {
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).
@@ -72,20 +47,11 @@ func getContactByEmailAndGroup(email string, groupId int) (*entity.Contact, erro
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 // 已经存在联系人,直接设置为已确认状态
- }
-
- // 如果已存在则更新,否则插入
+ // If exists, update; otherwise, insert
var contact entity.Contact
- err = g.DB().Model("bm_contacts").
+ err := g.DB().Model("bm_contacts").
Where("email", email).
Where("group_id", groupId).
Scan(&contact)
@@ -99,7 +65,7 @@ func addOrUpdateContact(email string, groupId int, attribs map[string]string, st
}
if g.IsEmpty(contact) {
- // 插入新联系人
+ // Insert new contact
contact = entity.Contact{
Email: email,
GroupId: groupId,
@@ -112,7 +78,7 @@ func addOrUpdateContact(email string, groupId int, attribs map[string]string, st
}
}
- // 更新现有联系人
+ // Update existing contact
contact.Status = status
contact.Attribs = attribs
_, err = g.DB().Model("bm_contacts").Data(contact).Where("id", contact.Id).Update()
@@ -123,10 +89,8 @@ func addOrUpdateContact(email string, groupId int, attribs map[string]string, st
return nil
}
-// 更新联系人状态 确认(0,1) 订阅1
+// Update contact status: confirm (0,1), subscribe = 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).
@@ -139,31 +103,31 @@ func updateContactStatus(email string, groupId int, status int) error {
func readTemplateFiles(baseFilename string) (htmlContent string, txtContent string, err error) {
hostwork := public.HostWorkDir
- // 构造两个文件路径(自动处理不同操作系统分隔符)
+ // Construct two file paths (automatically handle OS-specific separators)
htmlPath := filepath.Join(hostwork, "core", "data", baseFilename+".html")
txtPath := filepath.Join(hostwork, "core", "data", baseFilename+".txt")
- // 安全检查(防止目录遍历)
+ // Security check (prevent directory traversal)
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)
+ return "", "", fmt.Errorf("illegal path access: %s", baseFilename)
}
- // 读取HTML文件
+ // Read HTML file
htmlBytes, err := os.ReadFile(htmlPath)
if err != nil {
- return "", "", fmt.Errorf("读取HTML模板失败: %w", err)
+ return "", "", fmt.Errorf("failed to read HTML template: %w", err)
}
- // 读取TXT文件(允许不存在)
+ // Read TXT file (allowed to not exist)
txtBytes, err := os.ReadFile(txtPath)
if err != nil {
if !os.IsNotExist(err) {
g.Log().Warningf(context.Background(),
- "读取TXT模板失败: %v, 路径: %s", err, txtPath)
+ "failed to read TXT template: %v, path: %s", err, txtPath)
}
- txtBytes = []byte("") // 不存在时返回空内容
+ txtBytes = []byte("") // Return empty content if file does not exist
}
return string(htmlBytes), string(txtBytes), nil
@@ -177,11 +141,11 @@ func GetDefaultTemplate(emailType int) (html string, txt string) {
)
switch emailType {
- case 1: // 欢迎邮件
+ case 1: // Welcome email
basePath = "default_welcome_email/welcome_email"
defaultHtml = "<p>Welcome to subscribe!</p>"
defaultTxt = ""
- case 2: // 确认邮件
+ case 2: // Confirmation email
basePath = "default_confirm_email/confirm_email"
defaultHtml = "<p>Please confirm your subscription.</p>"
defaultTxt = ""
@@ -192,7 +156,7 @@ func GetDefaultTemplate(emailType int) (html string, txt string) {
htmlContent, txtContent, err := readTemplateFiles(basePath)
if err != nil {
g.Log().Errorf(context.Background(),
- "获取模板失败,使用默认内容。错误: %v, 路径: %s",
+ "failed to load template, using default. Error: %v, Path: %s",
err, basePath)
return defaultHtml, defaultTxt
}
@@ -200,32 +164,32 @@ func GetDefaultTemplate(emailType int) (html string, txt string) {
return htmlContent, txtContent
}
-// 发送邮件
+// Send email
func sendMail(ctx context.Context, emailHtml, email, subject, confirmUrl string) error {
- // 1. 获取模板
+ // 1. Load template
if emailHtml == "" {
return gerror.New(public.LangCtx(ctx, "邮件模板ID不能为空"))
}
- // 如果存在{{ ConfirmURL . }}变量,则替换为确认链接
+ // If {{ ConfirmURL . }} variable exists, replace it with confirmation link
if strings.Contains(emailHtml, "{{ ConfirmURL . }}") {
if confirmUrl == "" {
- return gerror.New(public.LangCtx(ctx, "确认邮件需要提供确认链接"))
+ return gerror.New(public.LangCtx(ctx, "The confirmation email requires a confirmation link"))
}
emailHtml = strings.ReplaceAll(emailHtml, "{{ ConfirmURL . }}", confirmUrl)
}
- // 2. 获取联系人(用于变量替换)
+ // 2. Retrieve contact for variable replacement
var contact entity.Contact
_ = g.DB().Model("bm_contacts").Where("email", email).Scan(&contact)
- // 3. 退订链接处理
+ // 3. Handle unsubscribe link
content := emailHtml
//if !strings.Contains(content, "{{ UnsubscribeURL . }}") {
// content = public.AddUnsubscribeButton(content)
//}
- //// 4. 生成退订jwt和链接
+ //// 4. Generate unsubscribe JWT and link
//jwtToken, _ := batch_mail.GenerateUnsubscribeJWT(email, templateId, 0)
//domain := domains.GetBaseURL()
//unsubscribeURL := fmt.Sprintf("%s/api/unsubscribe", domain)
@@ -233,33 +197,32 @@ func sendMail(ctx context.Context, emailHtml, email, subject, confirmUrl string)
//unsubscribeJumpURL := fmt.Sprintf("%s/unsubscribe.html?jwt=%s&email=%s&url_type=%s&url_unsubscribe=%s",
// domain, jwtToken, email, groupURL, unsubscribeURL)
- // 5. 渲染内容和主题
+ // 5. Render content and subject
engine := batch_mail.GetTemplateEngine()
personalizedContent, err := engine.RenderEmailTemplate(ctx, content, &contact, nil, "")
if err != nil {
- return gerror.New(public.LangCtx(ctx, "渲染邮件内容失败"))
+ return gerror.New(public.LangCtx(ctx, "Failed to render email content"))
}
- 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, "渲染邮件主题失败"))
+ return gerror.New(public.LangCtx(ctx, "Failed to render email subject"))
}
- g.Log().Errorf(context.Background(), "主题: 33%v", personalizedSubject)
- //address := "[email protected]"
- DefaultDomain, err := getDefaultDomain()
+
+ DefaultDomain, err := GetDefaultDomain()
if err != nil {
- return gerror.New(public.LangCtx(ctx, "获取默认发件域名失败: {}", err))
+ return gerror.New(public.LangCtx(ctx, "Failed to get default sending domain: {}", err))
}
address, err := createNoreplyEmail(DefaultDomain)
if err != nil {
- return gerror.New(public.LangCtx(ctx, "查找noreply邮箱失败: {}", err))
+ return gerror.New(public.LangCtx(ctx, "Failed to find noreply email: {}", err))
}
- // 6. 创建发件人
+ // 6. Create sender
sender, err := mail_service.NewEmailSenderWithLocal(address)
if err != nil {
- return gerror.New(public.LangCtx(ctx, "创建发件人失败"))
+ return gerror.New(public.LangCtx(ctx, "Failed to create a sender"))
}
defer sender.Close()
messageId := sender.GenerateMessageID()
@@ -271,51 +234,52 @@ func sendMail(ctx context.Context, emailHtml, email, subject, confirmUrl string)
mail_tracker.AppendTrackingPixel()
renderedContent := mail_tracker.GetHTML()
- // 7. 创建消息
+ // 7. Create message
message := mail_service.NewMessage(personalizedSubject, renderedContent)
+ //message := mail_service.NewMessage(personalizedSubject, personalizedContent)
message.SetMessageID(messageId)
message.SetRealName("noreply")
- // 8. 发送邮件
+ // 8. Send email
err = sender.Send(message, []string{email})
if err != nil {
- return gerror.New(public.LangCtx(ctx, "发送邮件失败: {}", err))
+ return gerror.New(public.LangCtx(ctx, "Failed to send email: {}", err))
}
return nil
}
-// 生成token
+// Generate 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)
+ g.Log().Errorf(context.Background(), "Failed to generate subscription confirmation token: %v", err)
return ""
}
return token
}
-// 取token中的email groupToken
+// Extract email and groupToken from token
func getEmailFromToken(token string) (string, string, error) {
claims, err := batch_mail.ParseSubscribeConfirmJWT(token)
if err != nil {
- return "", "", gerror.New("解析订阅确认token失败: " + err.Error())
+ return "", "", gerror.New("Failed to parse subscription confirmation token: " + err.Error())
}
return claims.Email, claims.GroupToken, nil
}
-// 构建确认链接
+// Build confirmation URL
func buildConfirmUrl(token string) string {
hostUrl := public.GethostUrl()
return fmt.Sprintf("%s/api/subscribe/confirm?token=%s", hostUrl, token)
}
-// 查询发件邮箱是否存 创建
+// Query whether the sender email exists, create if not
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("查询邮箱失败")
+ return "", gerror.New("Failed to query email")
}
if count == 0 {
ctx := context.Background()
@@ -333,9 +297,8 @@ func createNoreplyEmail(domain string) (string, error) {
return noreplyEmail, nil
}
-// 获取默认发件域名
-func getDefaultDomain() (string, error) {
- ctx := context.Background()
+// Get default sending domain
+func GetDefaultDomain() (string, error) {
configuredDomain, err := g.DB().Model("bm_options").
Where("name", "default_sender_domain").
@@ -345,19 +308,17 @@ func getDefaultDomain() (string, error) {
return configuredDomain.String(), nil
}
- // 2. 获取最早创建的活跃域名
-
+ // 2. Get the oldest created active domain
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("没有可用的活跃域名,请先添加域名")
+ return "", gerror.New("No available active domains, please add one first")
}
- // 3. 保存到配置表
+ // 3. Save to config table
_, err = g.DB().Model("bm_options").
Data(g.Map{
"name": "default_sender_domain",
@@ -367,16 +328,14 @@ func getDefaultDomain() (string, error) {
Save()
if err != nil {
- g.Log().Errorf(ctx, "保存默认域名失败: %v", err)
- return "", gerror.Wrap(err, "保存默认发件域名配置失败")
+ return "", gerror.Wrap(err, "Failed to save default sender domain configuration")
}
return oldestDomain.String(), nil
}
-// 获取订阅表单代码
+// Get subscription form code
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)
@@ -384,7 +343,8 @@ func GetSubscribeFormCode(groupToken string) string {
if !strings.Contains(content, "{{ SubmitURL . }}") {
return ""
}
- // 链接对应页面
+
+ // Link to corresponding page
var submitUrl string
hostUrl := public.GethostUrl()
submitUrl = hostUrl + "/api/subscribe/submit?token=" + groupToken
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
index 2f2a6569..373cd882 100644
--- a/core/internal/controller/subscribe_list/subscribe_list_v1_subscribe_confirm.go
+++ b/core/internal/controller/subscribe_list/subscribe_list_v1_subscribe_confirm.go
@@ -17,54 +17,51 @@ func (c *ControllerV1) SubscribeConfirm(ctx context.Context, req *v1.SubscribeCo
email, groupToken, err := getEmailFromToken(req.Token)
if err != nil {
- res.SetError(gerror.New(public.LangCtx(ctx, "确认链接无效")))
+ g.RequestFromCtx(ctx).Response.RedirectTo("/invalid.html", 302)
return
}
if email == "" || groupToken == "" {
- res.SetError(gerror.New(public.LangCtx(ctx, "确认链接无效")))
+ g.RequestFromCtx(ctx).Response.RedirectTo("/invalid.html", 302)
return
}
- // 1. 查找订阅组
+ // 1. Find subscription group
group, err := getGroupByToken(groupToken)
if err != nil {
- res.SetError(gerror.New(public.LangCtx(ctx, "订阅组不存在")))
+ g.RequestFromCtx(ctx).Response.RedirectTo("/invalid.html", 302)
return
}
- // 2. 查找联系人
+ // 2. Find contact by email and group
contact, err := getContactByEmailAndGroup(req.Email, group.Id)
if err != nil || contact == nil {
- res.SetError(gerror.New(public.LangCtx(ctx, "联系人不存在")))
+ g.RequestFromCtx(ctx).Response.RedirectTo("/invalid.html", 302)
return
}
hostUrl := public.GethostUrl()
if contact.Status == 1 {
- // 已确认
if group.AlreadyUrl != "" {
- res.Data = group.AlreadyUrl
+ g.RequestFromCtx(ctx).Response.RedirectTo(group.AlreadyUrl, 302)
} else {
- res.Data = fmt.Sprintf("%s/already_subscribed.html", hostUrl)
+ g.RequestFromCtx(ctx).Response.RedirectTo(fmt.Sprintf("%s/already_subscribed.html", hostUrl), 302)
}
- res.SetSuccess(public.LangCtx(ctx, "已订阅"))
return
}
- // 4. 更新联系人状态为已确认
+ // 4. Update contact status to confirmed
err = updateContactStatus(req.Email, group.Id, 1)
if err != nil {
- res.SetError(gerror.New(public.LangCtx(ctx, "更新联系人状态失败")))
+ res.SetError(gerror.New(public.LangCtx(ctx, "Failed to update contact status")))
return
}
- // 5. 发送欢迎邮件
+ // 5. Send welcome email
if group.SendWelcomeEmail == 1 {
if group.WelcomeHtml == "" {
- // 取默认欢迎邮件模版
group.WelcomeHtml, _ = GetDefaultTemplate(1)
}
if group.WelcomeSubject == "" {
- group.WelcomeSubject = "默认主题"
+ group.WelcomeSubject = "Welcome Aboard!"
}
gtimer.AddOnce(500*time.Millisecond, func() {
@@ -77,13 +74,11 @@ func (c *ControllerV1) SubscribeConfirm(ctx context.Context, req *v1.SubscribeCo
})
}
-
- // 6. 跳转到订阅成功页面
+ // 6. Redirect to subscription success page
if group.SuccessUrl != "" {
- res.Data = group.SuccessUrl
+ g.RequestFromCtx(ctx).Response.RedirectTo(group.SuccessUrl, 302)
} else {
- res.Data = fmt.Sprintf("%s/subscribe_success.html", hostUrl)
+ g.RequestFromCtx(ctx).Response.RedirectTo(fmt.Sprintf("%s/subscribe_success.html", hostUrl), 302)
}
- 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
index 749dae70..e08e5384 100644
--- a/core/internal/controller/subscribe_list/subscribe_list_v1_subscribe_submit.go
+++ b/core/internal/controller/subscribe_list/subscribe_list_v1_subscribe_submit.go
@@ -12,72 +12,62 @@ import (
)
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, "订阅组不存在")))
+ g.RequestFromCtx(ctx).Response.RedirectTo("/invalid.html", 302)
return
}
hostUrl := public.GethostUrl()
- // 2. 查找联系人 存在联系人且已确认 -- 已订阅 存在联系人但未确认 -- 二次确认 不存在联系人 -- 一次确认
+ // 2. Find contact by email and group
contact, err := getContactByEmailAndGroup(req.Email, group.Id)
if contact.Id != 0 {
if contact.Active == 0 {
- // 存在联系人但退订,更新状态为1 改为已订阅
+ // Contact exists but unsubscribed, update status to 1 (subscribed)
err = updateContactStatus(req.Email, group.Id, 1)
if err != nil {
- res.SetError(gerror.New(public.LangCtx(ctx, "更新联系人状态失败")))
+ res.SetError(gerror.New(public.LangCtx(ctx, "Failed to update contact status")))
return
}
if group.SuccessUrl != "" {
- res.Data = group.SuccessUrl
+ g.RequestFromCtx(ctx).Response.RedirectTo(group.SuccessUrl, 302)
} else {
- res.Data = fmt.Sprintf("%s/subscribe_success.html", hostUrl)
-
+ g.RequestFromCtx(ctx).Response.RedirectTo(fmt.Sprintf("%s/subscribe_success.html", hostUrl), 302)
}
- res.SetSuccess(public.LangCtx(ctx, "已订阅1"))
return
}
if contact.Status == 1 {
- // 已订阅
if group.AlreadyUrl != "" {
- res.Data = group.AlreadyUrl
+ g.RequestFromCtx(ctx).Response.RedirectTo(group.AlreadyUrl, 302)
} else {
- res.Data = fmt.Sprintf("%s/already_subscribed.html", hostUrl)
+ g.RequestFromCtx(ctx).Response.RedirectTo(fmt.Sprintf("%s/already_subscribed.html", hostUrl), 302)
}
- res.SetSuccess(public.LangCtx(ctx, "已订阅2"))
return
- } else {
- // 存在联系人但未确认
}
}
- // 3. 判断是否二次确认
+ // 3. Check if double opt-in is enabled
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, "添加联系人失败")))
+ res.SetError(gerror.New(public.LangCtx(ctx, "Failed to add contact")))
return
}
- // 3.2 发送确认邮件
+ // 3.2 Send confirmation email
confirmToken := generateConfirmToken(req.Email, group.Token)
confirmUrl := buildConfirmUrl(confirmToken)
-
if group.ConfirmHtml == "" {
group.ConfirmHtml, _ = GetDefaultTemplate(2)
}
if group.ConfirmSubject == "" {
- group.ConfirmSubject = "默认主题"
+ group.ConfirmSubject = "Confirm Your Subscription"
}
gtimer.AddOnce(500*time.Millisecond, func() {
err = sendMail(ctx, group.ConfirmHtml, req.Email, group.ConfirmSubject, confirmUrl)
@@ -88,51 +78,44 @@ func (c *ControllerV1) SubscribeSubmit(ctx context.Context, req *v1.SubscribeSub
})
- // 3.3 跳转到订阅确认页面
+ // 3.3 Redirect to subscription confirmation page
if group.ConfirmUrl != "" {
- res.Data = group.ConfirmUrl
+ g.RequestFromCtx(ctx).Response.RedirectTo(group.ConfirmUrl, 302)
} else {
- res.Data = fmt.Sprintf("%s/subscribe_confirm.html", hostUrl)
+ g.RequestFromCtx(ctx).Response.RedirectTo(fmt.Sprintf("%s/subscribe_confirm.html", hostUrl), 302)
}
-
- res.SetError(gerror.New(public.LangCtx(ctx, "请检查您的邮箱进行确认订阅")))
return
} else {
- // 一次确认
- // 4.1 添加/更新联系人,status=1
+ // Single opt-in (no confirmation required)
+ // 4.1 Add or update contact with status=1 (confirmed)
err = addOrUpdateContact(req.Email, group.Id, req.Attribs, 1)
if err != nil {
- res.SetError(gerror.New(public.LangCtx(ctx, "添加联系人失败")))
+ res.SetError(gerror.New(public.LangCtx(ctx, "Failed to add contact")))
return
}
- // 4.2 发送欢迎邮件 当组内允许发送时发送
+
+ // 4.2 Send welcome email if enabled for the group
if group.SendWelcomeEmail == 1 {
if group.WelcomeHtml == "" {
- // 取默认欢迎邮件模版
group.WelcomeHtml, _ = GetDefaultTemplate(1)
}
if group.WelcomeSubject == "" {
- group.WelcomeSubject = "默认主题"
+ group.WelcomeSubject = "Welcome Aboard!"
}
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
+ g.RequestFromCtx(ctx).Response.RedirectTo(group.SuccessUrl, 302)
} else {
- res.Data = fmt.Sprintf("%s/subscribe_success.html", hostUrl)
+ g.RequestFromCtx(ctx).Response.RedirectTo(fmt.Sprintf("%s/subscribe_success.html", hostUrl), 302)
}
- res.SetSuccess(public.LangCtx(ctx, "Subscribe successfully"))
return
-
}
}
diff --git a/core/internal/model/entity/batch_mail.go b/core/internal/model/entity/batch_mail.go
index f5498717..83c14b96 100644
--- a/core/internal/model/entity/batch_mail.go
+++ b/core/internal/model/entity/batch_mail.go
@@ -7,6 +7,21 @@ type ContactGroup struct {
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"`
}
// Contact Entity
diff --git a/core/internal/service/batch_mail/batch_mail.go b/core/internal/service/batch_mail/batch_mail.go
index f92f5a1c..b6f2e532 100644
--- a/core/internal/service/batch_mail/batch_mail.go
+++ b/core/internal/service/batch_mail/batch_mail.go
@@ -273,6 +273,7 @@ func GetActiveContacts(ctx context.Context, groupId int) ([]*entity.Contact, err
err := g.DB().Model("bm_contacts").
Where("group_id", groupId).
Where("active", 1).
+ Where("status", 1). // Confirmed email address
Scan(&contacts)
return contacts, err
}
diff --git a/core/internal/service/batch_mail/jwt.go b/core/internal/service/batch_mail/jwt.go
index e9215a6c..9b1cabc2 100644
--- a/core/internal/service/batch_mail/jwt.go
+++ b/core/internal/service/batch_mail/jwt.go
@@ -13,7 +13,8 @@ import (
)
const (
- JWT_SECRET_KEY = "unsubscribe_jwt_secret"
+ JWT_SECRET_KEY = "unsubscribe_jwt_secret"
+ SUBSCRIBE_CONFIRM_JWT_SECRET = "subscribe_confirm_jwt_secret"
)
type UnsubscribeClaims struct {
@@ -193,3 +194,105 @@ func ParseUnsubscribeJWT(tokenString string) (*UnsubscribeClaims, error) {
return nil, errors.New("invalid token claims")
}
+
+type SubscribeConfirmClaims struct {
+ Email string `json:"email"`
+ GroupToken string `json:"group_token"`
+ jwt.RegisteredClaims
+}
+
+func getSubscribeConfirmConfig() *jwtConfig {
+ once.Do(func() {
+ config = loadSubscribeConfirmConfig()
+ })
+ return config
+}
+
+func loadSubscribeConfirmConfig() *jwtConfig {
+ ctx := gctx.New()
+ return &jwtConfig{
+ secret: getOrGenerateSubscribeConfirmSecret(ctx),
+ expiry: 30 * 24 * time.Hour,
+ }
+}
+
+func getOrGenerateSubscribeConfirmSecret(ctx context.Context) string {
+ val, err := g.DB().Model("bm_options").
+ Where("name", SUBSCRIBE_CONFIRM_JWT_SECRET).
+ Value("value")
+ if err == nil && val != nil && val.String() != "" {
+ return val.String()
+ }
+ newSecret := generateSecret(ctx)
+ _, err = g.DB().Model("bm_options").
+ Data(g.Map{
+ "name": SUBSCRIBE_CONFIRM_JWT_SECRET,
+ "value": newSecret,
+ }).
+ Where("name", SUBSCRIBE_CONFIRM_JWT_SECRET).
+ WhereNull("value").
+ Insert()
+ if err != nil {
+ g.Log().Warning(ctx, "Failed to persist subscribe confirm JWT secret to database:", err)
+ val, err := g.DB().Model("bm_options").
+ Where("name", SUBSCRIBE_CONFIRM_JWT_SECRET).
+ Value("value")
+ if err == nil && val != nil && val.String() != "" {
+ return val.String()
+ }
+ } else {
+ g.Log().Info(ctx, "Generated and persisted new subscribe confirm JWT secret")
+ }
+ return newSecret
+}
+
+func GenerateSubscribeConfirmJWT(email, groupToken string) (string, error) {
+ cfg := getSubscribeConfirmConfig()
+ claims := SubscribeConfirmClaims{
+ Email: email,
+ GroupToken: groupToken,
+ RegisteredClaims: jwt.RegisteredClaims{
+ ExpiresAt: jwt.NewNumericDate(time.Now().Add(cfg.expiry)),
+ IssuedAt: jwt.NewNumericDate(time.Now()),
+ },
+ }
+ token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)
+ return token.SignedString([]byte(cfg.secret))
+}
+
+func ParseSubscribeConfirmJWT(tokenString string) (*SubscribeConfirmClaims, error) {
+ if tokenString == "" {
+ return nil, errors.New("empty token string")
+ }
+ cfg := getSubscribeConfirmConfig()
+ token, err := jwt.Parse(tokenString, func(token *jwt.Token) (interface{}, error) {
+ if _, ok := token.Method.(*jwt.SigningMethodHMAC); !ok {
+ return nil, fmt.Errorf("unexpected signing method: %v", token.Header["alg"])
+ }
+ return []byte(cfg.secret), nil
+ })
+ if err != nil {
+ return nil, fmt.Errorf("failed to parse JWT: %w", err)
+ }
+ if claims, ok := token.Claims.(jwt.MapClaims); ok && token.Valid {
+ result := &SubscribeConfirmClaims{}
+ if email, ok := claims["email"].(string); ok {
+ result.Email = email
+ } else {
+ return nil, errors.New("JWT missing email claim")
+ }
+ if groupToken, ok := claims["group_token"].(string); ok {
+ result.GroupToken = groupToken
+ } else {
+ return nil, errors.New("JWT missing group_token claim")
+ }
+ if exp, ok := claims["exp"].(float64); ok {
+ if time.Now().Unix() > int64(exp) {
+ return nil, errors.New("JWT has expired")
+ }
+ result.RegisteredClaims.ExpiresAt = jwt.NewNumericDate(time.Unix(int64(exp), 0))
+ }
+ return result, nil
+ }
+ return nil, errors.New("invalid token claims")
+}
diff --git a/core/internal/service/contact/contact.go b/core/internal/service/contact/contact.go
index e7e641e7..565cad87 100644
--- a/core/internal/service/contact/contact.go
+++ b/core/internal/service/contact/contact.go
@@ -4,20 +4,27 @@ import (
v1 "billionmail-core/api/contact/v1"
"billionmail-core/internal/model/entity"
"context"
+ "database/sql"
"encoding/json"
+ "fmt"
+ "github.com/gogf/gf/crypto/gmd5"
"github.com/gogf/gf/v2/database/gdb"
"github.com/gogf/gf/v2/frame/g"
+ "math/rand"
"strings"
"time"
)
-func CreateGroup(ctx context.Context, name, description string) (int, error) {
+func CreateGroup(ctx context.Context, name, description string, double_optin int) (int, error) {
now := time.Now().Unix()
+ token := GfMd5Short()
data := g.Map{
- "name": name,
- "description": description,
- "create_time": int(now),
- "update_time": int(now),
+ "name": name,
+ "description": description,
+ "create_time": int(now),
+ "update_time": int(now),
+ "token": token,
+ "double_optin": double_optin,
}
lastInsertId, err := g.DB().Model("bm_contact_groups").Ctx(ctx).Data(data).InsertAndGetId()
return int(lastInsertId), err
@@ -42,7 +49,7 @@ func GetAllGroups(ctx context.Context, keyword string) ([]*v1.ContactGroup, erro
var groups []*v1.ContactGroup
err := model.Scan(&groups)
- if err != nil {
+ if err != nil && err != sql.ErrNoRows {
return nil, err
}
@@ -271,18 +278,17 @@ func GetContactGroupsInfo(ctx context.Context, email string, status int) ([]*ent
return groups, nil
}
-func GetContactsTrend(ctx context.Context, startTime, endTime time.Time) ([]*struct {
+type ContactTrend struct {
Month string `json:"month"`
SubscribeCount int `json:"subscribe_count"`
UnsubscribeCount int `json:"unsubscribe_count"`
-}, error) {
- var trends []*struct {
- Month string `json:"month"`
- SubscribeCount int `json:"subscribe_count"`
- UnsubscribeCount int `json:"unsubscribe_count"`
- }
+}
- err := g.DB().Model("bm_contacts").
+func GetContactsTrend(ctx context.Context, startTime, endTime time.Time, groupId int) ([]*ContactTrend, error) {
+
+ var trends []*ContactTrend
+
+ db := g.DB().Model("bm_contacts").
Fields(
"to_char(to_timestamp(create_time), 'YYYY-MM') as month",
"SUM(CASE WHEN active = 1 THEN 1 ELSE 0 END) as subscribe_count",
@@ -290,10 +296,21 @@ func GetContactsTrend(ctx context.Context, startTime, endTime time.Time) ([]*str
).
Where("create_time BETWEEN ? AND ?", startTime.Unix(), endTime.Unix()).
Group("month").
- Order("month ASC").
- Scan(&trends)
+ Order("month ASC")
+
+ if groupId != 0 {
+ db = db.Where("group_id = ?", groupId)
+ }
+
+ if err := db.Scan(&trends); err != nil {
+ return nil, fmt.Errorf("failed to get contacts trend: %w", err)
+ }
- return trends, err
+ if trends == nil {
+ return make([]*ContactTrend, 0), nil
+ }
+
+ return trends, nil
}
func UpdateContactsGroups(ctx context.Context, emails []string, status int, newGroupIds []int) (int, error) {
@@ -520,3 +537,8 @@ func BatchCreateContactsWithOverwrite(ctx context.Context, contacts []*entity.Co
return totalSuccessCount, nil
}
+
+func GfMd5Short() string {
+ str := fmt.Sprintf("%s_%d_%d", time.Now().UnixNano(), rand.Intn(100000))
+ return gmd5.MustEncryptString(str)[:12]
+}
diff --git a/core/internal/service/database_initialization/batch_mail.go b/core/internal/service/database_initialization/batch_mail.go
index c8277f85..8e2eaba7 100644
--- a/core/internal/service/database_initialization/batch_mail.go
+++ b/core/internal/service/database_initialization/batch_mail.go
@@ -6,6 +6,7 @@ import (
)
func init() {
+
registerHandler(func() {
batchMailSQLList := []string{
@@ -25,6 +26,10 @@ func init() {
confirm_url TEXT DEFAULT '', -- URL to redirect after confirmation
already_url TEXT DEFAULT '', -- URL to redirect if already subscribed
subscribe_form TEXT DEFAULT '', -- HTML form for subscription
+ confirm_subject TEXT DEFAULT '', -- Confirmation Email Subject
+ welcome_subject TEXT DEFAULT '', -- Welcome Email Subject
+ send_welcome_email SMALLINT NOT NULL DEFAULT 0,-- 0: No need to send email, 1: send email
+
UNIQUE(name)
)`,
@@ -191,6 +196,9 @@ func init() {
_ = AddColumnIfNotExists("bm_contact_groups", "welcome_mail_drag", "TEXT", "''", false)
_ = AddColumnIfNotExists("bm_contact_groups", "confirm_mail_html", "TEXT", "''", false)
_ = AddColumnIfNotExists("bm_contact_groups", "confirm_mail_drag", "TEXT", "''", false)
+ _ = AddColumnIfNotExists("bm_contact_groups", "confirm_subject", "TEXT", "''", false)
+ _ = AddColumnIfNotExists("bm_contact_groups", "welcome_subject", "TEXT", "''", false)
+ _ = AddColumnIfNotExists("bm_contact_groups", "send_welcome_email", "SMALLINT", "0", true)
g.Log().Info(context.Background(), "Batch mail tables initialized successfully")
})
diff --git a/core/internal/service/public/common.go b/core/internal/service/public/common.go
index 16d2f833..7a1a7f0c 100644
--- a/core/internal/service/public/common.go
+++ b/core/internal/service/public/common.go
@@ -2656,8 +2656,7 @@ func GethostUrl() string {
} else {
hostUrl = fmt.Sprintf("https://%s/", hostname)
}
- g.Log().Warning(context.Background(), "BillionMail host URL: ", hostUrl)
- //return hostUrl
- return "https://192.168.66.124:82"
+ return hostUrl
+
}
diff --git a/core/internal/service/rbac/jwt.go b/core/internal/service/rbac/jwt.go
index 75146004..57d0539b 100644
--- a/core/internal/service/rbac/jwt.go
+++ b/core/internal/service/rbac/jwt.go
@@ -151,7 +151,17 @@ func (s *JWTService) IsTokenBlacklisted(token *JWTCustomClaims) bool {
// JWTAuthMiddleware provides JWT authentication middleware
func (s *JWTService) JWTAuthMiddleware(r *ghttp.Request) {
// Skip authentication for login and refresh token endpoints
- if r.URL.Path == "/api/login" || r.URL.Path == "/api/refresh-token" || r.URL.Path == "/api/unsubscribe/user_group" || r.URL.Path == "/api/get_validate_code" || r.URL.Path == "/api/unsubscribe" || r.URL.Path == "/api/languages/set" || r.URL.Path == "/api/languages/get" || r.URL.Path == "/api/batch_mail/api/send" {
+ if r.URL.Path == "/api/login" ||
+ r.URL.Path == "/api/refresh-token" ||
+ r.URL.Path == "/api/unsubscribe/user_group" ||
+ r.URL.Path == "/api/get_validate_code" ||
+ r.URL.Path == "/api/unsubscribe" ||
+ r.URL.Path == "/api/languages/set" ||
+ r.URL.Path == "/api/languages/get" ||
+ r.URL.Path == "/api/batch_mail/api/send" ||
+ r.URL.Path == "/api/batch_mail/api/batch_send" ||
+ r.URL.Path == "/api/subscribe/submit" ||
+ r.URL.Path == "/api/subscribe/confirm" {
r.Middleware.Next()
return
}
diff --git a/core/internal/service/timers/timers.go b/core/internal/service/timers/timers.go
index 0e743338..138f0ba9 100644
--- a/core/internal/service/timers/timers.go
+++ b/core/internal/service/timers/timers.go
@@ -9,6 +9,7 @@ import (
"billionmail-core/internal/service/mail_service"
"billionmail-core/internal/service/maillog_stat"
"billionmail-core/internal/service/relay"
+ "billionmail-core/internal/service/subscribe_list"
"billionmail-core/internal/service/warmup"
"context"
"github.com/gogf/gf/os/gtimer"
@@ -126,6 +127,11 @@ func Start(ctx context.Context) (err error) {
// fail2ban access logs detection
gtimer.AddOnce(800*time.Millisecond, fail2ban.NewAccessLogDetection().Start)
+ // {{ SubmitURL . }}
+ gtimer.AddOnce(500*time.Millisecond, func() {
+ subscribe_list.ReplaceSubmitUrl(ctx)
+ })
+
g.Log().Debug(ctx, "All timers started successfully")
return nil
}