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 <[email protected]>
From: me <[email protected]>
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 關注
- 215 瀏覽
添加回答
舉報