ruby-on-rails - 使用 Rails 使用 SendGrid 将附件添加到电子邮件
问题描述
我创建了一个使用 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
解决方案
根据 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)
推荐阅读
- r - 使用因素:将两个函数放入 dplyr
- typescript - TypeScript:即使 strictNullChecks 为假,我是否可以检查类型是否包含未定义?
- ruby - 在 /tmp/vagrant-puppet 找不到课程
- sqlite - 颤振 | 行太大而无法放入 CursorWindow
- python - 发送消息时禁用登录 Flask-Mail
- django - 使用 djangosaml2 实现 SSO 时出现验证错误 'is_staff': ["'true' value must be True or False."]
- vba - 在 VBA for Outlook 的另一个子中调用函数
- cypress - 柏树访问未捕获参考
- mysql - mysql date_format() 或 str_to_date() 在 where 子句中
- java - 初学者Java工资单程序,带有嵌套if else if控件的While循环,需要计算有多少“是”答案