How to send an email with attachments in Go

烂漫一生 提交于 2019-12-05 13:05:57

问题


I have found this library and have managed to send an attachment in an empty email but not to combine text and attachments.

https://github.com/sloonz/go-mime-message

How can it be done?


回答1:


I ended up implementing it myself: https://github.com/scorredoira/email

Usage is very simple:

m := email.NewMessage("Hi", "this is the body")
m.From = "from@example.com"
m.To = []string{"to@example.com"}

err := m.Attach("picture.png")
if err != nil {
    log.Println(err)
}

err = email.Send("smtp.gmail.com:587", smtp.PlainAuth("", "user", "password", "smtp.gmail.com"), m)



回答2:


I prefer to use https://github.com/jordan-wright/email for email purposes. It supports attachments.

Email for humans

The email package is designed to be simple to use, but flexible enough so as not to be restrictive. The goal is to provide an email interface for humans.

The email package currently supports the following:

  • From, To, Bcc, and Cc fields
  • Email addresses in both "test@example.com" and "First Last " format
  • Text and HTML Message Body
  • Attachments
  • Read Receipts
  • Custom headers
  • More to come!



回答3:


I created gomail for this purpose. It supports attachments as well as multipart emails and encoding of non-ASCII characters. It is well documented and tested.

Here is an example:

package main

func main() {
    m := gomail.NewMessage()
    m.SetHeader("From", "alex@example.com")
    m.SetHeader("To", "bob@example.com", "cora@example.com")
    m.SetAddressHeader("Cc", "dan@example.com", "Dan")
    m.SetHeader("Subject", "Hello!")
    m.SetBody("text/html", "Hello <b>Bob</b> and <i>Cora</i>!")
    m.Attach("/home/Alex/lolcat.jpg")

    d := gomail.NewPlainDialer("smtp.example.com", 587, "user", "123456")

    // Send the email to Bob, Cora and Dan.
    if err := d.DialAndSend(m); err != nil {
        panic(err)
    }
}



回答4:


Attachements in the SMTP protocol are sent using a Multipart MIME message.

So I suggest you simply

  • create a MultipartMessage

  • set your text in the fist part as a TextMessage (with "Content-Type", "text/plain")

  • add your attachements as parts using AddPart.



来源:https://stackoverflow.com/questions/11075749/how-to-send-an-email-with-attachments-in-go

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!