Python script for email notifications on Linux desktop

Since I switched from KDE to XFCE, I had to setup everything again in order to get the functionality I was getting through KDE’s widgets and other tools. I got most of it through the XFCE panel’s widgets and Conky, but for some reason, the XFCE’s email checker doesn’t work for me. I am setting it up and seems to connect, but there are no notifications coming. No errors are shown in the logs, so I guess it might be either a small bug or it finds it hard for some reason to cooperate with my server.

To cut the long story short, I ended up using the following python script for doing the work. It is a ‘quick and dirty’ solution. I ‘m no python expert so there is high enough possibility there is some nonsense there! To use it, you will need of course to put your real username, password and imap server address (e.g. your gmail).


import imaplib
import re
import time
import subprocess

## enter your account details bellow!
imapServer = "imap.server.com"
port = "993"
username = "yourUserName"
password = "yourPassword"

##how often to check? give interval in seconds! Checking too often might affect performance and stability.
checkIntevaral = 120

Mailbox = imaplib.IMAP4_SSL(imapServer, port)
rc,resp = Mailbox.login(username,password)
if rc == 'OK':
    print("Connected to mail-server "+imapServer)
    rc, message = Mailbox.status('INBOX', "(UNSEEN)")
    unreadCount = int(re.search("UNSEEN (\d+)",str( message[0])).group(1))
    oldValue = 0
    file = open("/tmp/mailnotify.tmp", "w+")
    file.write(str(unreadCount))    
    file.close
    while(1):
        rc, message = Mailbox.status('INBOX', "(UNSEEN)")
        unreadCount = int(re.search("UNSEEN (\d+)",str( message[0])).group(1))
        file = open("/tmp/mailnotify.tmp", "r+")
        oldValue = int(file.readline())
        file.close()
        if (unreadCount>oldValue):
            subprocess.call(["notify-send", "-u", "low", "-t", "5000", "New email!" ,"You have "+str(unreadCount)+" unread "+ "emails!" if unreadCount > 1 else "email!", "--icon=email"])
        if oldValue != unreadCount:
            file = open("/tmp/mailnotify.tmp", "w+")
            file.write(str(unreadCount))    
            file.close()
        time.sleep(checkIntevaral)
else :
    print('Fail to connect')
Mailbox.logout()
file.remove()

Save this as checkMail.py and run is through your terminal:

python checkMail.py

When you run it like that, if it connects successfully it will return a success message, otherwise you’ll get an error.

When you get a new email, the script will send a desktop notification informing you how many unread emails you have in your inbox.The python script will store the number of unread emails to a temporary file in your /tmp/ directory, called “mailnotify.tmp”. If you use conky, like I do, it is then easy to put the two things together and have a counter on your desktop, like the following:

script output on conky
script output on conky

There you go, you have email notifications and unread emails counter on your desktop!

PS: I am no Python expert and as I said, the script is a “quick and dirty” one! If you notice something weird, or have suggestions or improvements, please throw a comment!

4 thoughts on “Python script for email notifications on Linux desktop”

  1. Thanks for the script! It worked perfectly for me without any changes (besides username and password). Thank!

    1. I am glad it worked for you! I hope I get the time to post some more scripts /code snippets or tutorials.

      Best ,

      N

  2. Hello,

    Excellent script, I am also a newbie to python. I had a few questions, but I have already answered my first one.

    1. How to keep this file secure – with the password in plain text.
    Answer: I found this website: http://enscryption.com/ witch allowed me to completely obscure the code. 🙂

    2. What if you have two factor authentication setup on your email accounts say gmail? Do you know or have you found a way to script this into the python script?

    1. Hey!
      I am glad you found it useful! Thanks for stopping-by and commenting 🙂
      1 )Regarding security and code-obfuscating: It all depends on the level of security you want to achieve. My whole HD and my home partition are encrypted. I consider it “OK”, as when I am logged in (and my home partition is decrypted), I am on the pc myself. Consequently, my whole home folder is exposed anyway…
      If you need additional security, then I would consider another solution as in my humble opinion, code obfuscating is not a the way to go… I suggest you just add an input-field popup asking for the password instead. You can use something like Zenity https://en.wikipedia.org/wiki/Zenity for it.
      You would have to just replace the hard-coded values part with something like the following:

      output = subprocess.check_output([“zenity”, “–username”, “–password”])
      vals = output.split(“|”);
      username = vals[0]
      password = vals[1]

      What this does is take the values the user types in the dialog as an array, split it, and wooosh, go! This is only an example I am giving, you should work on it a bit, but I hope you now know where to start.
      If you do it, it would be nice if you just write here and let me know if and how it works 🙂
      2) Regarding gmail’s 2 factor auth: I am not using gmail and I haven’t looked into it, so sorry… Once again, if/when you fix it, please drop a word! More people might find it interesting. If I get the time I might have a look into it myself at some point – but please don’t count on it!

      Best,
      N

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.