This seems like a very common need, but I didn't find any good guides when I searched for it.
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.
mime := "MIME-version: 1.0;
Content-Type: text/html; charset=\"UTF-8\";
";
subject := "Subject: Test email from Go!
"
msg := []byte(subject + mime + "<html><body><h1>Hello World!</h1></body></html>")
smtp.SendMail(server, auth, from, to, msg)
Hope this helps =)
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", "alex@example.com")
m.SetHeader("To", "bob@example.com")
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.
This is an addendum to @GreyHands answer:
I was having the issue where even after setting the MIME / Content Type my html tags were showing as plain text.
Turns out I had imported html/template
and the escaping resulted in the html appearing as plain text. Importing text/template
, instead, fixed the issue.