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?
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)
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
.
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)
}
}
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!