使用Rails通过SendGrid添加附件到电子邮件

3
我已经创建了一个使用Sendgrid发送电子邮件的hello_world方法。我正在尝试包含一个附件。我在另一个stackoverflow答案中找到了以下行:mail.attachments['test.txt'] = File.read("#{Rails.root}/public/test.txt") 然而,这会生成以下错误:
Completed 500 Internal Server Error in 17ms (ActiveRecord: 3.4ms)



TypeError - no implicit conversion of String into Integer:
  app/controllers/messages_controller.rb:32:in `hello_world'
  app/controllers/messages_controller.rb:65:in `create'

在控制器中邮寄代码:

  def hello_world(company, message)
    from = Email.new(email: "test+#{current_user.auth_token}@example.com")
    to = Email.new(email: 'hello@pim.gg')

    subject = 'TEST from dev'
      content = Content.new(type: 'text/plain', value: "#{company.email} #{current_user} #{current_user.first_name} #{current_user.last_name} #{message.text}")

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

    sg = SendGrid::API.new(api_key: ENV['SENDGRID_API_KEY'])
    response = sg.client.mail._('send').post(request_body: mail.to_json)
    puts response.status_code
    puts response.body
    puts response.headers
  end
1个回答

4
根据sendgrid-ruby gem的文档,添加附件的方法如下:
attachment = SendGrid::Attachment.new
attachment.content = Base64.strict_encode64(File.open(fpath, 'rb').read)
attachment.type = 'application/vnd.openxmlformatsofficedocument.spreadsheetml.sheet'
attachment.filename = fname
attachment.disposition = 'attachment'
attachment.content_id = 'Reports Sheet'
mail.add_attachment(attachment)

似乎是在语法上出了问题...NameError - 未定义的局部变量或方法 fpath' for #<MessagesController:0x00007fed4a53c228>: app/controllers/messages_controller.rb:34:in 'hello_world' app/controllers/messages_controller.rb:72:in 'create' - Pimmesz
1
fpath = "#{Rails.root}/public/test.txt" fname = 'test.txt' attachment.type = 'text/html' - Artem Dorodovskyi
SendGrid不是Sendgrid,我花了一段时间才弄清楚。 - Sebastián Palma

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接