Jay Stramel
Jay Stramel

Reputation: 3301

How to send an email using Go with an HTML formatted body?

This seems like a very common need, but I didn't find any good guides when I searched for it.

Upvotes: 43

Views: 30826

Answers (2)

GreyHands
GreyHands

Reputation: 1794

Assuming that you're using the net/smtp package and so the smtp.SendMail function, you just need to declare the MIME type in your message.

subject := "Subject: Test email from Go!\n"
mime := "MIME-version: 1.0;\nContent-Type: text/html; charset=\"UTF-8\";\n\n"
body := "<html><body><h1>Hello World!</h1></body></html>"
msg := []byte(subject + mime + body)

smtp.SendMail(server, auth, from, to, msg)

Hope this helps =)

Upvotes: 79

Ale
Ale

Reputation: 2014

I am the author of gomail. With this package you can easily send HTML emails:

package main

import (
    "gopkg.in/gomail.v2"
)

func main() {
    m := gomail.NewMessage()
    m.SetHeader("From", "[email protected]")
    m.SetHeader("To", "[email protected]")
    m.SetHeader("Subject", "Hello!")
    m.SetBody("text/html", "Hello <b>Bob</b>!")

    // Send the email to Bob
    d := gomail.NewPlainDialer("smtp.example.com", 587, "user", "123456")
    if err := d.DialAndSend(m); err != nil {
        panic(err)
    }
}

You can also add a plain text version of the body in your email for the client that does not support HTML using the method AddAlternative.

Upvotes: 31

Related Questions