Santiago Corredoira
Santiago Corredoira

Reputation: 47276

How to send an email with attachments in Go

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?

Upvotes: 21

Views: 29961

Answers (5)

PePa
PePa

Reputation: 69

If you don't want a library where you'd still have to write your own Golang code, but just a (CLI) app, I made this one: https://github.com/pepa65/mailer

Upvotes: 0

Ale
Ale

Reputation: 2014

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", "[email protected]")
    m.SetHeader("To", "[email protected]", "[email protected]")
    m.SetAddressHeader("Cc", "[email protected]", "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)
    }
}

Upvotes: 19

Bijan
Bijan

Reputation: 26507

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 "[email protected]" and "First Last " format
  • Text and HTML Message Body
  • Attachments
  • Read Receipts
  • Custom headers
  • More to come!

Upvotes: 12

Santiago Corredoira
Santiago Corredoira

Reputation: 47276

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 = "[email protected]"
m.To = []string{"[email protected]"}

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)

Upvotes: 23

Denys S&#233;guret
Denys S&#233;guret

Reputation: 382274

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.

Upvotes: 3

Related Questions