如何使用 Rails3 应用程序解析电子邮件正文中的文本?

发布于 2024-11-08 06:48:15 字数 375 浏览 0 评论 0原文

我需要从转发的电子邮件中获取姓名和电子邮件地址,其中正文中有这样一行:

From: john smith <[email protected]>

执行此操作的最佳方法是什么?我应该使用一个好的图书馆/宝石吗?

此外,该行会因发送的电子邮件客户端以及语言而异,因此我需要一种更可靠的方法,而不仅仅是匹配该字符串。

另外,有些客户不包括姓名,而只包括电子邮件地址,所以我需要能够处理这个问题。

I need to get the name and email address from a forwarded email where there is a line like this in the body:

From: john smith <[email protected]>

What is the best way to do this? Is there a good library/gem I should use?

Also this line will vary from which email client it's sent from and also what language, so I need a more robust way than just matching just this string.

Also some clients do not include the name but just the email address on this line so I need to be able to handle that.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

沙与沫 2024-11-15 06:48:15
require 'mail'  # only needed for non-Rails
m = Mail.new( "any RFC-conforming email including headers" )
puts m[:from].display_names.first
puts m[:from].addresses.first

Mail 对象会自动包含在使用 ActionMailer 的 Rails 项目中 - 但如果您不这样做,则需要将其添加到 Gemfile 中使用 ActionMailer

更新

我没有正确阅读OP的问题 - 他们想从转发邮件的正文中获取电子邮件地址。我只是使用一些正则表达式:

name, email = m.body.match( /^\s*From:\s*(.*)\s+<(.*)>$/)[1,2]

注意:这对电子邮件的结构进行了相当多的假设 - 纯 HTML 电子邮件可以轻松阻止此正则表达式。

require 'mail'  # only needed for non-Rails
m = Mail.new( "any RFC-conforming email including headers" )
puts m[:from].display_names.first
puts m[:from].addresses.first

The Mail object is automatically included in Rails projects that use ActionMailer - but you'll need to add it to your Gemfile if you're not using ActionMailer

Update

I didn't read the OP's question properly - they want to get an email address from the body of a forwarded mail. I'd just use some regex:

name, email = m.body.match( /^\s*From:\s*(.*)\s+<(.*)>$/)[1,2]

NB: this assumes a fair amount about the structure of the email - an HTML-only email can easily thwart this regex.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文