Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to send an email with attachments in Go

Tags:

email

go

smtp

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?

like image 471
Santiago Corredoira Avatar asked Jun 18 '12 00:06

Santiago Corredoira


People also ask

How do I send an email with an attachment in Golang?

Golang - send an email with attachments. m := NewMessage("Test", "Body message.")

Why is my email not sending my attachments?

The most common reason that an attachment won't send is that it is too big. These limits are set by whoever you use for email, whether it's an email account through your ISP or through an online provider like Yahoo or GMail. You should check with your email service provider to see what the limits are for attachments.


2 Answers

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)
like image 75
Santiago Corredoira Avatar answered Sep 29 '22 03:09

Santiago Corredoira


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)
    }
}
like image 24
Ale Avatar answered Sep 29 '22 02:09

Ale