我正在尝试在Go(Golang)中发送包含电子邮件正文和文件附件(CSV文件)的电子邮件。
我遵循的是多部分消息的mime
标准,但是我对遵循该标准的消息的结构不是很熟悉。我隐约地跟随一位同事的Python代码片段作为指导,该指南正在使用Python库email
(我认为这来自标准库),例如MIMEText
和MIMEMultipart
。
执行以下Go代码时,电子邮件正文未显示:
此函数应返回一个 byte slice ,用作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)不必完全在此处,可以将其附加到上面的内容类型行中。它只需要在content-type和主体的开头之间看到一个空白行。
我假设附件没有问题,对吗?我的假设是,因为在添加附件数据之前,您在内容配置行的末尾有双换行符。
关于go - 在Golang中附加文件并通过SMTP发送时没有正文的电子邮件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56565594/