如何使用Go发送带有HTML格式的电子邮件?

huangapple go评论90阅读模式
英文:

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 (
	&quot;gopkg.in/gomail.v2&quot;
)

func main() {
	m := gomail.NewMessage()
	m.SetHeader(&quot;From&quot;, &quot;alex@example.com&quot;)
	m.SetHeader(&quot;To&quot;, &quot;bob@example.com&quot;)
	m.SetHeader(&quot;Subject&quot;, &quot;Hello!&quot;)
	m.SetBody(&quot;text/html&quot;, &quot;Hello &lt;b&gt;Bob&lt;/b&gt;!&quot;)

	// Send the email to Bob
	d := gomail.NewPlainDialer(&quot;smtp.example.com&quot;, 587, &quot;user&quot;, &quot;123456&quot;)
	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.

huangapple
  • 本文由 发表于 2012年3月31日 04:36:04
  • 转载请务必保留本文链接:https://go.coder-hub.com/9950098.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定