Skip to content

Instantly share code, notes, and snippets.

@scturtle
Last active December 8, 2018 04:42
Show Gist options
  • Save scturtle/4369460 to your computer and use it in GitHub Desktop.
Save scturtle/4369460 to your computer and use it in GitHub Desktop.
a mail checker on the system tray (pyqt)
# coding: utf-8
import logging
import os, sys, json
from PyQt4 import QtGui
from PyQt4.QtCore import QTimer
import imaplib, StringIO, rfc822
from email.Header import decode_header
_config = json.load(open('config.json')) # server, user, pasw
locals().update(_config)
# logging config, disable it by setting level=logging.INFO instead of DEBUG
logging.basicConfig(level=logging.DEBUG, filename='log.txt',
format='%(asctime)s %(levelname)s: %(message)s',
datefmt='%Y-%m-%d %H:%M:%S')
# connect to imap server
server = imaplib.IMAP4_SSL(server, 993)
resp = server.login(user, pasw)
if resp[0] != 'OK':
logging.debug('Login Error!')
exit()
msg = None
def checkmail():
mid = server.select()[1][0] # trick to get the recent mail id
resp, data = server.fetch(mid, "(RFC822.PEEK)") # keep unread
message = rfc822.Message(StringIO.StringIO(data[0][1]))
subject = message['subject']
date = message['date']
# utf-8 decode
if subject.startswith('=?'):
subject = decode_header(subject)[0][0]
# logging
logging.debug("[SUBJECT]: {} [AT]: {}".format(subject, date))
# check with old data
newest = True
if (not os.path.exists('data.json') or
json.load(file('data.json'))['date'] != date):
newest = False
file('data.json', 'w').write(
json.dumps({'date': date,
'subject': subject.decode('GBK')}))
if not newest: # show
msg.lbl.setText('new mail!\n\n{}\n\n{}'.format(subject, date)
.decode('GBK'))
msg.show()
class MsgBox(QtGui.QWidget):
def __init__(self):
super(MsgBox, self).__init__()
self.setGeometry(800, 500, 250, 100)
self.setWindowTitle('New mail!')
self.lbl = QtGui.QLabel('', self)
self.lbl.move(15, 10)
def closeEvent(self, event):
# don't exit
self.hide()
event.ignore()
class SystemTrayIcon(QtGui.QSystemTrayIcon):
def __init__(self, icon, parent=None):
QtGui.QSystemTrayIcon.__init__(self, icon, parent)
self.menu = QtGui.QMenu(parent)
checkAction = self.menu.addAction("Check Now")
checkAction.triggered.connect(checkmail)
exitAction = self.menu.addAction("Exit")
exitAction.triggered.connect(QtGui.qApp.quit)
self.setContextMenu(self.menu)
def main():
global msg
app = QtGui.QApplication(sys.argv)
icon = QtGui.QIcon('mail.ico') # need a icon
trayIcon = SystemTrayIcon(icon)
# checker
timer = QTimer()
timer.timeout.connect(checkmail)
timer.start(30000) # every 30 secs
QTimer.singleShot(3000, checkmail) # check on open
msg = MsgBox()
trayIcon.show()
sys.exit(app.exec_())
if __name__ == '__main__':
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment