#!/usr/bin/python

# Simple email checker
#
# Wrote by copycat-killer on a rainy day of august 2013
# to be used in Lain. 
#
# https://github.com/copycat-killer/lain

import sys, getopt, locale, imaplib

def main(argv):
   usage    = "usage: checkmail -s <imapserver> -u <usermail> -p <password> [--port <port>] [--encoding <encoding>] [--cut]"
   server   = ""
   user     = ""
   password = ""
   port     = 993
   cut      = False
   encoding = locale.getdefaultlocale()[1]
   output   = ""

   try:
       opts, args = getopt.getopt(argv, "hs:u:p:", ["port=", "encoding=", "cut"])
   except getopt.GetoptError:
      print(usage)
      sys.exit(2)

   if len(argv) == 0:
      print(usage)
      sys.exit()

   for opt, arg in opts:
      if opt == "-h":
         print(usage)
         sys.exit()
      elif opt == "-s":
         server = arg
      elif opt == "-u":
         user = arg
      elif opt == "-p":
         password = arg
      elif opt == "--port":
         port = int(arg)
      elif opt == "--cut":
         cut = True
      elif opt == "--encoding":
         encoding = arg

   try:
      mail = imaplib.IMAP4_SSL(server, port)
      mail.login(user, password)
   except imaplib.IMAP4.error:
      print("CheckMailError: invalid credentials")
      sys.exit(2)

   status, counts = mail.status("Inbox","(MESSAGES UNSEEN)")

   unread = int(counts[0].split()[4][:-1])

   if status == "OK" and unread:
      mail.select("Inbox", readonly = 1)
      ret, messages = mail.uid("search", None, "(UNSEEN)")

      if ret == "OK":
          latest_email_uid = messages[0].split()[-1]

          ret_header, new_mail_header = mail.uid("fetch", latest_email_uid,
                                                 "(BODY.PEEK[HEADER.FIELDS (SUBJECT FROM)])")
          ret_text, new_mail_text = mail.uid("fetch", latest_email_uid, "(BODY[TEXT])")

          if ret_header == "OK" and ret_text == "OK":
              try: # not all the servers like this, that's why we try
                  mail.store(latest_email_uid, "-FLAGS", "\\Seen")
              except imaplib.IMAP4.error:
                  # this simply means the server refused to
                  # toggle Seen flag from mail
                  print("[+Seen]\n")

              nm_header = new_mail_header[0][1].decode(encoding, "replace").strip()
              nm_text = new_mail_text[0][1].decode(encoding, "replace").strip()

              if unread == 1:
                  print(user, "has 1 new message\n")
              else:
                  print(user, "has", unread, "new messages\n")
                  nm_header.replace("From:", "Latest from:", 1)

              print(nm_header, "\n")

              if cut:
                  if len(nm_text) <= 100:
                      print(nm_text)
                  else:
                      print(nm_text[0:100])
                      print("[...]")
              else:
                  print(nm_text)
   else:
      print("No new messages")

   mail.logout()

if __name__ == "__main__":
   main(sys.argv[1:])