如何将图片插入电子邮件正文中?

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

How do I Insert an image into email body?

问题

我想使用Go语言在电子邮件正文中发送一张图片。
我使用了来自github的这个包:

https://github.com/scorredoira/email

    err := m.Attach("image.png")
	if err1 != nil {
		fmt.Println(err1)
	}

现在我能够将图片文件作为附件发送,但我需要将图片文件发送到电子邮件正文中。

提前感谢。

英文:

I want to send a image in email body using go lang.
Used this package from github

https://github.com/scorredoira/email

    err := m.Attach("image.png")
	if err1 != nil {
		fmt.Println(err1)
	}

Now i am able to send image file as attachment but my need is to send a image file in email body.

Thanks in advance.

答案1

得分: 8

你可以使用Gomail(我是作者)。请查看Embed方法,它允许你在电子邮件正文中嵌入图片:

package main

import "gopkg.in/gomail.v2"

func main() {
    m := gomail.NewMessage()
    m.SetHeader("From", "from@example.com")
    m.SetHeader("To", "to@example.com")
    m.SetHeader("Subject", "Hello!")
    m.Embed("image.png")
    m.SetBody("text/html", `<img src="cid:image.png" alt="My image" />`)

    d := gomail.NewPlainDialer("smtp.example.com", 587, "user", "123456")

    if err := d.DialAndSend(m); err != nil {
        panic(err)
    }
}

希望对你有帮助!

英文:

You can use Gomail (I'm the author). Have a look at the Embed method which allow you to embed images in the email body:

package main

import &quot;gopkg.in/gomail.v2&quot;

func main() {
	m := gomail.NewMessage()
	m.SetHeader(&quot;From&quot;, &quot;from@example.com&quot;)
	m.SetHeader(&quot;To&quot;, &quot;to@example.com&quot;)
	m.SetHeader(&quot;Subject&quot;, &quot;Hello!&quot;)
	m.Embed(&quot;image.png&quot;)
	m.SetBody(&quot;text/html&quot;, `&lt;img src=&quot;cid:image.png&quot; alt=&quot;My image&quot; /&gt;`)

	d := gomail.NewPlainDialer(&quot;smtp.example.com&quot;, 587, &quot;user&quot;, &quot;123456&quot;)

	if err := d.DialAndSend(m); err != nil {
		panic(err)
	}
}

huangapple
  • 本文由 发表于 2016年1月14日 21:24:33
  • 转载请务必保留本文链接:https://go.coder-hub.com/34790771.html
匿名

发表评论

匿名网友

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

确定