如何在 golang 中实现带有附件的 aws ses SendRawEmail



我需要在golang中实现带有附件的Amazon ses SendRawEmail,
我尝试使用以下代码:

session, err := session.NewSession()
svc := ses.New(session, &aws.Config{Region: aws.String("us-west-2")})
source := aws.String("XXX <xxx@xxx.com>")
destinations := []*string{aws.String("xxx <xxx@xxx.com>")}
message := ses.RawMessage{ Data: []byte(` From: xxx <xxx@xxx.com>\nTo: xxx  <xxx@xxx.com>\nSubject: Test email (contains an attachment)\nMIME-Version: 1.0\nContent-type: Multipart/Mixed; boundary="NextPart"\n\n--NextPart\nContent-Type: text/plain\n\nThis is the message body.\n\n--NextPart\nContent-Type: text/plain;\nContent-Disposition: attachment; filename="sample.txt"\n\nThis is the text in the attachment.\n\n--NextPart--" `)}
input := ses.SendRawEmailInput{Source: source, Destinations: destinations, RawMessage: &message}
output, err := svc.SendRawEmail(&input)

但在我收到的邮件中,它显示了我在邮件中提供的内容,而不是附件。不知道到底出了什么问题???

请参阅 AWS 示例,了解如何发送带有附件的 RAW 电子邮件。

实现建议:为了便于撰写电子邮件,并以字节形式获取电子邮件并将其发送到SES,如上述参考示例中所述。

使用库gopkg.in/gomail.v2撰写带有附件的电子邮件,然后调用 WriteTo 方法。

var emailRaw bytes.Buffer
emailMessage.WriteTo(&emailRaw)
// while create instance of RawMessage
RawMessage: &ses.RawMessage{
    Data: emailRaw.Bytes(),
}

祝你好运!


编辑:对于评论。

撰写电子邮件-

msg := gomail.NewMessage()
msg.SetHeader("From", "alex@example.com")
msg.SetHeader("To", "bob@example.com", "cora@example.com")
msg.SetHeader("Subject", "Hello!")
msg.SetBody("text/html", "Hello <b>Bob</b> and <i>Cora</i>!")
msg.Attach("/home/Alex/lolcat.jpg")
var emailRaw bytes.Buffer
msg.WriteTo(&emailRaw)
message := ses.RawMessage{ Data: emailRaw.Bytes() }
// Remaining is same as what you mentioned the question.

如果您尝试从字节附加文件:

msg.Attach("report.pdf", gomail.SetCopyFunc(func(w io.Writer) error {
    _, err := w.Write(reportData)
    return err
}))

最新更新