44 lines
808 B
Go
44 lines
808 B
Go
|
package mgmailer
|
||
|
|
||
|
import (
|
||
|
"context"
|
||
|
"fmt"
|
||
|
"sync/atomic"
|
||
|
"time"
|
||
|
|
||
|
"github.com/mailgun/mailgun-go/v4"
|
||
|
)
|
||
|
|
||
|
type Config struct {
|
||
|
MailgunDomain string
|
||
|
MailgunAPIKey string
|
||
|
SenderEmail string
|
||
|
SenderName string
|
||
|
}
|
||
|
|
||
|
type Mailer struct {
|
||
|
conf atomic.Pointer[Config]
|
||
|
mg atomic.Pointer[mailgun.MailgunImpl]
|
||
|
}
|
||
|
|
||
|
func (m *Mailer) Update(conf Config) {
|
||
|
m.conf.Store(&conf)
|
||
|
m.mg.Store(mailgun.NewMailgun(conf.MailgunDomain, conf.MailgunAPIKey))
|
||
|
}
|
||
|
|
||
|
func (m *Mailer) Send(subject, body, to string) error {
|
||
|
mg := m.mg.Load()
|
||
|
conf := m.conf.Load()
|
||
|
message := mailgun.NewMessage(
|
||
|
fmt.Sprintf("%s <%s>", conf.SenderName, conf.SenderEmail),
|
||
|
subject,
|
||
|
body,
|
||
|
to)
|
||
|
|
||
|
ctx, cancel := context.WithTimeout(context.Background(), time.Second*10)
|
||
|
defer cancel()
|
||
|
|
||
|
_, _, err := mg.Send(ctx, message)
|
||
|
return err
|
||
|
}
|