如何在Golang中集成AWS SDK SES?

3

我正在使用AWS托管我的Go语言服务器。 我卡住了,因为我不确定如何使用他们的 AWS SES SDK 发送电子邮件。 有什么想法吗?


请参考以下链接:https://dev59.com/hKLia4cB1Zd3GeqPoMX5#44670306 - a4DEVP
4个回答

18

根据您提供的链接,这非常简单。

您遇到了什么问题?

最小示例:

导入: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)

API是否已更改?当我尝试从我的本地主机运行此代码时,出现错误MissingEndpoint:此服务需要“Endpoint”配置 - Babr
@Babar - 我认为这种用法已经过时了 - 现在有golang AWS SDK 2 (https://github.com/aws/aws-sdk-go-v2)和SESV2 (https://github.com/aws/aws-sdk-go-v2/tree/main/service/sesv2)。 - tim-montague

4

互联网上充斥着过时的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中的Sessions不再使用,已被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()对象,是亚马逊网络服务团队软件设计不佳的结果。应该使用原始字符串""来代替;因为(a)原始字符串对于开发人员更易于使用(不需要指针*和解除引用&),(b)原始字符串使用堆栈分配,比使用堆栈分配的字符串对象具有更高的性能。

1

请参考这里的文档示例:https://docs.aws.amazon.com/ses/latest/DeveloperGuide/examples-send-using-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)
}

1
这不太好,因为它没有展示/解释如何包含凭据,你需要进一步寻找那部分内容。 - JorgeGarza

0

这是使用Amazon SES v2 SDK发送原始电子邮件的示例

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

注意:在开始发送和接收电子邮件之前,您需要满足一些先决条件。请参照this
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)
}


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接