英文:
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.
答案1
得分: 73
subject := "主题:来自Go的测试邮件\n"
mime := "MIME版本:1.0;\n内容类型:text/html; 字符集="UTF-8";\n\n"
body := "
你好,世界!
"
msg := []byte(subject + mime + body)
smtp.SendMail(server, auth, from, to, msg)
英文:
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 =)
答案2
得分: 27
我是gomail的作者。使用这个包,你可以轻松地发送HTML邮件:
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>!")
// 发送邮件给Bob
d := gomail.NewPlainDialer("smtp.example.com", 587, "user", "123456")
if err := d.DialAndSend(m); err != nil {
panic(err)
}
}
你还可以使用AddAlternative方法,在邮件中添加一个纯文本版本的正文,以供不支持HTML的客户端使用。
英文:
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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论