在Golang中附加文件并通过SMTP发送时没有正文部分的电子邮件

问题描述 投票:1回答:1

我试图在Go(Golang)中发送带有电子邮件正文和文件附件(CSV文件)的电子邮件。

我正在遵循多部分消息的mime标准,但是我对遵循该标准的消息的结构不是很熟悉。我隐约地跟随一位同事的Python代码片段作为使用Python库email的指南(我认为这是来自标准库),例如MIMETextMIMEMultipart

电子邮件正文未显示在执行以下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
}
go smtp email-attachments mime
1个回答
1
投票

巧合的是,前几天我遇到了类似的问题。我需要在正文内容类型和正文本身的开头之间留空行。以下是此部分代码的更新行:

    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和主体的开头之间看到一个空白行。

我假设附件没有问题,对吗?我的假设是,这是因为在添加附件数据之前,您在内容处置行的末尾有双换行符。

© www.soinside.com 2019 - 2024. All rights reserved.