Files
backend/internal/service/email_service.go
lan 4d8f2ec997 Initial backend repository commit.
Set up project files and add .gitignore to exclude local build/runtime artifacts.

Made-with: Cursor
2026-03-09 21:28:58 +08:00

83 lines
1.9 KiB
Go

package service
import (
"context"
"fmt"
"strings"
emailpkg "carrot_bbs/internal/pkg/email"
)
// SendEmailRequest 发信请求
type SendEmailRequest struct {
To []string
Cc []string
Bcc []string
ReplyTo []string
Subject string
TextBody string
HTMLBody string
Attachments []string
}
type EmailService interface {
IsEnabled() bool
Send(ctx context.Context, req SendEmailRequest) error
SendText(ctx context.Context, to []string, subject, body string) error
SendHTML(ctx context.Context, to []string, subject, html string) error
}
type emailServiceImpl struct {
client emailpkg.Client
}
func NewEmailService(client emailpkg.Client) EmailService {
return &emailServiceImpl{client: client}
}
func (s *emailServiceImpl) IsEnabled() bool {
return s.client != nil && s.client.IsEnabled()
}
func (s *emailServiceImpl) Send(ctx context.Context, req SendEmailRequest) error {
if s.client == nil {
return fmt.Errorf("email client is nil")
}
if !s.client.IsEnabled() {
return fmt.Errorf("email service is disabled")
}
if len(req.To) == 0 {
return fmt.Errorf("email recipient is empty")
}
if strings.TrimSpace(req.Subject) == "" {
return fmt.Errorf("email subject is empty")
}
return s.client.Send(ctx, emailpkg.Message{
To: req.To,
Cc: req.Cc,
Bcc: req.Bcc,
ReplyTo: req.ReplyTo,
Subject: req.Subject,
TextBody: req.TextBody,
HTMLBody: req.HTMLBody,
Attachments: req.Attachments,
})
}
func (s *emailServiceImpl) SendText(ctx context.Context, to []string, subject, body string) error {
return s.Send(ctx, SendEmailRequest{
To: to,
Subject: subject,
TextBody: body,
})
}
func (s *emailServiceImpl) SendHTML(ctx context.Context, to []string, subject, html string) error {
return s.Send(ctx, SendEmailRequest{
To: to,
Subject: subject,
HTMLBody: html,
})
}