简体   繁体   English

将邮件消息附加到 Rails 中的邮件

[英]Attach mail message to mail in Rails

In a Rails 5.1 ActionMailer, I want to attach a Mail object to an e-mail:在 Rails 5.1 ActionMailer 中,我想将 Mail 对象附加到电子邮件:

def attach_mail(original_email)
  attachments['original-email.eml'] = { mime_type: 'message/rfc822', encoding: '7bit', content: original_email.to_s }
  mail to: 'postmaster', subject: 'mail should be attached'
end

However, this does not produce valid e-mails.但是,这不会产生有效的电子邮件。 Thunderbird lists the attachment with size '0'. Thunderbird 列出了大小为“0”的附件。 Horde lists the attachment with correct size, but does not recognize it as an e-mail. Horde 列出了大小正确的附件,但无法将其识别为电子邮件。

I've tried variations of the attachments line:我尝试了attachments行的变体:

attachments['original-email.eml'] = original_email
attachments['original-email.eml'] = { content: original_email.to_s }
attachments['original-email.eml'] = { mime_type: 'message/rfc822', content: original_email.to_s }

but none of these result in an e-mail with an e-mail attachment.但这些都不会产生带有电子邮件附件的电子邮件。

What's the solution?解决办法是什么?

Finally figured it out.终于想通了。

To attach an email (Mail object from the 'mail' gem) to an ActionMailer message, you need to specify the MIME type and encoding like so:要将电子邮件(来自“邮件”gem 的邮件对象)附加到 ActionMailer 消息,您需要指定 MIME 类型和编码,如下所示:

def attach_mail(original_email)
  attachments['original-email.eml'] = { mime_type: 'message/rfc822', 
    encoding: '7bit',
    content: original_email.to_s }
  mail to: 'postmaster', subject: 'mail should be attached'
end

This creates a multipart/mixed message which is properly displayed in MUAs.这将创建一个在 MUA 中正确显示的multipart/mixed消息。

However, if you happen to add any inline attachment (eg to display a logo image in the ActionMailer e-mail body), the entire message will have a multipart/related mime type.但是,如果您碰巧添加了任何内嵌附件(例如,在 ActionMailer 电子邮件正文中显示徽标图像),则整个邮件将具有multipart/related MIME 类型。 The MUAs that I tried were unable to interpret a multipart/related message with an e-mail attachment.我尝试过的 MUA 无法解释带有电子邮件附件的multipart/related消息。

Therefore, refrain from adding any inline attachments when attaching an e-mail to an e-mail.因此,在将电子邮件附加到电子邮件时不要添加任何内嵌附件。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM