在Ruby中发送带嵌入图像的邮件

时间:2016-12-06 14:46:57

标签: ruby-on-rails ruby html-email pony

我想发送带有附加图片的邮件,并将此图片嵌入到html中。作为标记的来源,我应该写什么,是否有任何缺少的标题部分,如content_type?

当我进行真正的测试时,我会发送邮件到我的Gmail帐户。我可以看到有一个名为“未命名”的附件,即使我下载也无法显示图像。

宝石:小马

require 'pony'
Pony.override_options = { :via => :test }
Pony.mail(
    :to => 'foo@bar',
    :from => 'abc@abc.com',
    :subject => 'test123',
    :body =>   "<h1><strong>Dear X, check the newsletter ,<br></strong></h1> <img src='attached image' />",
    :attachments => {"happy_image.jpg" => File.read("happy_image.jpg")}
)
puts Mail::TestMailer.deliveries

输出:

Date: Tue, 06 Dec 2016 17:23:05 +0300

From: abc@abc.com

To: foo@bar

Message-ID: <5846c9ca183d6_5983c9fd899060@MW7BIQ12TKYHQC.mail>

Subject: test123

Mime-Version: 1.0

Content-Type: multipart/mixed;

boundary="--==_mimepart_5846c9caf15a_5983c9fd8989e5";

charset=UTF-8

Content-Transfer-Encoding: 7bit





----==_mimepart_5846c9caf15a_5983c9fd8989e5

Content-Type: text/plain;

charset=UTF-8

Content-Transfer-Encoding: 7bit



<h1><strong>Dear X, check the newsletter ,<br></strong></h1> <img src='' />

----==_mimepart_5846c9caf15a_5983c9fd8989e5

Content-Type: image/jpeg;

 filename=happy_image.jpg

Content-Transfer-Encoding: base64

Content-Disposition: attachment;

filename=happy_image.jpg

Content-ID: <happy_image.jpg@MW7BIQ12TKYHQC>



/9j/4AAQSkZJRgABAQEAYABgAAD/2wBDAAMCAgMCAgMDAwMEAwMEBQgFBQQE

BQoHBwYIDAoMDAsKCwsNDhIQDQ4RDgsLEBYQERMUFRUVDA8XGBYUGBIUFRT/

2wBDAQMEBAUEBQkFBQkUDQsNFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQU

FBQUFBQUFBQUFBQUFBQUFBQUFBQUFBT/wAARCAHiAuMDASIAAhEBAxEB/8QA

HwAAAQUBAQEBAQEAAAAAAAAAAAECAwQFBgcICQoL/8QAtRAAAgEDAwIEAwUF

BAQAAAF9AQIDAAQRBRIhMUEGE1FhByJxFDKBkaEII0KxwRVS0fAkM2JyggkK

FhcYGQ==



----==_mimepart_5846c9caf15a_5983c9fd8989e5--

1 个答案:

答案 0 :(得分:0)

您应该能够对图像进行BASE64编码,并将结果字符串用作\d+\s\d+(\s\d+)+标记的src

例如:

img

另外,请确保将您的内容类型设置为<img src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAWQAAAD8CAYAAAB..."/> 而不是text/html。看邮件,它似乎设置为后者,因此图像不会渲染,标签呈现为文本。将以下内容添加到您的参数中以使用text/plain内容类型:

text/html