fusenapi/server/auth/internal/logic/email_manager.go

178 lines
4.2 KiB
Go
Raw Normal View History

2023-07-24 09:22:06 +00:00
package logic
import (
"bytes"
"log"
"net/smtp"
"sync"
"text/template"
"time"
)
var EmailManager *EmailSender
2023-07-27 08:48:43 +00:00
type EmailFormat struct {
TargetEmail string // 发送的目标email
CompanyName string // fs公司名
ConfirmationLink string // fs确认连接
SenderName string // 发送人
SenderTitle string // 发送标题
}
2023-07-24 09:22:06 +00:00
// EmailSender
type EmailSender struct {
lock sync.Mutex
2023-07-27 08:48:43 +00:00
EmailTasks chan *EmailFormat
2023-07-24 11:43:56 +00:00
Auth smtp.Auth
FromEmail string
ResendTimeLimit time.Duration
2023-07-27 08:48:43 +00:00
emailSending map[string]*EmailTask
semaphore chan struct{}
2023-07-24 09:22:06 +00:00
}
// EmailTask
type EmailTask struct {
2023-07-27 08:48:43 +00:00
Email *EmailFormat // email
SendTime time.Time // 处理的任务时间
2023-07-24 09:22:06 +00:00
}
func (m *EmailSender) ProcessEmailTasks() {
for {
2023-07-27 08:48:43 +00:00
emailformat, ok := <-m.EmailTasks
2023-07-24 09:22:06 +00:00
if !ok {
log.Println("Email task channel closed")
break
}
m.lock.Lock()
2023-07-27 08:48:43 +00:00
_, isSending := m.emailSending[emailformat.TargetEmail]
2023-07-24 09:22:06 +00:00
if isSending {
m.lock.Unlock()
continue
}
2023-07-27 08:48:43 +00:00
m.emailSending[emailformat.TargetEmail] = &EmailTask{
Email: emailformat,
2023-08-24 10:28:01 +00:00
SendTime: time.Now().UTC(),
2023-07-24 09:22:06 +00:00
}
m.lock.Unlock()
2023-07-24 11:43:56 +00:00
// Acquire a token
m.semaphore <- struct{}{}
go func() {
defer func() { <-m.semaphore }() // Release a token
2023-07-27 08:48:43 +00:00
content := RenderEmailTemplate(emailformat.CompanyName, emailformat.ConfirmationLink, emailformat.SenderName, emailformat.SenderTitle)
err := smtp.SendMail("smtp.gmail.com:587", m.Auth, m.FromEmail, []string{emailformat.TargetEmail}, content)
2023-07-24 11:43:56 +00:00
if err != nil {
2023-07-27 08:48:43 +00:00
log.Printf("Failed to send email to %s: %v\n", emailformat, err)
m.Resend(emailformat.TargetEmail, content)
2023-07-24 11:43:56 +00:00
}
}()
2023-07-24 09:22:06 +00:00
}
}
// Resend 重发邮件
func (m *EmailSender) Resend(emailTarget string, content []byte) {
time.Sleep(m.ResendTimeLimit)
m.lock.Lock()
defer m.lock.Unlock()
// Check if the email task still exists and has not been sent successfully
2023-08-24 10:28:01 +00:00
if task, ok := m.emailSending[emailTarget]; ok && task.SendTime.Add(m.ResendTimeLimit).After(time.Now().UTC()) {
2023-07-24 09:22:06 +00:00
err := smtp.SendMail(emailTarget, m.Auth, m.FromEmail, []string{emailTarget}, content)
if err != nil {
log.Printf("Failed to resend email to %s: %v\n", emailTarget, err)
} else {
delete(m.emailSending, emailTarget)
}
}
}
// ClearExpiredTasks 清除过期的邮件任务
func (m *EmailSender) ClearExpiredTasks() {
ticker := time.NewTicker(time.Minute)
defer ticker.Stop()
for {
<-ticker.C
m.lock.Lock()
for email, task := range m.emailSending {
2023-08-24 10:28:01 +00:00
if task.SendTime.Add(m.ResendTimeLimit).Before(time.Now().UTC()) {
2023-07-24 09:22:06 +00:00
delete(m.emailSending, email)
}
}
m.lock.Unlock()
}
}
func init() {
// Initialize the email manager
EmailManager = &EmailSender{
2023-07-27 08:48:43 +00:00
EmailTasks: make(chan *EmailFormat, 10),
2023-07-24 09:22:06 +00:00
Auth: smtp.PlainAuth(
"",
2023-08-10 08:25:41 +00:00
"support@fusenpack.com",
2023-08-29 02:21:50 +00:00
"wfbjpdgvaozjvwah",
2023-07-24 09:22:06 +00:00
"smtp.gmail.com",
),
2023-08-10 08:25:41 +00:00
FromEmail: "support@fusenpack.com",
2023-07-24 09:22:06 +00:00
emailSending: make(map[string]*EmailTask, 10),
ResendTimeLimit: time.Minute * 1,
2023-07-24 11:43:56 +00:00
semaphore: make(chan struct{}, 10), // Initialize semaphore with a capacity of 10
2023-07-24 09:22:06 +00:00
}
// Start processing email tasks
go EmailManager.ProcessEmailTasks()
// Start clearing expired tasks
go EmailManager.ClearExpiredTasks()
}
const emailTemplate = `Subject: Your {{.CompanyName}} Account Confirmation
Dear
Thank you for creating an account with {{.CompanyName}}. We're excited to have you on board!
Before we get started, we just need to confirm that this is the right email address. Please confirm your email address by clicking on the link below:
{{.ConfirmationLink}}
Once you've confirmed, you can get started with {{.CompanyName}}. If you have any questions, feel free to reply to this email. We're here to help!
If you did not create an account with us, please ignore this email.
Thanks,
{{.SenderName}}
{{.SenderTitle}}
{{.CompanyName}}
`
2023-07-24 11:43:56 +00:00
func RenderEmailTemplate(companyName, confirmationLink, senderName, senderTitle string) []byte {
2023-07-24 09:22:06 +00:00
tmpl, err := template.New("email").Parse(emailTemplate)
if err != nil {
log.Fatal(err)
}
data := map[string]string{
"CompanyName": companyName,
"ConfirmationLink": confirmationLink,
"SenderName": senderName,
"SenderTitle": senderTitle,
}
var result bytes.Buffer
err = tmpl.Execute(&result, data)
if err != nil {
log.Fatal(err)
}
2023-07-24 11:43:56 +00:00
return result.Bytes()
2023-07-24 09:22:06 +00:00
}