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:無法傳送附件的電子郵件的詳細內容。更多資訊請關注PHP中文網其他相關文章!