-
-
Save letsjustfixit/5d2269cb07126eceac97f7b85e5c6b46 to your computer and use it in GitHub Desktop.
Building an email in Golang to be delivered using Amazon SES
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
func buildEmailInput(source, destination, subject, message string, | |
csvFile []byte) (*ses.SendRawEmailInput, error) { | |
buf := new(bytes.Buffer) | |
writer := multipart.NewWriter(buf) | |
// email main header: | |
h := make(textproto.MIMEHeader) | |
h.Set("From", source) | |
h.Set("To", destination) | |
h.Set("Return-Path", source) | |
h.Set("Subject", subject) | |
h.Set("Content-Language", "en-US") | |
h.Set("Content-Type", "multipart/mixed; boundary=\""+writer.Boundary()+"\"") | |
h.Set("MIME-Version", "1.0") | |
_, err := writer.CreatePart(h) | |
if err != nil { | |
return nil, err | |
} | |
// body: | |
h = make(textproto.MIMEHeader) | |
h.Set("Content-Transfer-Encoding", "7bit") | |
h.Set("Content-Type", "text/plain; charset=us-ascii") | |
part, err := writer.CreatePart(h) | |
if err != nil { | |
return nil, err | |
} | |
_, err = part.Write([]byte(message)) | |
if err != nil { | |
return nil, err | |
} | |
// file attachment: | |
fn := attachmentFilename | |
h = make(textproto.MIMEHeader) | |
h.Set("Content-Disposition", "attachment; filename="+fn) | |
h.Set("Content-Type", "text/csv; x-unix-mode=0644; name=\""+fn+"\"") | |
h.Set("Content-Transfer-Encoding", "7bit") | |
part, err = writer.CreatePart(h) | |
if err != nil { | |
return nil, err | |
} | |
_, err = part.Write(csvFile) | |
if err != nil { | |
return nil, err | |
} | |
err = writer.Close() | |
if err != nil { | |
return nil, err | |
} | |
// Strip boundary line before header (doesn't work with it present) | |
s := buf.String() | |
if strings.Count(s, "\n") < 2 { | |
return nil, fmt.Errorf("invalid e-mail content") | |
} | |
s = strings.SplitN(s, "\n", 2)[1] | |
raw := ses.RawMessage{ | |
Data: []byte(s), | |
} | |
input := &ses.SendRawEmailInput{ | |
Destinations: []*string{aws.String(destination)}, | |
Source: aws.String(source), | |
RawMessage: &raw, | |
} | |
return input, nil | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Hey can you help me. I am unable to send email with attachment other than csv files.