php小编草莓今天给大家分享一篇关于GoLang的问题:无法发送带附件的电子邮件。在日常开发中,发送带附件的电子邮件是一个常见需求,但有时候我们会遇到一些问题。本文将介绍如何解决这个问题,帮助大家顺利发送带附件的电子邮件。我们将一步步解析问题的原因,并提供相应的解决方案,希望能帮到大家。
问题内容
我正在尝试使用以下代码发送带有附件的电子邮件:
package mail
import (
"bytes"
logging "project/logging"
"fmt"
"log"
"mime/multipart"
"net/textproto"
"gopkg.in/mail.v2"
)
func SendWithAttachment(from string, to []string, subject, bodyHTML string, attachmentName string, attachmentData []byte) error {
logoURL := "/path/to/cs.jpg"
m := mail.NewMessage()
m.SetHeader("From", from)
m.SetHeader("To", to...)
m.SetHeader("Subject", subject)
m.Embed(logoURL)
// Create a multipart message
body := &bytes.Buffer{}
writer := multipart.NewWriter(body)
// Add HTML part
htmlPart := make(textproto.MIMEHeader)
htmlPart.Set("Content-Type", "text/html")
htmlPart.Set("Content-Transfer-Encoding", "quoted-printable")
htmlPartWriter, err := writer.CreatePart(htmlPart)
if err != nil {
logging.NewDefaultLogger().Errorf("Error creating html part: %s", err)
return err
}
htmlPartWriter.Write([]byte(bodyHTML))
// Add Attachment part
attachmentPart := make(textproto.MIMEHeader)
attachmentPart.Set("Content-Type", "application/octet-stream")
attachmentPart.Set("Content-Transfer-Encoding", "base64")
attachmentPart.Set("Content-Disposition", `attachment; filename="`+attachmentName+`"`)
attachmentPartWriter, err := writer.CreatePart(attachmentPart)
if err != nil {
logging.NewDefaultLogger().Errorf("Error creating attachment part: %s", err)
return err
}
attachmentPartWriter.Write(attachmentData)
writer.Close()
m.SetBody("multipart/mixed", body.String())
fmt.Printf("Sending mail.....")
err = gs.dialer.DialAndSend(m)
if err != nil {
logging.NewDefaultLogger().Errorf("Error sending email..: %s", err)
return err
}
return nil
}
登录后复制
正文内容和附件内容均作为附件出现在名为“noname”的文件中。
附件文件内容如下:
--d885a04b467ae7d6100eb844c09574a6bdaef0a9796dc6fdde03a90613c9
内容传输编码:引用可打印
内容类型:text/html
...
--d885a04b467ae7d6100eb844c09574a6bdaef0a9796dc6fdde03a90613c9
内容处置:附件;文件名=“resource_details.csv”
内容传输编码:base64
内容类型:应用程序/八位字节流
附件内容..
--d885a04b467ae7d6100eb844c09574a6bdaef0a9796dc6fdde03a90613c9--
解决方法
我能够让它工作:
m := mail.NewMessage()
m.SetHeader("From", emailDetails.From)
m.SetHeader("To", emailDetails.To...)
m.SetHeader("Subject", emailDetails.Subject)
if emailDetails.BodyHTML != "" {
m.SetBody("text/html", emailDetails.BodyHTML)
} else {
m.SetBody("text/plain", emailDetails.BodyPlain)
}
if emailDetails.AttachmentName != "" && len(emailDetails.AttachmentData) > 0 {
m.Attach(emailDetails.AttachmentName, mail.SetCopyFunc(func(writer io.Writer) error {
_, err := writer.Write(emailDetails.AttachmentData)
return err
}))
}
登录后复制
以上就是GoLang:无法发送带附件的电子邮件的详细内容,更多请关注每日运维网(www.mryunwei.com)其它相关文章!