user3612491
user3612491

Reputation: 233

Ruby: how to parse e-mail mime from the stdin

Anyone know how I can parse the E-mail MIME from Ruby when the input is from STDIN? I have found a gem called "mail" which looks really nice but so far as I can see it's able to read a mail only from the file:

require 'mail'
mail = Mail.read('/path/to/message.eml')

This is how I'm testing it:

# First one is from stdin:
require 'mail'
mail = Mail.new($stdin.readlines)
p mail.from
p mail.to

returns: nil nil

# This one is from the file:
mail2 = Mail.new("my_email.txt")
p mail2.from
p mail2.to

returns: nil nil

# The same file but I'm using Mail.read:
mail3 = Mail.read("my_email.txt")
p mail3.from
p mail3.to

returns: ["[email protected]"] ["[email protected]"]

STDIN I'm testing like:

# cat my_email.txt | ruby code.rb

So the method Mail.read works fine with my e-mail, but when I want to put my stdin to the Mail.read I have:

mail/mail.rb:176:in `initialize': no implicit conversion of Array into String (TypeError)

I know that I can save that file from stdin to the temp folder and then open it by Mail.read but I don't want to do this in that way since it will be slow.

The full url to the gem is: https://github.com/mikel/mail

Upvotes: 2

Views: 1173

Answers (2)

Luc
Luc

Reputation: 153

readlines returns an array... of lines! You might want to try read on ARGF which is the input provided by $stdin instead.

mail = Mail.new ARGF.read

See the relevant documentation.

Upvotes: 4

Amadan
Amadan

Reputation: 198324

IO#readlines produces an array. You want a string there:

# readmail.rb
require 'mail'
mail = Mail.new(STDIN.read)
p mail.from
p mail.to

# mail.eml
From: [email protected]
To: [email protected]
Subject: This is an email

This is the body

# command line
$ ruby readmail.rb < mail.eml
# => ["[email protected]"]
# => ["[email protected]"]

Upvotes: 2

Related Questions