简体   繁体   中英

How can I parse the full name from an email using Ruby?

I'm trying to extract information from email messages. I have a list of .eml files and have a ruby program to read in each message, then print the output.

Here's my code so far:

#!/usr/bin/env ruby
require 'mail'
basedir = '.'
files = Dir.glob("*.eml")
files.each do |i|
  mail = Mail.read(i)
  puts "filename: #{i}"
  puts "from: #{mail.from}"
  puts "to: #{mail.to}"
end

It works, but I'm trying to get the full name from the email addresses as well. So instead of just "bobloblaw@example.com" I'm trying to get "<Bob Loblaw> bobloblaw@example.com" .

You should be able to use the display_names property like so:

mail[:from].display_names.first
mail[:to].display_names.first

Note that display_names is an array as a message can have more than one recipient. The code above would get you the first name.

You can directly access the header to retrieve this information.

mail.header[:from].formatted

See common_address.rb for more methods.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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