如何在Ruby中通过电子邮件发送图表而无需保存到磁盘?

5
我正在使用Ruby脚本和"mail" gem发送电子邮件。
问题 - 如何在不保存到磁盘的情况下通过Ruby发送图形电子邮件?这是否可能?您推荐哪个绘图工具,"mail" gem是否支持流式传输?(或者必须先保存到磁盘)如果可能/容易,提供如何操作的示例代码将非常有帮助...

我认为提供更多信息会更有帮助。你所说的“图形”是指具有节点和边缘的事物,某些功能数据的图形表示,还是完全不同的东西?你要处理什么类型的数据?为什么将其保存到磁盘上会成为问题? - dantswain
@dantswain 关于图表,我的意思是创建一个简单的图表,例如条形图,其输入可能是X,Y值的哈希表之类的东西。在一个具体的案例中。所以像Corens下面链接引用的SVG库中的图表http://www.germane-software.com/software/SVG/SVG%3A%3AGraph/看起来很好。 - Greg
看起来@Coren的回答是正确的。 - dantswain
2个回答

10

你的完整回答。

为了简单起见,这里使用了纯 Ruby PNG 图表;实际应用程序可能会使用 SVG、快速本地代码或图表 API。

#!/usr/bin/env ruby
=begin

How to send a graph via email in Ruby without saving to disk
Example code by Joel Parker Henderson at SixArm, joel@sixarm.com

    https://dev59.com/VWHVa4cB1Zd3GeqPprpR

You need two gems:

    gem install chunky_png
    gem install mail

Documentation:

    http://rdoc.info/gems/chunky_png/frames
    https://github.com/mikel/mail

=end


# Create a simple PNG image from scratch with an x-axis and y-axis.
# We use ChunkyPNG because it's pure Ruby and easy to write results;
# a real-world app would more likely use an SVG library or graph API.

require 'chunky_png'
png = ChunkyPNG::Image.new(100, 100, ChunkyPNG::Color::WHITE)
png.line(0, 50, 100, 50, ChunkyPNG::Color::BLACK)  # x-axis
png.line(50, 0, 50, 100, ChunkyPNG::Color::BLACK)  # y-axis

# We do IO to a String in memory, rather than to a File on disk.
# Ruby does this by using the StringIO class which akin to a stream.
# For more on using a string as a file in Ruby, see this blog post:
# http://macdevelopertips.com/ruby/using-a-string-as-a-file-in-ruby.html

io = StringIO.new
png.write(io) 
io.rewind

# Create a mail message using the Ruby mail gem as usual. 
# We create it item by item; you may prefer to create it in a block.

require 'mail'
mail = Mail.new
mail.to = 'alice@example.com'
mail.from = 'bob@example.com'
mail.subject = 'Hello World'

# Attach the PNG graph, set the correct mime type, and read from the StringIO

mail.attachments['graph.png'] = {
  :mime_type => 'image/png', 
  :content => io.read 
}

# Send mail as usual. We choose sendmail because it bypasses the OpenSSL error.
mail.delivery_method :sendmail
mail.deliver

5

我不认为你不能做到。在 mail 的文档中,你可以看到以下示例代码:

mail = Mail.new do
  from     'me@test.lindsaar.net'
  to       'you@test.lindsaar.net'
  subject  'Here is the image you wanted'
  body     File.read('body.txt')
  add_file :filename => 'somefile.png', :content => File.read('/somefile.png')
end

mail.deliver!

您只需将:content => ...的目标替换为您内存中的文件内容即可。这就足够了。没有必要将附件保存在磁盘上,即使是暂时的,因为它们被重新编码为base64并添加到电子邮件末尾。
至于您问题的第二部分,有许多绘图/图形库可供选择。例如,请参见此问题此库
针对这种情况,真正超越其他库的并不存在。有许多用于许多不同用途的库,您需要选择最符合您需求和限制的库。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接