git.sr.ht/~pingoo/stdx@v0.0.0-20240218134121-094174641f6e/email/ses/ses.go (about)

     1  package ses
     2  
     3  import (
     4  	"context"
     5  	"net/http"
     6  
     7  	"git.sr.ht/~pingoo/stdx/email"
     8  	"github.com/aws/aws-sdk-go/aws"
     9  	"github.com/aws/aws-sdk-go/aws/credentials"
    10  	"github.com/aws/aws-sdk-go/aws/session"
    11  	"github.com/aws/aws-sdk-go/service/ses"
    12  )
    13  
    14  // Mailer implements the `email.Mailer` interface to send emails using SMTP
    15  type Mailer struct {
    16  	sesClient *ses.SES
    17  }
    18  
    19  type Config struct {
    20  	Region          string
    21  	AccessKeyID     string
    22  	SecretAccessKey string
    23  	HttpClient      *http.Client
    24  }
    25  
    26  // NewMailer returns a new smtp Mailer
    27  func NewMailer(config Config) (*Mailer, error) {
    28  	awsSession, err := session.NewSession(&aws.Config{
    29  		Region:      aws.String(config.Region),
    30  		Credentials: credentials.NewStaticCredentials(config.AccessKeyID, config.SecretAccessKey, ""),
    31  		HTTPClient:  config.HttpClient,
    32  	})
    33  	if err != nil {
    34  		return nil, err
    35  	}
    36  
    37  	// Create SES service client
    38  	sesClient := ses.New(awsSession)
    39  
    40  	return &Mailer{
    41  		sesClient,
    42  	}, nil
    43  }
    44  
    45  // Send an email using the SES mailer
    46  func (mailer *Mailer) SendTransactionnal(ctx context.Context, email email.Email) error {
    47  	rawEmail, err := email.Bytes()
    48  	if err != nil {
    49  		return err
    50  	}
    51  
    52  	_, err = mailer.sesClient.SendRawEmail(&ses.SendRawEmailInput{
    53  		RawMessage: &ses.RawMessage{
    54  			Data: rawEmail,
    55  		},
    56  	})
    57  
    58  	return err
    59  }
    60  
    61  // TODO
    62  func (mailer *Mailer) SendBroadcast(ctx context.Context, email email.Email) error {
    63  	rawEmail, err := email.Bytes()
    64  	if err != nil {
    65  		return err
    66  	}
    67  
    68  	_, err = mailer.sesClient.SendRawEmail(&ses.SendRawEmailInput{
    69  		RawMessage: &ses.RawMessage{
    70  			Data: rawEmail,
    71  		},
    72  	})
    73  
    74  	return err
    75  }