Rails - 邮件,以纯文本形式获取身体 [英] Rails - Mail, getting the body as Plain Text

查看:188
本文介绍了Rails - 邮件,以纯文本形式获取身体的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

给出: message = Mail.new(params [:message])



如下所示:< a href =http://docs.heroku.com/cloudmailin =noreferrer> http://docs.heroku.com/cloudmailin



它展示了如何将message.body作为HTML,如何获得纯文本/文本版本?



谢谢
<上面的代码:

  message = Mail.new( params [:message])

会创建一个新的 mail gem 。然后,您可以使用该消息中的任何方法来获取内容。因此,您可以使用以下方式获取纯文本内容:

  message.text_part 

或HTML与

  message.html_part 

这些方法只是猜测并找到text / plain或text / html内容类型的多部分消息中的第一部分。 CloudMailin也通过params [:plain]和params [:html]提供了这些方便的方法。值得记住的是,这个消息永远不会保证有一个纯文本或html部分。可能值得使用类似下面的内容来确保:

  plain_part = message.multipart? ? (message.text_part?message.text_part.body.decoded:nil):message.body.decoded 
html_part = message.html_part? message.html_part.body.decoded:nil

作为附注,提取内容编码也很重要从使用这些方法时的消息中,确保输出编码为您所需的编码方法(如UTF-8)。


Given: message = Mail.new(params[:message])

as seen here: http://docs.heroku.com/cloudmailin

It shows how to get the message.body as HTML, how to do you get the plain/text version?

Thanks

解决方案

The code above:

message = Mail.new(params[:message])

will create a new instance of the mail gem from the full message. You can then use any of the methods on that message to get the content. You can therefore get the plain content using:

message.text_part

or the HTML with

message.html_part

These methods will just guess and find the first part in a multipart message of either text/plain or text/html content type. CloudMailin also provides these as convenience methods however via params[:plain] and params[:html]. It's worth remembering that the message is never guaranteed to have a plain or html part. It may be worth using something like the following to be sure:

plain_part = message.multipart? ? (message.text_part ? message.text_part.body.decoded : nil) : message.body.decoded
html_part = message.html_part ? message.html_part.body.decoded : nil

As a side note it's also important to extract the content encoding from the message when you use these methods and make sure that the output is encoded into the encoding method you desire (such as UTF-8).

这篇关于Rails - 邮件,以纯文本形式获取身体的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