在Rails中使用SendGrid为邮件添加附件时遇类型错误
解决SendGrid添加附件时的TypeError问题
你这是把Rails Action Mailer的附件写法直接套到SendGrid的Ruby SDK上了,这就是报错的根源!
错误原因分析
你用的mail.attachments['test.txt'] = File.read(...)是Rails内置Action Mailer的用法——它的attachments是哈希结构。但SendGrid的Ruby库(sendgrid-ruby)里,mail.attachments是数组类型,当你用字符串作为"索引"赋值时,Ruby会尝试把字符串转成整数(数组只认整数索引),于是就触发了TypeError - no implicit conversion of String into Integer这个错误。
正确的实现方式
SendGrid要求你先创建一个Attachment对象,配置好必要属性后,把它添加到attachments数组里。而且附件内容必须经过Base64编码,这是SendGrid的硬性要求。
修改你的hello_world方法如下:
def hello_world require 'sendgrid-ruby' include SendGrid require 'base64' # 确保引入Base64编码模块 # 基础邮件配置 from = Email.new(email: '你的发件邮箱@example.com') to = Email.new(email: '收件人邮箱@example.com') subject = '测试带附件的SendGrid邮件' content = Content.new(type: 'text/plain', value: '这是一封带有附件的测试邮件') # 构造附件 file_path = "#{Rails.root}/public/test.txt" # 读取文件内容并做Base64编码 encoded_file_content = Base64.strict_encode64(File.read(file_path)) attachment = Attachment.new( filename: 'test.txt', # 收件人看到的附件文件名 content: encoded_file_content, # 必须是Base64编码后的字符串 type: 'text/plain', # 文件的MIME类型,根据实际文件调整(比如PDF用application/pdf) disposition: 'attachment' # 标记为附件,而非内嵌资源 ) # 创建邮件对象并添加附件 mail = Mail.new(from, subject, to, content) mail.attachments << attachment # 把附件追加到数组中 # 发送邮件 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 end
额外注意事项
- 确保你已经安装了
sendgrid-rubygem,并且配置了正确的SendGrid API密钥(建议存在环境变量SENDGRID_API_KEY中) - 确认
public/test.txt文件真实存在,否则File.read会抛出文件不存在的错误 - 根据附件的实际类型调整
type参数的MIME值,比如JPG图片用image/jpeg,Excel文件用application/vnd.openxmlformats-officedocument.spreadsheetml.sheet等
内容的提问来源于stack exchange,提问作者Pimmesz
相关产品推荐
相关产品推荐

