如何在Golang中集成AWS SDK SES



我正在使用AWS用GO语言托管服务器。我不确定如何使用他们的AWS SES SDK发送电子邮件。有任何想法吗?

它非常简单,如您的问题的链接所示。

您遇到什么麻烦?

最小示例:

导入:github.com/aws/aws-sdk-go/awsgithub.com/aws/aws-sdk-go/service/sesgithub.com/aws/aws-sdk-go/aws/credentialsgithub.com/aws/aws-sdk-go/aws/session

awsSession := session.New(&aws.Config{
        Region:      aws.String("aws.region"),
        Credentials: credentials.NewStaticCredentials("aws.accessKeyID", "aws.secretAccessKey" , ""),
    })
sesSession := ses.New(awsSession)
sesEmailInput := &ses.SendEmailInput{
    Destination: &ses.Destination{
        ToAddresses:  []*string{aws.String("receiver@xyz.com")},
    },
    Message: &ses.Message{
        Body: &ses.Body{
            Html: &ses.Content{
                Data: aws.String("Body HTML")},
        },
        Subject: &ses.Content{
            Data: aws.String("Subject"),
        },
    },
    Source: aws.String("sender@xyz.com"),
    ReplyToAddresses: []*string{
        aws.String("sender@xyz.com"),
    },
}
_, err := sesSession.SendEmail(sesEmailInput)

