Skip to content

Commit

Permalink
[imap] configurable content-type selection for multipart messages
Browse files Browse the repository at this point in the history
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.
  • Loading branch information
bfritz committed Nov 18, 2013
1 parent 4a035d2 commit 8b5c78c
Show file tree
Hide file tree
Showing 2 changed files with 54 additions and 1 deletion.
8 changes: 7 additions & 1 deletion lib/logstash/inputs/imap.rb
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,10 @@ class LogStash::Inputs::IMAP < LogStash::Inputs::Base
config :check_interval, :validate => :number, :default => 300
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
def register
require "net/imap" # in stdlib
Expand All @@ -36,6 +40,8 @@ def register
@port = 143
end
end

@content_type_re = Regexp.new("^" + @content_type)
end # def register

def connect
Expand Down Expand Up @@ -79,7 +85,7 @@ def parse_mail(mail)
message = mail.body.decoded
else
# 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
end

Expand Down
47 changes: 47 additions & 0 deletions spec/inputs/imap.rb
Original file line number Diff line number Diff line change
@@ -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 "[email protected]"
to "[email protected]"
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

0 comments on commit 8b5c78c

Please sign in to comment.