我正在尝试使用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
之前是否有人遇到此错误?
答案 0 :(得分:0)
根据docs,通常你会使用Hash创建一个新的Mail
对象,其值为Strings。这很难说,因为我不知道你的Email
或Content
课程在做什么,但我怀疑你创建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)