加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

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

发布时间:2020-12-17 04:04:44 所属栏目:百科 来源:网络整理
导读:我正在使用 Ruby脚本和“mail”gem来发送电子邮件. 问题 – 如何在Ruby中通过电子邮件发送图表而不保存到磁盘?这可能吗?你会推荐哪种图形工具,并且“mail”gem支持以某种方式将其流出来? (或者它必须首先保存到磁盘)如果它可能/简单的示例代码行应该如何
我正在使用 Ruby脚本和“mail”gem来发送电子邮件.

问题 – 如何在Ruby中通过电子邮件发送图表而不保存到磁盘?这可能吗?你会推荐哪种图形工具,并且“mail”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

    https://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,ChunkyPNG::Color::BLACK)  # x-axis
png.line(50,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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读