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

Rails ActionMailer - Attaching text file causes email body to be sent as attachment

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

调查电子邮件的 mimeparts 表明文本附件 mimepart 出现在 html mimepart 之前,我想将其作为电子邮件的正文。但是,我不确定 mimeparts 的顺序是否导致了问题。

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

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

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

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

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

我通过附加 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 }

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

对于 Rails 4/5 只需使用

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

添加 mail.attachments 解决问题。