我正在使用Ruby脚本和“邮件”gem来发送电子邮件。如何通过电子邮件在Ruby中发送图形而不保存到磁盘?
问题 - 如何在Ruby中通过电子邮件发送图形而不保存到磁盘?这可能吗?你会推荐哪种图形工具,并且“邮件”gem支持以某种方式将此流出? (或者它是一个给定的,你必须先保存到磁盘)如果它是可能的/简单的示例代码行应该如何将是伟大的....
我正在使用Ruby脚本和“邮件”gem来发送电子邮件。如何通过电子邮件在Ruby中发送图形而不保存到磁盘?
问题 - 如何在Ruby中通过电子邮件发送图形而不保存到磁盘?这可能吗?你会推荐哪种图形工具,并且“邮件”gem支持以某种方式将此流出? (或者它是一个给定的,你必须先保存到磁盘)如果它是可能的/简单的示例代码行应该如何将是伟大的....
您的完整答案。
为简单起见,它使用纯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, [email protected]
http://stackoverflow.com/questions/9779565
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 = '[email protected]'
mail.from = '[email protected]'
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
我不明白你为什么不能。在mail's documentation,你可以看到这个示例代码:
mail = Mail.new do
from '[email protected]'
to '[email protected]'
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重新编码并添加到邮件的末尾。
对于问题的第二部分,在那里有很多plot/graph lib。例如参见this question或this lib。
这种事情并没有真正的一个以上的lib。有很多不同的用法,你必须选择适合你的需求和约束条件。
我认为更多的信息会有帮助。 “图”是什么意思?一个有节点和边的东西,一些功能数据的图形表示,完全不同的东西?你从什么样的数据开始?为什么要保存到磁盘有问题? – dantswain 2012-03-22 12:13:58
@dantswain重新图我的意思是创建一个简单的图形,例如条形图,其中输入可能是X,Y值或其他值的散列。在一个特定的情况下。因此,像下面的Corens链接引用的图http://www.germane-software.com/software/SVG/SVG%3A%3AGraph/ SVG库看起来很好。 – Greg 2012-03-22 23:59:56
看起来像@ Coren的答案是在正确的轨道上,那么。 – dantswain 2012-03-23 13:58:35