Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

email

go

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

like image 321
Jay Stramel Avatar asked Mar 30 '12 20:03

Jay Stramel


People also ask

How do you send a go email?

Below is the complete code to send a plain text email with smtp package in golang. package main import ( "fmt" "net/smtp" ) func main() { // Sender data. from := "[email protected]" password := "<Email Password>" // Receiver email address. to := []string{ "[email protected]", } // smtp server configuration.

Does email accept HTML?

While HTML email still has issues, most notably with compatibility, it still wins in the end. Plain text emails are often reliable in terms of email deliverability. Still, when it comes to overall user experience, visual display, and brand consistency, HTML wins out, hands down.

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

To use Gomail, you'll need version 1.2 of Go or newer. In the code below, NewMessage creates a new message, and the headers are set by the SetHeader function. The SetBody function is used for the message itself. Because you're using a third-party package, the Attach function attaches external files to the email.


1 Answers

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 =)

like image 58
GreyHands Avatar answered Oct 16 '22 17:10

GreyHands