简体   繁体   English

如何在golang中集成aws sdk ses?

[英]How to integrate aws sdk ses in golang?

I'm using AWS to host my server in Go language.我正在使用 AWS 以 Go 语言托管我的服务器。 I am stuck as I'm not sure how to use their AWS SES SDK to send an email.我被卡住了,因为我不确定如何使用他们的AWS SES SDK发送 email。 Any ideas?有任何想法吗?

It is pretty straightforward as shown in the link from your question.如您问题的链接所示,这非常简单。

What are you having trouble with ?你有什么问题?

Minimal Example :最小的例子:

Imports : github.com/aws/aws-sdk-go/aws , github.com/aws/aws-sdk-go/service/ses and github.com/aws/aws-sdk-go/aws/credentials , github.com/aws/aws-sdk-go/aws/session导入: github.com/aws/aws-sdk-go/aws github.com/aws/aws-sdk-go/aws/credentials github.com/aws/aws-sdk-go/service/ses github.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)

Refer here for a well-documented example : https://docs.aws.amazon.com/ses/latest/DeveloperGuide/examples-send-using-sdk.html请参阅此处获取有据可查的示例: 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)
}

The internet is littered with outdated SES examples for golang.互联网上充斥着过时的 golang SES 示例。 Even Amazon's own code examples are outdated ( https://docs.aws.amazon.com/sdk-for-go/v1/developer-guide/ses-example-send-email.html ), and that leads developers towards the use of older documentation.甚至亚马逊自己的代码示例也已过时( https://docs.aws.amazon.com/sdk-for-go/v1/developer-guide/ses-example-send-email.html ),这导致开发人员使用较旧的文档。

It's 2022!现在是 2022 年! And this is how you implement SES.这就是您实施 SES 的方式。


The AWS GO SDK is on version 2 AWS GO SDK 是版本 2
https://github.com/aws/aws-sdk-go-v2 https://github.com/aws/aws-sdk-go-v2

The AWS GO SES SDK is also on version 2 AWS GO SES SDK 也在版本 2
https://github.com/aws/aws-sdk-go-v2/tree/main/service/sesv2https://github.com/aws/aws-sdk-go-v2/tree/main/service/sesv2

So we'll start by importing these packages.所以我们将从导入这些包开始。 Note: Sessions from AWS GO SDK version 1 are no longer used, and have been replaced with Config.注意:不再使用来自 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"
)

Next you'll need to setup your Amazon service key, and service secret key.接下来,您需要设置您的 Amazon 服务密钥和服务密钥。 This can be done multiple ways ( https://aws.github.io/aws-sdk-go-v2/docs/configuring-sdk/ ).这可以通过多种方式完成( https://aws.github.io/aws-sdk-go-v2/docs/configuring-sdk/ )。 The recommended practice from Go documentation is to initialize within an init function ( https://go.dev/doc/effective_go#init ), so that's where I setup credentials. 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)
}

The final step, is to use the configured service to send an email from main or another function.最后一步,是使用配置的服务从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
  }
}

Note: I consider the need for aws.String() objects in these SDKs, the result of poor software design on the part of the Amazon Web Services team.注意:我认为这些 SDK 中需要aws.String()对象,这是亚马逊网络服务团队软件设计不佳的结果。 Primitive strings "" should be used in the design instead;应该在设计中使用原始字符串"" because (a) it's easier for developers to work with primitives (no need for pointers * and de-referencing & ), and (b) primitives use stack allocation, and have higher performance than string objects which use heap allocation.因为 (a) 开发人员使用原语更容易(不需要指针*和取消引用& ),并且 (b) 原语使用堆栈分配,并且比使用堆分配的字符串对象具有更高的性能。

Here is an example of sending raw email using Amazon SES v2 SDK这是使用 Amazon SES v2 SDK 发送原始 email 的示例

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

Note: There are some prerequisites before you can start sending and receiving emails.注意:在您开始发送和接收电子邮件之前,有一些先决条件。 Follow 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)
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM