How to integrate aws sdk ses in golang?

huangapple go评论105阅读模式
英文:

How to integrate aws sdk ses in golang?

问题

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

英文:

I'm using AWS to host my server in Go language. I am stuck as I'm not sure how to use their AWS SES SDK to send an email. Any ideas?

1: http://docs.aws.amazon.com/sdk-for-go/api/service/ses/#example_SES_SendEmail "AWS-SES-SDK"

答案1

得分: 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)

请注意,这只是一个示例代码,你需要根据自己的实际情况进行适当的修改。

英文:

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

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)

答案2

得分: 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中的会话,而是使用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 {
    // 记录错误
  }

  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 {
    // 记录错误
  }
}

注意:我认为这些SDK中需要aws.String()对象的需求是亚马逊Web服务团队软件设计不佳的结果。设计中应该使用原始字符串"",因为(a)原始字符串更容易让开发人员使用(不需要指针*和解引用&),(b)原始字符串使用堆栈分配,比使用堆分配的字符串对象性能更高。

英文:

The internet is littered with outdated SES examples for golang. 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.

It's 2022! And this is how you implement SES.


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

The AWS GO SES SDK is also on version 2
https://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.

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. This can be done multiple ways (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.

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.

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. 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.

答案3

得分: 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 (
    // 将 sender@example.com 替换为您的发件人地址。
    // 此地址必须在 Amazon SES 中进行验证。
    Sender = "sender@example.com"
    
    // 将 recipient@example.com 替换为您的收件人地址。
    // 如果您的账户仍处于沙箱状态,则此地址必须进行验证。
    Recipient = "recipient@example.com"

    // 指定一个配置集。如果您不想使用配置集,请注释掉以下常量以及下面的 ConfigurationSetName: aws.String(ConfigurationSet) 参数
    ConfigurationSet = "ConfigSet"
    
    // 将 us-west-2 替换为您在 Amazon SES 中使用的 AWS 区域。
    AwsRegion = "us-west-2"
    
    // 邮件的主题行。
    Subject = "Amazon SES Test (AWS SDK for Go)"
    
    // 邮件的 HTML 正文。
    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>"
    
    // 针对非 HTML 邮件客户端的收件人的邮件正文。
    TextBody = "This email was sent with Amazon SES using the AWS SDK for Go."
    
    // 邮件的字符编码。
    CharSet = "UTF-8"
)

func main() {
    
    // 创建一个新的会话并指定 AWS 区域。
    sess, err := session.NewSession(&aws.Config{
        Region:aws.String(AwsRegion)},
    )
    
    // 在会话中创建一个 SES 客户端。
    svc := ses.New(sess)
    
    // 组装邮件。
    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),
            // 如果您不使用配置集,请注释或删除以下行
            ConfigurationSetName: aws.String(ConfigurationSet),
    }

    // 尝试发送邮件。
    result, err := svc.SendEmail(input)
    
    // 如果发生错误,则显示错误消息。
    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 {
            // 打印错误,将 err 转换为 awserr.Error 以获取错误的 Code 和 Message。
            fmt.Println(err.Error())
        }
        return
    }
    
    fmt.Println("Email Sent!")
    fmt.Println(result)
}

以上是一个使用 AWS SDK for Go 发送邮件的示例代码。

英文:

Refer here for a well-documented example : https://docs.aws.amazon.com/ses/latest/DeveloperGuide/examples-send-using-sdk.html

package main
import (
&quot;fmt&quot;
//go get -u github.com/aws/aws-sdk-go
&quot;github.com/aws/aws-sdk-go/aws&quot;
&quot;github.com/aws/aws-sdk-go/aws/session&quot;
&quot;github.com/aws/aws-sdk-go/service/ses&quot;
&quot;github.com/aws/aws-sdk-go/aws/awserr&quot;
)
const (
// Replace sender@example.com with your &quot;From&quot; address. 
// This address must be verified with Amazon SES.
Sender = &quot;sender@example.com&quot;
// Replace recipient@example.com with a &quot;To&quot; address. If your account 
// is still in the sandbox, this address must be verified.
Recipient = &quot;recipient@example.com&quot;
// 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 = &quot;ConfigSet&quot;
// Replace us-west-2 with the AWS Region you&#39;re using for Amazon SES.
AwsRegion = &quot;us-west-2&quot;
// The subject line for the email.
Subject = &quot;Amazon SES Test (AWS SDK for Go)&quot;
// The HTML body for the email.
HtmlBody =  &quot;&lt;h1&gt;Amazon SES Test Email (AWS SDK for Go)&lt;/h1&gt;&lt;p&gt;This email was sent with &quot; +
&quot;&lt;a href=&#39;https://aws.amazon.com/ses/&#39;&gt;Amazon SES&lt;/a&gt; using the &quot; +
&quot;&lt;a href=&#39;https://aws.amazon.com/sdk-for-go/&#39;&gt;AWS SDK for Go&lt;/a&gt;.&lt;/p&gt;&quot;
//The email body for recipients with non-HTML email clients.
TextBody = &quot;This email was sent with Amazon SES using the AWS SDK for Go.&quot;
// The character encoding for the email.
CharSet = &quot;UTF-8&quot;
)
func main() {
// Create a new session and specify an AWS Region.
sess, err := session.NewSession(&amp;aws.Config{
Region:aws.String(AwsRegion)},
)
// Create an SES client in the session.
svc := ses.New(sess)
// Assemble the email.
input := &amp;ses.SendEmailInput{
Destination: &amp;ses.Destination{
CcAddresses: []*string{
},
ToAddresses: []*string{
aws.String(Recipient),
},
},
Message: &amp;ses.Message{
Body: &amp;ses.Body{
Html: &amp;ses.Content{
Charset: aws.String(CharSet),
Data:    aws.String(HtmlBody),
},
Text: &amp;ses.Content{
Charset: aws.String(CharSet),
Data:    aws.String(TextBody),
},
},
Subject: &amp;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(&quot;Email Sent!&quot;)
fmt.Println(result)
}

答案4

得分: 0

以下是使用Amazon SES v2 SDK发送原始电子邮件的示例代码:

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() {
	// 加载共享的AWS配置(~/.aws/config)
	cfg, err := config.LoadDefaultConfig(context.TODO())
	if err != nil {
		log.Fatal(err)
	}

	client := ses.NewFromConfig(cfg)
	// 读取任何EML文件
	eml, err := os.ReadFile("./example.eml")
	if err != nil {
		log.Fatal("错误:", 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("错误:", err)
		return
	}
	log.Println("发送成功,消息ID:", output.MessageId)
}

在开始发送和接收电子邮件之前,需要满足一些先决条件。请按照此链接进行操作。

英文:

Here is an example of sending raw email using Amazon SES v2 SDK

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 (
&quot;context&quot;
&quot;log&quot;
&quot;os&quot;
&quot;github.com/aws/aws-sdk-go-v2/aws&quot;
&quot;github.com/aws/aws-sdk-go-v2/config&quot;
&quot;github.com/aws/aws-sdk-go-v2/service/ses&quot;
&quot;github.com/aws/aws-sdk-go-v2/service/ses/types&quot;
)
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(&quot;./example.eml&quot;)
if err != nil {
log.Fatal(&quot;Error: &quot;, err)
}
param := &amp;ses.SendRawEmailInput{
RawMessage: &amp;types.RawMessage{
Data: eml,
},
Destinations: []string{
(&quot;pqr@outlook.com&quot;),
},
Source: aws.String(&quot;abc@test.com&quot;),
}
output, err := client.SendRawEmail(context.Background(), param)
if err != nil {
log.Println(&quot;Error: &quot;, err)
return
}
log.Println(&quot;Sending successful, message ID: &quot;, output.MessageId)
}

huangapple
  • 本文由 发表于 2016年12月16日 10:09:54
  • 转载请务必保留本文链接:https://go.coder-hub.com/41176256.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定