Search code examples
emailgosmtp

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?


Solution

  • 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)
        }
    }