Spaces:
Configuration error
Configuration error
| package mail | |
| import ( | |
| "errors" | |
| "fmt" | |
| "github.com/jordan-wright/email" | |
| "net/mail" | |
| "net/smtp" | |
| ) | |
| var ( | |
| ErrEmailEmpty = errors.New("mail is empty") | |
| ErrEmailInvalid = errors.New("invalid email") | |
| ) | |
| // Config menyimpan pengaturan untuk koneksi SMTP. | |
| type Config struct { | |
| Host string | |
| Port string | |
| Username string | |
| Password string | |
| From string | |
| } | |
| // SMTP adalah implementasi Sender untuk mengirim mail melalui SMTP | |
| type SMTP struct { | |
| name string | |
| fromEmailAddress string | |
| smtpServerAddress string | |
| smtpAuthAddress smtp.Auth | |
| } | |
| // New membuat instance baru SMTP dengan konfigurasi. | |
| func New(cfg *Config) (Sender, error) { | |
| if err := validateEmail(cfg.From); err != nil { | |
| return nil, fmt.Errorf("invalid from address: %w", err) | |
| } | |
| return &SMTP{ | |
| name: cfg.From, | |
| fromEmailAddress: cfg.From, | |
| smtpServerAddress: fmt.Sprintf("%s:%s", cfg.Host, cfg.Port), | |
| smtpAuthAddress: smtp.PlainAuth("", cfg.Username, cfg.Password, cfg.Host), | |
| }, nil | |
| } | |
| // Send mengirim mail ke penerima dengan subjek, konten HTML, dan data lainnya. | |
| func (s *SMTP) Send(recipient, subject string, htmlContent string, data any) error { | |
| e := email.NewEmail() | |
| e.From = s.fromEmailAddress | |
| e.To = []string{recipient} | |
| e.Subject = subject | |
| e.HTML = []byte(htmlContent) | |
| return s.sendEmail(e) | |
| } | |
| func (s *SMTP) sendEmail(e *email.Email) error { | |
| return e.Send(s.smtpServerAddress, s.smtpAuthAddress) | |
| } | |
| func validateEmail(email string) error { | |
| if email == "" { | |
| return ErrEmailEmpty | |
| } | |
| if _, err := mail.ParseAddress(email); err != nil { | |
| return ErrEmailInvalid | |
| } | |
| return nil | |
| } | |