git.sr.ht/~pingoo/stdx@v0.0.0-20240218134121-094174641f6e/email/scaleway/scaleway.go (about) 1 package scaleway 2 3 import ( 4 "context" 5 "fmt" 6 "net/http" 7 8 "git.sr.ht/~pingoo/stdx/email" 9 scwemail "github.com/scaleway/scaleway-sdk-go/api/tem/v1alpha1" 10 "github.com/scaleway/scaleway-sdk-go/scw" 11 ) 12 13 // Mailer implements the `email.Mailer` interface to send emails using scaleway's API 14 // https://developers.scaleway.com/en/products/transactional_email/api 15 // https://www.scaleway.com/en/docs/managed-services/transactional-email 16 type Mailer struct { 17 scalewayClient *scwemail.API 18 } 19 20 type Config struct { 21 AccessKeyID string 22 SecretKey string 23 Region string 24 ProjectID string 25 HttpClient *http.Client 26 } 27 28 // NewMailer returns a new smtp Mailer 29 func NewMailer(config Config) (mailer *Mailer, err error) { 30 scwClientOptions := []scw.ClientOption{ 31 scw.WithAuth(config.AccessKeyID, config.SecretKey), 32 scw.WithDefaultRegion(scw.Region(config.Region)), 33 scw.WithDefaultProjectID(config.ProjectID), 34 } 35 if config.HttpClient != nil { 36 scwClientOptions = append(scwClientOptions, scw.WithHTTPClient(*&config.HttpClient)) 37 } 38 39 scwClient, err := scw.NewClient(scwClientOptions...) 40 if err != nil { 41 err = fmt.Errorf("scaleway.NewMailer: creating client: %w", err) 42 return 43 } 44 45 scalewayApi := scwemail.NewAPI(scwClient) 46 47 mailer = &Mailer{ 48 scalewayClient: scalewayApi, 49 } 50 51 return 52 } 53 54 func (mailer *Mailer) SendTransactionnal(ctx context.Context, email email.Email) error { 55 // replyTo := "" 56 // if len(email.ReplyTo) == 1 { 57 // replyTo = email.ReplyTo[0].String() 58 // } 59 input := &scwemail.CreateEmailRequest{ 60 // Region: "", 61 From: &scwemail.CreateEmailRequestAddress{Email: email.From.Address, Name: &email.From.Name}, 62 To: []*scwemail.CreateEmailRequestAddress{ 63 {Email: email.To[0].Address, Name: &email.To[0].Name}, 64 }, 65 // Cc: []*scwemail.CreateEmailRequestAddress{}, 66 // Bcc: []*scwemail.CreateEmailRequestAddress{}, 67 Subject: email.Subject, 68 Text: string(email.Text), 69 HTML: string(email.HTML), 70 // ProjectID: "", 71 // Attachments: []*scwemail.CreateEmailRequestAttachment{}, 72 // SendBefore: &time.Time{}, 73 } 74 75 _, err := mailer.scalewayClient.CreateEmail(input) 76 77 return err 78 } 79 80 func (mailer *Mailer) SendBroadcast(ctx context.Context, email email.Email) error { 81 return mailer.SendTransactionnal(ctx, email) 82 }