【问题标题】:Rails mail attachment is in e-mail bodyRails 邮件附件在电子邮件正文中
【发布时间】:2018-11-09 05:55:36
【问题描述】:

我需要发送带有附件的简单邮件。现在它发送一封电子邮件,但附件是这样的电子邮件正文。

--
Content-Type: text/csv;
 charset=UTF-8
Content-Transfer-Encoding: 7bit
Content-Disposition: attachment;
 filename=errors_in_address_table.csv
Content-ID: <5b0e7d6b4abff_10c12ac224c8b0d4994d@development.mail>

发送电子邮件的当前代码

saved_file = Rails.root.join('db', 'fix_db', 'errors_in_address_table.csv')
mailer = ActionMailer::Base.mail(from: 'no-replay@test.com', to: 'test@test.com', subject: 'Errors in database', body: '', content_type: 'multipart/mixed')
mailer.attachments['errors_in_address_table.csv'] = { mime_type: 'text/csv', content: File.read(saved_file) }
mailer.deliver

我试图让它正常工作几个小时。也许一些更有经验的程序员可以帮助我。

【问题讨论】:

  • 我不知道你所说的“在电子邮件正文中”是什么意思,也许因为你的邮件客户端显示它以某种方式内联而令人困惑?但从 EML 我可以说它是作为附件存储的
  • @siegy22 发送邮件后,我在正文部分收到了包含此文本的电子邮件。
  • 你能上传你的电子邮件吗? .eml 文件?

标签: ruby-on-rails ruby email sendmail ruby-on-rails-4.2


【解决方案1】:

对于遇到此问题的其他人,这应该可以从 Rails 控制台工作(至少在 Rails 6+ 中):

mailer = ActionMailer::Base.new
mailer.attachments['errors_in_address_table.csv'] = File.read(saved_file)
mailer.mail(from: 'from@test.com', to: 'to@test.com', subject: 'Errors', body: '').deliver

【讨论】:

    【解决方案2】:

    我的应用中有一些不同的附件代码,我不确定这是否适合您,但您可以尝试一下。

    尝试替换你的块

    saved_file = Rails.root.join('db', 'fix_db', 'errors_in_address_table.csv')
    mailer = ActionMailer::Base.mail(from: 'no-replay@test.com', to: 'test@test.com', subject: 'Errors in database', body: '', content_type: 'multipart/mixed')
    mailer.attachments['errors_in_address_table.csv'] = { mime_type: 'text/csv', content: File.read(saved_file) }
    mailer.deliver
    

    下面这个比较简单:

    attachments['errors_in_address_table.csv'] = open(Rails.root.join('db', 'fix_db', 'errors_in_address_table.csv')).read
    mail(from: 'no-replay@test.com', to: 'test@test.com', subject: 'Errors in database', body: '')
    

    这实际上是一种试错法。不行的话我就删了。

    你也有你的邮件的看法吗?

    【讨论】:

    • 不,我没有查看邮件。我需要让它尽可能简单。我可以在不添加邮件视图的情况下这样做吗?
    【解决方案3】:

    根据分享的描述,您似乎需要修改附件代码

    saved_file = Rails.root.join('db', 'fix_db', 'errors_in_address_table.csv')
    mailer = ActionMailer::Base.mail(from: 'no-replay@test.com', to:    'test@test.com', subject: 'Errors in database', body: '', content_type: 'multipart/mixed')
    mailer.attachments['errors_in_address_table.csv'] = saved_file
    mailer.deliver
    

    【讨论】:

    • 你能描述一下你改变了什么以及为什么?
    • mailer.attachments['errors_in_address_table.csv'] = saved_file #更改了这一行
    • api.rubyonrails.org/v5.0/classes/ActionMailer/…中所说,mail.attachments['filename.jpg'] = File.read('/path/to/filename.jpg') 需要在附件中指定文件路径
    • 是的..我也写过同样的东西.. mail.attachments['filename.jpg'] = File.read('/path/to/filename.jpg')
    猜你喜欢
    • 2012-09-07
    • 2018-07-24
    • 1970-01-01
    • 2021-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-12-12
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多