我正在使用 Ruby 脚本和“邮件”gem 发送电子邮件。
问题 - 如何在 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, joel@sixarm.com
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 = '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
我不明白你为什么不能。在邮件的文档中,您可以看到以下示例代码:
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 中重新编码并添加到邮件末尾。
对于您问题的第二部分,那里有很多绘图/图形库。例如,请参阅此问题或此库。
对于这类事情,实际上并没有一个高于其他库的库。有许多不同用途的库,您必须选择更适合您的需求和约束的库。