2

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: ["test@gmail.com"] ["test2@gmail.com"]

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

user3612491
  • 223
  • 3
  • 7

2 Answers2

4

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.

Luc
  • 143
  • 6
2

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: bob@test.lindsaar.net
To: mikel@test.lindsaar.net
Subject: This is an email

This is the body

# command line
$ ruby readmail.rb < mail.eml
# => ["bob@test.lindsaar.net"]
# => ["mikel@test.lindsaar.net"]
Amadan
  • 191,408
  • 23
  • 240
  • 301