2 回答
TA贡献1786条经验 获得超13个赞
我不是 Go 的人,所以这只是一次粗暴的尝试,试图绕过代码行以产生有效的 MIME 结构。
func generateRawEmailContent(subject, to, from, HTMLBody string, attachments *[]EmailAttachment) []byte {
buf := bytes.NewBuffer(nil)
// Creating headers by gluing together strings is precarious.
// I'm sure there must be a better way.
buf.WriteString(fmt.Sprintf("Subject: %s\n", subject))
buf.WriteString(fmt.Sprintf("To: %s\n", to))
// Remove spurious newline
buf.WriteString(fmt.Sprintf("From: %s\n", from))
writer := multipart.NewWriter(buf)
boundary := writer.Boundary()
buf.WriteString(fmt.Sprintf("MIME-Version: 1.0\n", boundary))
buf.WriteString(fmt.Sprintf("Content-Type: multipart/mixed; boundary=%s\n", boundary))
// End of headers
buf.WriteString("\n")
buf.WriteString(fmt.Sprintf("--%s\n", boundary))
buf.WriteString("Content-Type: text/html; charset=\"UTF-8\";\n\n")
buf.WriteString(HTMLBody)
for _, attachment := range *attachments {
buf.WriteString(fmt.Sprintf("\n\n--%s\n", boundary))
buf.WriteString(fmt.Sprintf("Content-Type: %s\n", http.DetectContentType(attachment.Data)))
buf.WriteString("Content-Transfer-Encoding: base64\n")
buf.WriteString(fmt.Sprintf("Content-Disposition: attachment; filename=%s\n", attachment.FileName))
b := make([]byte, base64.StdEncoding.EncodedLen(len(attachment.Data)))
base64.StdEncoding.Encode(b, attachment.Data)
buf.Write(b)
// Don't add a second boundary here
buf.WriteString("\n")
}
// Final terminating boundary, notice -- after
buf.WriteString(fmt.Sprintf("\n--%s--\n", boundary))
log.Println(string(buf.Bytes()))
return buf.Bytes()
}
结果输出应该类似于
Subject: subject
To: recipient <victim@example.org>
From: me <sender@example.net>
MIME-Version: 1.0
Content-Type: multipart/mixed; boundary=foobar
--foobar
Content-Type: text/html; charset="UTF-8"
<h1>Tremble, victim</h1>
<p>We don't send <tt>text/plain</tt> because we
hate our users.</p>
--foobar
Content-Type: application/octet-stream
Content-Transfer-Encoding: base64
Content-Disposition: attachment; filename=skull_crossbones.jpg
YmluYXJ5ZGF0YQ==
--foobar--
TA贡献1864条经验 获得超6个赞
好的,找到问题了。事实证明,这个 403 错误与我的代码无关,而是与 AWS 中的 IAM 权限有关。显然,必须打开 IAM 权限才能启用 RAW 电子邮件内容。
- 2 回答
- 0 关注
- 186 浏览
添加回答
举报