如何将图像添加到电子邮件的HTML正文中(Go)

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

How to add image to html body of an email (Go)

问题

我正在使用Gomail

我正在尝试发送一封邮件给自己。我已经知道如何发送邮件,但现在我想添加一张图片,可以将其放在HTML正文中或作为附件(无论哪种方式都可以)。我只需要能在我的邮件中看到这张图片。

首先,我通过POST请求发送img src,然后将其保存到以下struct中...

type test_struct struct {
    Test string `json:"image"`
}

然后我尝试将其附加到邮件正文中,代码如下...

mail := gomail.NewMessage()
mail.SetHeader("From", "XXXX@gmail.com")
mail.SetHeader("To", "XXXX@gmail.com")
mail.SetHeader("Subject", "IMAGE!")

mail.SetBody("text/html", `<img src="cid:t.Test" alt="My Image"/>`)

这样做没有起作用,所以我尝试使用Embed方法...

mail.Embed(t.Test)

这给了我一个空白的图片,并显示错误消息"文件名或扩展名太长"。不确定这是否重要,但请注意,我得到的src是来自HTML5的Canvas。我从Canvas获取图像的源代码如下...

localCanvas.toDataURL('image/png');

这是我保存在t.Test中的值...

buf, err := ioutil.ReadAll(req.Body)
reader := bytes.NewReader(buf)

var t test_struct

err = json.NewDecoder(reader).Decode(&t)

保存在t.Test中的字符串格式如下...

data:image/png:base64, iVBORw0KGgoAAAANSUhEUgAAAoAAAAHgCAYAAAA10dzkAAAgA...

我该如何将其发送到我的电子邮件中?文档只能帮助我到这一步。

英文:

I am using Gomail

I am attempting to send an email to myself. I have figured out how to do so, but now I want to add an image, either in the html body or as an attachment (does not really matter). I just need to be able to see the image in my email.

First off, I am sending the img src through a POST request, which I then save into the following struct...

type test_struct struct {
    Test string `json:&quot;image&quot;`
}

I then try to attach it in the email body like so...

mail := gomail.NewMessage()
mail.SetHeader(&quot;From&quot;, &quot;XXXX@gmail.com&quot;)
mail.SetHeader(&quot;To&quot;, &quot;XXXX@gmail.com&quot;)
mail.SetHeader(&quot;Subject&quot;, &quot;IMAGE!&quot;)

mail.SetBody(&quot;text/html&quot;, `&lt;img src=&quot;cid:t.Test&quot; alt=&quot;My Image&quot;/&gt;`)

this did not work, so I tried to use Embed method...

mail.Embed(t.Test)

This gave me a blank image with the error the filename or extension is too long. Not sure if this is important, but note that the src I got is from HTML5 Canvas. I got the source of the image from Canvas...

localCanvas.toDataURL(&#39;image/png&#39;);

And this is the value I save in t.Test...

buf, err := ioutil.ReadAll(req.Body)
reader := bytes.NewReader(buf)

var t test_struct

err = json.NewDecoder(reader).Decode(&amp;t)

The string being save in the t.Test is of the following format...

data:image/png:base64, iVBORw0KGgoAAAANSUhEUgAAAoAAAAHgCAYAAAA10dzkAAAgA...

How can I send this to my email? The documentation only gets me so far.

答案1

得分: 4

首先,检查t.Test中的数据是否正确(是否包含文件名、路径或其他需要引用图像的内容)。

好的,你有几个选项,首先,如果只需附加图像,你只需要执行以下操作:

mail.Attach("/path/of/your/image/image.png")

但是,如果你需要在消息中使用图像,你有几种选择。

选项1:使用Embed方法

你必须在文件系统中有图像,因为该方法是以这种方式定义的。你需要执行以下操作:

mail.SetBody("text/html", "Image <img src=\"cid:tux.png\"/>")
mail.Embed("/path/of/your/image/tux.png")

在添加图像时,你必须使用图像名称,例如tux.png,并在html正文中使用img标签定义srccid:tux.png

选项2:使用base64编码

对于这个选项,你需要知道图像文件的MIME类型,在我的示例中是一个png文件,所以MIME类型是image/png。此外,你需要将图像编码为base64。

img, err := ioutil.ReadFile("/path/of/your/image/tux.png")
if err != nil {
    // 检查错误
}
out := base64.StdEncoding.EncodeToString(img)

或者,如果你没有图像在文件系统中,但是你有一个变量中的图像数据([]byte类型),你可以使用EncodeToString方法。

var imageData []byte
// 在某个地方,你将图像数据加载到imageData中
out := base64.StdEncoding.EncodeToString(imageData)

然后,你可以这样使用它:

mail.SetBody("text/html", fmt.Sprintf("Image <img src=\"data:image/png;base64,%s\"/>", out))

因此,当你使用img时,你需要在src中设置一个嵌入的图像,格式为data:mime_type;base64,image_encoded_base64。如果我们看一下示例,它是data:image/png;base64,iVBORw0K...

编辑:

我创建了一个带有JSON请求和处理程序的示例Example

英文:

First of all, check if the data in t.Test is correct (if contains the filename, path, or whatever you need to reference the image)

Well, you have some options, first, if it's ok just attaching the image, you only should do:

mail.Attach(&quot;/path/of/your/image/image.png&quot;)

But, if you need to use the image in the message, you have some alternatives.

Alt 1: Use Embed method

You must to have the image in your filesystem, because the method is defined in that way. You have to do something like:

mail.SetBody(&quot;text/html&quot;, &quot;Image &lt;img src=\&quot;cid:tux.png\&quot;/&gt;&quot;)
mail.Embed(&quot;/path/of/your/image/tux.png&quot;)

You must to use the image name, in this case tux.png, when you add it in the html body with the img tag, you have to define the src like cid:tux.png

Alt 2: Use a base64 encoding

For this you need to know the mime type of the image file, in my example is a png file, so the mime is image/png. Also, you have to encode the image as base64.

img, err := ioutil.ReadFile(&quot;/path/of/your/image/tux.png&quot;)
if err != nil {
    // check errors
}
out := base64.StdEncoding.EncodeToString(img)

Or, if you don't have the image in the filesystem, but you have it in a variable ([]byte type), you can use it with EncodeToString

var imageData []byte
// in some part, you load the image data into imageData
out := base64.StdEncoding.EncodeToString(imageData)

And you use it like

mail.SetBody(&quot;text/html&quot;, fmt.Sprintf(&quot;Image &lt;img src=\&quot;data:image/png;base64,%s\&quot;/&gt;&quot;, out))

So, when you use img, you have to set in src an embedded image with data:mime_type;base64,image_encoded_base64, if we look the example, is data:image/png;base64,iVBORw0K...

EDIT:

I created an example with the JSON request and the handler Example

huangapple
  • 本文由 发表于 2016年12月13日 12:10:49
  • 转载请务必保留本文链接:https://go.coder-hub.com/41113598.html
匿名

发表评论

匿名网友

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

确定