如何在不首先使用ruby gmail创建文件的情况下发送带有附件的电子邮件



我正在使用ruby gmail gem发送邮件。

我想做的是将ruby散列作为json文件发送。

示例:

require 'gmail'
require 'json'
hash = {'foo' => 'bar}
Gmail.new(<EMAIL>, <PASSWORD>) do |gmail|
  gmail.deliver do
    to <RECIPIENT>
    subject <SUBJECT>
    text_part do
      body <EMAIL MESSAGE>
    end
    add_file hash.to_json
  end
end

当我尝试这样做时,它只是发送没有附件的邮件。

我下一步可以尝试什么?

编辑:

我想在不首先创建文件的情况下完成此操作。

您需要先创建文件,然后才能用add_file方法发送:

hash = {'foo' => 'bar'}
File.open("filename.json","w") do |f|
  f.write(hash.to_json)
end

然后:

Gmail.new(<EMAIL>, <PASSWORD>) do |gmail|
  gmail.deliver do
    to <RECIPIENT>
    subject <SUBJECT>
    text_part do
      body <EMAIL MESSAGE>
    end
    add_file 'path/to/filename.json`
  end
end

如果使用"gmail"gem(https://rubygems.org/gems/gmail),则可以添加具有名称和内容参数的文件,而不必实际创建本地文件。例如:

Gmail.connect(<EMAIL>, <PASSWORD>) do |gmail|
   gmail.deliver do
     to(<RECIPIENT>)
     subject(<SUBJECT>)
     text_part do
       body(<TEXT_BODY>)
     end
     html_part do
        content_type('text/html; charset=UTF-8')
        body(<HTML_BODY>)
     end
     add_file({filename: <FILE_NAME>, content: <FILE_CONTENT>})
   end
end

相关内容

最新更新