【问题标题】:mail attachment SendGrid using ruby使用 ruby​​ 的邮件附件 SendGrid
【发布时间】:2017-09-13 21:25:42
【问题描述】:

我正在尝试使用 Ruby 发送带有附件的电子邮件,并且我有以下行:

from = Email.new(email: 'mail@mail.com')
to = Email.new(email: 'mail@mail.com')
subject = 'file for this week'
content = Content.new(type: 'text/plain', value: 'Please find file for this week.')
mail = Mail.new(from, subject, to, content)
mail.attachments['test.txt'] = File.read("#{Rails.root}/public/test.txt")
sg = SendGrid::API.new(api_key:'myapikey')
sg.client.mail._('send').post(request_body: mail.to_json)

问题是以下行的代码(当我删除它时,我会收到一封电子邮件):

mail.attachments['test.txt'] = File.read("#{Rails.root}/public/test.txt")

但是当我尝试运行它时,我收到以下错误:

undefined method '[]=' for nil:NilClass

以前有人遇到过这个错误吗?

【问题讨论】:

  • 这意味着 mail.attachments 返回 nil。 mail 变量来自哪里?
  • 我已经更新了问题中的源代码。
  • 请再检查一遍

标签: ruby-on-rails ruby sendgrid cloud9-ide


【解决方案1】:

根据docs,通常您会使用值为字符串的哈希创建一个新的Mail 对象。很难说,因为我不知道你的 EmailContent 类在做什么,但我怀疑当你创建 mail 时出了点问题。让我们先把那些未知的类排除在外。

尝试将您的代码更改为:

from = 'mail@mail.com'
to = 'mail@mail.com'
subject = 'file for this week'
content = 'Please find file for this week.'

mail = Mail.new(from: from, to: to, subject: subject, body: content)
mail.attachments['test.txt'] = File.read("#{Rails.root}/public/test.txt")

sg = SendGrid::API.new(api_key:'myapikey')
sg.client.mail._('send').post(request_body: mail.to_json)

【讨论】:

  • 这也不起作用。我使用的示例来自这里:github.com/sendgrid/sendgrid-ruby#with-mail-helper-class
  • 哪一行报错了?请提供包含错误的完整堆栈转储。
  • mail.attachments['test.txt'] = File.read("#{Rails.root}/public/test.txt")
  • 这很奇怪,因为我可以将所有这些行逐字输入 Rails 控制台,然后我会返回一个带有附件的 Mail 对象。不知道该告诉你什么。你是如何运行你的代码的?您是否尝试过运行 Rails 控制台并一次输入一行?
猜你喜欢
  • 1970-01-01
  • 2012-01-06
  • 1970-01-01
  • 2021-10-24
  • 2016-10-23
  • 1970-01-01
  • 2017-08-21
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多