Rails ActionMailer - 附加文本文件会导致电子邮件正文作为附件发送

问题描述 投票:1回答:2

当我尝试将文本文件(带有.txt扩展名)附加到电子邮件时,电子邮件将在没有正文和附加附件的情况下发送:noname.html。此文件包含我希望在电子邮件正文中获得的内容。当我将文件的扩展名更改为.txt以外的其他内容并附加它时,问题不会发生。

调查电子邮件的mimeparts显示文本附件mimepart出现在html mimepart之前,我想成为电子邮件的正文。但是,我不确定mimeparts的顺序是否会导致问题。

我创建电子邮件的代码如下所示:

render_to_string # Using a template
attachments[name] = File.read...
mail(options)

将此添加到options参数没有帮助:

content_type: 'multipart/alternative',
parts_order: [ 'text/html', 'text/enriched', 'text/plain' ] 

这个问题的原因是什么?如何强制html部分成为电子邮件的正文?

ruby-on-rails email actionmailer
2个回答
0
投票

我通过附加mime类型text/x-diff的文本文件来解决这个问题:

mime_type = ... # Get mime type, e.g.: Paperclip::ContentTypeDetector.new(attachment_file_name).detect
mime_type = mime_type == 'text/plain' ? 'text/x-diff' : mime_type
attachments[attachment_file_name] = { content: File.read..., mime_type: mime_type }

通过用text/plain交换mime类型text/x-diff,文本文件附件不会被混淆为身体。它已正确附加到电子邮件,并且电子邮件正文作为正文正确发送。


0
投票

对于Rails 4/5只需使用

render_to_string mail.attachments[name] = File.read... mail(options)

添加邮件。附件解决问题。

© www.soinside.com 2019 - 2024. All rights reserved.