[imap] configurable content-type selection for multipart messages

User can now select which content-type in multipart messages should be
used as the event message.  Default behavior for multipart messages is
still to select first part with text/plain content-type.
This commit is contained in:
Brad Fritz 2013-11-18 14:01:14 -05:00
parent 4a035d295f
commit 8b5c78c8ff
2 changed files with 54 additions and 1 deletions

View file

@ -24,6 +24,10 @@ class LogStash::Inputs::IMAP < LogStash::Inputs::Base
config :check_interval, :validate => :number, :default => 300 config :check_interval, :validate => :number, :default => 300
config :delete, :validate => :boolean, :default => false config :delete, :validate => :boolean, :default => false
# For multipart messages, use the first part that has this
# content-type as the event message.
config :content_type, :validate => :string, :default => "text/plain"
public public
def register def register
require "net/imap" # in stdlib require "net/imap" # in stdlib
@ -36,6 +40,8 @@ class LogStash::Inputs::IMAP < LogStash::Inputs::Base
@port = 143 @port = 143
end end
end end
@content_type_re = Regexp.new("^" + @content_type)
end # def register end # def register
def connect def connect
@ -79,7 +85,7 @@ class LogStash::Inputs::IMAP < LogStash::Inputs::Base
message = mail.body.decoded message = mail.body.decoded
else else
# Multipart message; use the first text/plain part we find # Multipart message; use the first text/plain part we find
part = mail.parts.find { |p| p.content_type =~ /^text\/plain/ } || mail.parts.first part = mail.parts.find { |p| p.content_type.match @content_type_re } || mail.parts.first
message = part.decoded message = part.decoded
end end

47
spec/inputs/imap.rb Normal file
View file

@ -0,0 +1,47 @@
require "logstash/inputs/imap"
require "mail"
describe LogStash::Inputs::IMAP do
user = "logstash"
password = "secret"
msg_time = Time.new
msg_text = "foo\nbar\nbaz"
msg_html = "<p>a paragraph</p>\n\n"
msg = Mail.new do
from "me@example.com"
to "you@example.com"
subject "logstash imap input test"
date msg_time
body msg_text
add_file :filename => "some.html", :content => msg_html
end
context "with both text and html parts" do
context "when no content-type selected" do
it "should select text/plain part" do
config = {"type" => "imap", "host" => "localhost",
"user" => "#{user}", "password" => "#{password}"}
input = LogStash::Inputs::IMAP.new config
input.register
event = input.parse_mail(msg)
insist { event["message"] } == msg_text
end
end
context "when text/html content-type selected" do
it "should select text/html part" do
config = {"type" => "imap", "host" => "localhost",
"user" => "#{user}", "password" => "#{password}",
"content_type" => "text/html"}
input = LogStash::Inputs::IMAP.new config
input.register
event = input.parse_mail(msg)
insist { event["message"] } == msg_html
end
end
end
end