Search code examples
pythonemailstdin

Python: Not able to parse email message piped to stdin


I'm piping an email message from Pigeonhole to the Python script using Sieve filters which looks like

#!/usr/bin/python
import sys
import os
import email

input = sys.stdin

#For manual testing 
#input=open(sys.argv[2]).read()

msg=email.message_from_string(input)

But it fails with the error below

Sep 21 11:41:24 lmtp: Error: Traceback (most recent call last):
Sep 21 11:41:24 lmtp: Error: File "message-processor.py", line 11, in <module>
Sep 21 11:41:24 lmtp: Error: msg=email.message_from_string(input)
Sep 21 11:41:24 lmtp: Error: File "/usr/lib64/python2.6/email/__init__.py", line 57, in message_from_string
Sep 21 11:41:24 lmtp: Error: return Parser(*args, **kws).parsestr(s)
Sep 21 11:41:24 lmtp: Error: File "/usr/lib64/python2.6/email/parser.py", line 82, in parsestr
Sep 21 11:41:24 lmtp: Error: return self.parse(StringIO(text), headersonly=headersonly)
Sep 21 11:41:24 lmtp: Error: TypeError: expected read buffer, file found

It works fine when i use email saved as a file but not piped in.

Any tips on that?


Solution

  • I have switched to email.parser which do the job

    #!/usr/bin/python
    import sys
    import os
    import email
    import email.parser
    
    input = sys.stdin
    
    #For manual testing 
    #input=open(sys.argv[2]).read()
    
    msg = email.parser.Parser().parse(input)