互联网上散布着Golang过时的SES示例。甚至亚马逊自己的代码示例也已过时(https://docs.aws.amazon.com/sdk-for-go/v1/developer-guide/ses-example-send-email.html),这使开发人员朝着使用旧文档。

是2022!这就是您实现SES的方式。


AWS GO SDK在版本2上
https://github.com/aws/aws-sdk-go-v2

AWS GO SES SDK也在版本2上
https://github.com/aws/aws-sdk-go-v2/tree/main/service/sesv2

因此,我们将从导入这些软件包开始。注意: AWS GO SDK版本1的会话不再使用,并且已替换为Config。

package main
import (
  "github.com/aws/aws-sdk-go-v2/config"
  "github.com/aws/aws-sdk-go-v2/credentials"
  "github.com/aws/aws-sdk-go-v2/service/sesv2"
)

接下来,您需要设置Amazon服务密钥和服务秘密密钥。这可以多种方式(https://aws.github.io/aws-sdk-go-v2/docs/configuring-sdk/)。GO文档的推荐练习是在init函数(https://go.dev/doc/effective_go#init)中初始化,所以这是我设置凭据的地方。

var mailClient *sesv2.Client
func init() {
  accessKey := os.Getenv("AWS_ACCESS_KEY")
  secretKey := os.Getenv("AWS_SECRET_KEY")
  region := os.Getenv("AWS_REGION")
  amazonConfiguration, createAmazonConfigurationError :=
    config.LoadDefaultConfig(
      context.Background(),
      config.WithRegion(region),
      config.WithCredentialsProvider(
        credentials.NewStaticCredentialsProvider(
          accessKey, secretKey, "",
        ),
      ),
    )
  if createAmazonConfigurationError != nil {
    // log error
  }
  mailClient = sesv2.NewFromConfig(amazonConfiguration)
}

最后一步是使用配置的服务发送main或其他功能的电子邮件。

func main() {
  mailFrom := "sender@example.com"
  // mailFrom := os.Getenv("MAIL_FROM")
  mailTo := "reciever@example.com"
  charset := aws.String("UTF-8")
  mail := &sesv2.SendEmailInput{
    FromEmailAddress: aws.String(mailTo),
    Destination: &types.Destination{
      ToAddresses: []string{ mailTo },
    },
    Content: &types.EmailContent{
      Simple: &types.Message{
        Subject: &types.Content{
          Charset: charset,
          Data: aws.String("subject"),
        },
        Body: &types.Body{
          Text: &types.Content{
            Charset: charset,
            Data: aws.String("body"),
          },
        },
      },
    },
  }
  _, createMailError := mailClient.sendMail(context.Background(), mail)
  if createMailError != nil {
    // log error
  }
}

注意:我考虑了这些SDK中aws.String()对象的需求,这是Amazon Web Services团队的软件设计差的结果。原始字符串""应该在设计中使用;因为(a)开发人员更容易使用原语(不需要指针*和DE-RETARCING &),并且(b)原始词使用堆栈分配,并且比使用堆分配的字符串对象具有更高的性能。

请参阅此处的文献良好的示例:https://docs.aws.amazon.com/ses/latest/developerguide/developerguide/examples-send-send-send-send-using-send-send-sdk.html

package main
import (
    "fmt"
    
    //go get -u github.com/aws/aws-sdk-go
    "github.com/aws/aws-sdk-go/aws"
    "github.com/aws/aws-sdk-go/aws/session"
    "github.com/aws/aws-sdk-go/service/ses"
    "github.com/aws/aws-sdk-go/aws/awserr"
)
const (
    // Replace sender@example.com with your "From" address. 
    // This address must be verified with Amazon SES.
    Sender = "sender@example.com"
    
    // Replace recipient@example.com with a "To" address. If your account 
    // is still in the sandbox, this address must be verified.
    Recipient = "recipient@example.com"
    // Specify a configuration set. If you do not want to use a configuration
    // set, comment out the following constant and the 
    // ConfigurationSetName: aws.String(ConfigurationSet) argument below
    ConfigurationSet = "ConfigSet"
    
    // Replace us-west-2 with the AWS Region you're using for Amazon SES.
    AwsRegion = "us-west-2"
    
    // The subject line for the email.
    Subject = "Amazon SES Test (AWS SDK for Go)"
    
    // The HTML body for the email.
    HtmlBody =  "<h1>Amazon SES Test Email (AWS SDK for Go)</h1><p>This email was sent with " +
                "<a href='https://aws.amazon.com/ses/'>Amazon SES</a> using the " +
                "<a href='https://aws.amazon.com/sdk-for-go/'>AWS SDK for Go</a>.</p>"
    
    //The email body for recipients with non-HTML email clients.
    TextBody = "This email was sent with Amazon SES using the AWS SDK for Go."
    
    // The character encoding for the email.
    CharSet = "UTF-8"
)
func main() {
    
    // Create a new session and specify an AWS Region.
    sess, err := session.NewSession(&aws.Config{
        Region:aws.String(AwsRegion)},
    )
    
    // Create an SES client in the session.
    svc := ses.New(sess)
    
    // Assemble the email.
    input := &ses.SendEmailInput{
        Destination: &ses.Destination{
            CcAddresses: []*string{
            },
            ToAddresses: []*string{
                aws.String(Recipient),
            },
        },
        Message: &ses.Message{
            Body: &ses.Body{
                Html: &ses.Content{
                    Charset: aws.String(CharSet),
                    Data:    aws.String(HtmlBody),
                },
                Text: &ses.Content{
                    Charset: aws.String(CharSet),
                    Data:    aws.String(TextBody),
                },
            },
            Subject: &ses.Content{
                Charset: aws.String(CharSet),
                Data:    aws.String(Subject),
            },
        },
        Source: aws.String(Sender),
            // Comment or remove the following line if you are not using a configuration set
            ConfigurationSetName: aws.String(ConfigurationSet),
    }
    // Attempt to send the email.
    result, err := svc.SendEmail(input)
    
    // Display error messages if they occur.
    if err != nil {
        if aerr, ok := err.(awserr.Error); ok {
            switch aerr.Code() {
            case ses.ErrCodeMessageRejected:
                fmt.Println(ses.ErrCodeMessageRejected, aerr.Error())
            case ses.ErrCodeMailFromDomainNotVerifiedException:
                fmt.Println(ses.ErrCodeMailFromDomainNotVerifiedException, aerr.Error())
            case ses.ErrCodeConfigurationSetDoesNotExistException:
                fmt.Println(ses.ErrCodeConfigurationSetDoesNotExistException, aerr.Error())
            default:
                fmt.Println(aerr.Error())
            }
        } else {
            // Print the error, cast err to awserr.Error to get the Code and
            // Message from an error.
            fmt.Println(err.Error())
        }
        return
    }
    
    fmt.Println("Email Sent!")
    fmt.Println(result)
}

这是使用Amazon SES V2 SDK

发送原始电子邮件的示例

https://github.com/aws/aws-sdk-go-v2

注意:有一些先决条件,然后才能开始发送和接收电子邮件。遵循此

package main
import (
    "context"
    "log"
    "os"
    "github.com/aws/aws-sdk-go-v2/aws"
    "github.com/aws/aws-sdk-go-v2/config"
    "github.com/aws/aws-sdk-go-v2/service/ses"
    "github.com/aws/aws-sdk-go-v2/service/ses/types"
)
func main() {
    // Load the shared AWS configuration (~/.aws/config)
    cfg, err := config.LoadDefaultConfig(context.TODO())
    if err != nil {
        log.Fatal(err)
    }
    client := ses.NewFromConfig(cfg)
    // Read any EML file
    eml, err := os.ReadFile("./example.eml")
    if err != nil {
        log.Fatal("Error: ", err)
    }
    param := &ses.SendRawEmailInput{
        RawMessage: &types.RawMessage{
            Data: eml,
        },
        Destinations: []string{
            ("pqr@outlook.com"),
        },
        Source: aws.String("abc@test.com"),
    }
    output, err := client.SendRawEmail(context.Background(), param)
    if err != nil {
        log.Println("Error: ", err)
        return
    }
    log.Println("Sending successful, message ID: ", output.MessageId)
}

最新更新