Ruby on Rails:如何将文件附加到电子邮件

时间:2019-02-09 05:30:30

标签: ruby-on-rails google-api

我正在尝试从Rails项目发送带有附件的电子邮件。我正在使用Google API,特别是gmail_v1 API。

我已经能够获得发送带有主题和正文的电子邮件的代码,但是无法附加CSV。 CSV的名称是“ results.csv”

m = Mail.new(
  to: "to@gmail.com",
  from: "from@gmail.com",
  subject: "Test Subject",
  body:"Test Body")

  m.attachments['shoes.csv'] = {mime_type: 'results.csv', content: CSV}

  message_object = Google::Apis::GmailV1::Message.new(raw:m.to_s)
  service.send_user_message("me", message_object)

没有一行:

m.attachments['shoes.csv'] = {mime_type: 'results.csv', content: CSV}

该代码有效,但没有附件。添加附件的正确方法是什么?

1 个答案:

答案 0 :(得分:0)

您向附件发送了错误的参数。

附件的发送方式如下

attachments['shoes.csv'] = { mime_type: 'text/csv', content: File.read("path/to/csv/or/generator/methos") }

更新后的代码将为

m = Mail.new(
  to: "to@gmail.com",
  from: "from@gmail.com",
  subject: "Test Subject",
  body:"Test Body")

  m.attachments['shoes.csv'] = { mime_type: 'text/csv', content: File.read("path/to/csv/or/generator/methos") }

  message_object = Google::Apis::GmailV1::Message.new(raw:m.to_s)
  service.send_user_message("me", message_object)

希望这会有所帮助