0

Let's say I have two machines A and B

On A I have installed and configured a SMTP and IMAP server

For example I have user: george with password: 123456 on Machine A

I am trying to write a shell script which will be executed from Machine B and will read the last email user george received and display to STDOUT.

As far as I know in order to be read by the IMAP server the messages should be delivered in Maildir format.

  • What's the question? – Minos Jan 13 '15 at 21:04
  • How to read user last email using a shell script? – Adrian George Jan 13 '15 at 21:06
  • Such a script would implement a part of the IMAP protocol including authentication. It would be pretty daunting to write that as a script (perhaps with calls to netcat?). A python or perl program would make more sense. – Jos Jan 13 '15 at 21:33
2

Welcome to the wonderful hell of IMAP ;-)
You can use python to do that:

#!/usr/bin/env python
# -*- coding: utf-8 -*-

from __future__ import unicode_literals

from email.parser import HeaderParser

import imaplib, email, re

list_response_pattern = re.compile(r'\((?P<flags>.*?)\) "(?P<delimiter>.*)" (?P<name>.*)')

def parse_list_response(line):
    flags, delimiter, mailbox_name = list_response_pattern.match(line).groups()
    return (flags, delimiter, mailbox_name)

# Add your data here
HOST = 'server.de'
USERNAME = 'user'
PASSWORD = 'password'

server = imaplib.IMAP4(HOST) # connect
server.login(USERNAME, PASSWORD) # login
server.select('INBOX',readonly=True) # select mailbox aka folder

result, data = server.search(None, "ALL") # search emails

ids = data[0] # data is a list.
id_list = ids.split() # ids is a space separated string
latest_email_id = id_list[-1] # get the latest
result, data = server.fetch(latest_email_id, "(RFC822)") # fetch email

for response_part in data:
    if isinstance(response_part, tuple):
        msg = email.message_from_string(response_part[1])
        varSubject = msg['subject']
        varFrom = msg['from']
        varDate = msg['Date']

        print varDate + " " + varFrom.split()[-1] + " " + varSubject

server.close()
server.logout()
  • This is good place to start for anyone interested in doing what I was trying to do. – Adrian George Mar 30 '16 at 13:03
0

Why not try out shell-based mail clients, e.g. mh and mutt - I'm confident there are more of them if none of these suit your needs.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.