Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to implement aws ses SendRawEmail with attachment in golang

I need to implement Amazon ses SendRawEmail with attachment in golang,
i tried with the following code :

session, err := session.NewSession()
svc := ses.New(session, &aws.Config{Region: aws.String("us-west-2")})

source := aws.String("XXX <[email protected]>")
destinations := []*string{aws.String("xxx <[email protected]>")}
message := ses.RawMessage{ Data: []byte(` From: xxx <[email protected]>\\nTo: xxx  <[email protected]>\\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)

but in the mail I receive, it shows the content which I have given in the message, instead of the attachment. Not sure what exactly is wrong???

like image 375
a4DEVP Avatar asked Jun 21 '17 07:06

a4DEVP


2 Answers

Refer to AWS example for Sending RAW email with attachment.

Implementation Suggestion: for an easy to compose email and get email as bytes and send it to SES as mentioned in the above reference example.

Use library gopkg.in/gomail.v2 to compose your email message with attachment and then call WriteTo method.

var emailRaw bytes.Buffer
emailMessage.WriteTo(&emailRaw)

// while create instance of RawMessage
RawMessage: &ses.RawMessage{
    Data: emailRaw.Bytes(),
}

Good luck!


EDIT: For the comment.

Compose the email-

msg := gomail.NewMessage()
msg.SetHeader("From", "[email protected]")
msg.SetHeader("To", "[email protected]", "[email protected]")
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.
like image 56
jeevatkm Avatar answered Oct 19 '22 11:10

jeevatkm


if you're trying to attach a file from bytes:

msg.Attach("report.pdf", gomail.SetCopyFunc(func(w io.Writer) error {
    _, err := w.Write(reportData)
    return err
}))
like image 2
Sebastian Avatar answered Oct 19 '22 13:10

Sebastian