在 Golang 中附加文件并通过 SMTP 发送时,电子邮件消息没有正文部分
时间:2024-04-07
浏览:162
作者:佚名
本篇文章主要是结合我之前面试的各种经历和实战开发中遇到的问题解决经验整理的,希望这篇《在 Golang 中附加文件并通过 SMTP 发送时,电子邮件消息没有正文部分》对你有很大帮助!欢迎收藏,分享给更多的需要的朋友学习~
我正在尝试在 go (golang) 中发送一封包含电子邮件正文和文件附件(csv 文件)的电子邮件。
我遵循多部分消息的 mime 标准,但是我不太熟悉遵循该标准的消息的结构。我隐约遵循一位同事的python代码片段作为指南,该代码片段使用python库email(我认为这是来自标准库),例如mimetext 和 mimemultipart。
执行以下 go 代码时,电子邮件正文未显示:
- 这有什么问题吗?
- 如何发送包含该文件附件和电子邮件正文的电子邮件?
此函数应返回一个字节切片,用作从 go 标准库调用 smtp.sendmail 的参数。请参阅下面的评论,了解收到的电子邮件发生了什么情况(this does not show up [...] 和 this also does not show up [...])。
func msgWithAttachment(subject, filePath string) ([]byte, error) {
// this is the separator used for the various parts of the MIME message structure
// identified as "boundary"
bPlaceholder := "our-custom-separator"
// the message setup of the common/standard initial part
mime := bytes.NewBuffer(nil)
mime.WriteString(fmt.Sprintf("Subject: %s\r\nMIME-Version: 1.0\r\n", subject))
mime.WriteString(fmt.Sprintf("Content-Type: multipart/mixed; boundary=%s\r\n", bPlaceholder))
// THIS DOES NOT SHOW UP AS THE BODY OF THE EMAIL...
// mime.WriteString("\r\n")
// mime.WriteString(fmt.Sprintf("--%s\r\n", bPlaceholder))
// mime.WriteString("This should be the email message body (v1)...")
// mime.WriteString("\r\n")
// THIS ALSO DOES NOT SHOW UP AS THE BODY OF THE EMAIL...
// BUT IS NEEDED OTHERWISE THE EMAIL MESSAGE SEEMS TO CONTAIN AS ATTACHMENT THE EMAIL MESSAGE ITSELF
// (CONTAINING ITSELF THE REAL ATTACHMENT)
mime.WriteString(fmt.Sprintf("--%s\r\n", bPlaceholder))
mime.WriteString("Content-Type: text/plain; charset=utf-8\r\n")
mime.WriteString("This should be the email message body (v2)...")
// attach a file from the filesystem
_, msgFilename := filepath.Split(filePath)
mime.WriteString(fmt.Sprintf("\n--%s\r\n", bPlaceholder))
mime.WriteString("Content-Type: application/octet-stream\r\n")
mime.WriteString("Content-Description: " + msgFilename + "\r\n")
mime.WriteString("Content-Transfer-Encoding: base64\r\n")
mime.WriteString("Content-Disposition: attachment; filename=\"" + msgFilename + "\"\r\n\r\n")
fileContent, err := ioutil.ReadFile(filePath) // read and encode the content of the file
if err != nil {
return nil, err
}
b := make([]byte, base64.StdEncoding.EncodedLen(len(fileContent)))
base64.StdEncoding.Encode(b, fileContent)
mime.Write(b)
// footer of the email message
mime.WriteString("\r\n--" + bPlaceholder + "--\r\n\r\n")
return mime.Bytes(), nil
}解决方案
巧合的是,前几天我也遇到了类似的问题。我需要在正文内容类型和正文本身的开头之间有一个空行。以下是这部分代码的更新行:
mime.WriteString("Content-Type: text/plain; charset=utf-8\r\n")
mime.WriteString("\r\nThis should be the email message body (v2)...")
为了清楚起见,这个换行符 (\r\n) 不必完全位于此处,它可以附加到上面的内容类型行。它只需要在内容类型和正文开头之间看到一个空行。
我假设附件的附加没有问题,对吗?我的假设是,这是因为在添加附件数据之前,内容处置行末尾有双换行符。
阅读 rfc 规范对我有帮助:https://www.w3.org/Protocols/rfc1341/7_2_Multipart.html
今天关于《在 Golang 中附加文件并通过 SMTP 发送时,电子邮件消息没有正文部分》的内容就介绍到这里了,是不是学起来一目了然!想要了解更多关于的内容请关注golang学习网公众号!
本文内容来源于互联网,如有侵权请联系删除。
近期热门
站内热门
最新文章
热门专题
