File "/home/vastone/gmail_parser.py", line 46, in <module>
f = auth() # Do auth and then get the feed
File "/home/vastone/gmail_parser.py", line 30, in auth
feed = f.read()
File "/usr/lib/python2.7/socket.py", line 355, in read
data = self._sock.recv(rbufsize)
File "/usr/lib/python2.7/ssl.py", line 766, in recv
return self.read(buflen)
File "/usr/lib/python2.7/ssl.py", line 653, in read
v = self._sslobj.read(len)
socket.error: [Errno 0] Error
openssl
python-openssl
python3-openssl
import ssl
ssl.PROTOCOL_SSLv23 = ssl.PROTOCOL_TLSv1
import functools
import ssl
old_init = ssl.SSLSocket.__init__
@functools.wraps(old_init)
def vsido_gmail_bug(self, *args, **kwargs):
kwargs['ssl_version'] = ssl.PROTOCOL_TLSv1
old_init(self, *args, **kwargs)
ssl.SSLSocket.__init__ = vsido_gmail_bug
Traceback (most recent call last):
File "/home/vastone/gmail_parser.py", line 22, in <module>
maxlen = sys.argv[3]
IndexError: list index out of range
File "/home/vastone/gmail_parser.py", line 37
print '${color3} %s new email(s)\n' % (len(atom.entries))
^
SyntaxError: invalid syntax
## check-gmail.py -- A command line util to check GMail -*- Python -*-
## modified to display mailbox summary for conky
# ======================================================================
# Copyright (C) 2006 Baishampayan Ghose <b.ghose@ubuntu.com>
# Modified 2008 Hunter Loftis <hbloftis@uncc.edu>
# Time-stamp: Mon Jul 31, 2006 20:45+0530
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License version 2 as
# published by the Free Software Foundation.
# ======================================================================
import sys
import urllib # For BasicHTTPAuthentication
import feedparser # For parsing the feed
from textwrap import fill
_URL = "https://mail.google.com/gmail/feed/atom"
uname = sys.argv[1]
password = sys.argv[2]
maxlen = sys.argv[3]
urllib.FancyURLopener.prompt_user_passwd = lambda self, host, realm: (uname, password)
def auth():
'''The method to do HTTPBasicAuthentication'''
opener = urllib.FancyURLopener()
f = opener.open(_URL)
feed = f.read()
return feed
def readmail(feed, maxlen):
'''Parse the Atom feed and print a summary'''
atom = feedparser.parse(feed)
print '${color3} %s new email(s)\n' % (len(atom.entries))
for i in range(min(len(atom.entries), maxlen)):
print '${color2}%s' % fill(atom.entries[i].title,38)
#uncomment the following line if you want to show the name of the sender
# print ' ${color2}%s' % atom.entries[i].author
if len(atom.entries) > maxlen:
print ' ${color}more...'
if __name__ == "__main__":
f = auth() # Do auth and then get the feed
readmail(f, int(maxlen)) # Let the feed be chewed by feedparser
python /home/location_of_file/gmail_parser.py yourusername yourpassword
sudo apt-get install python-feedparser
python /home/location_of_file/gmail_parser.py yourusername yourpassword
#! /usr/bin/env python3
import urllib.request
import urllib # For BasicHTTPAuthentication
import feedparser # For parsing the feed
from textwrap import wrap # For pretty printing assistance
import sys
import time
_URL = "https://mail.google.com/gmail/feed/atom/unread"
WRAP_LIMIT = 50
def auth():
username = "your_gmail_username_here"
password = "your_gmail_password_here"
auth_handler = urllib.request.HTTPBasicAuthHandler()
auth_handler.add_password(realm='New mail feed',
uri='https://mail.google.com/',
user= username,
passwd= password)
opener = urllib.request.build_opener(auth_handler)
# ...and install it globally so it can be used with urlopen.
urllib.request.install_opener(opener)
'''The method to do HTTPBasicAuthentication'''
f = opener.open(_URL)
feed = f.read()
return feed
def fill(text, width):
'''A custom method to assist in pretty printing'''
if len(text) < width:
return text + ' '*(width-len(text))
else:
return text
def readmail(feed):
'''Parse the Atom feed and print a summary'''
atom = feedparser.parse(feed)
print ("${color white}You have %s new mails${color} ${alignr}Updated: ${color white}%s" % ((len(atom.entries)), time.strftime("%I:%M")))
for i in range(len(atom.entries)):
if(i>10):
break
if(len(atom.entries[i].title) > WRAP_LIMIT):
#print ("%s" % (fill(wrap(atom.entries[i].title, 50)[0]+" ...", 55)))
print ("${color1}%s" % (wrap(atom.entries[i].title, WRAP_LIMIT)[0]+" ..."))
else:
print ("${color1}%s" % (wrap(atom.entries[i].title, WRAP_LIMIT)[0]))
def countmail(feed):
'''Parse the Atom feed and print a summary'''
atom = feedparser.parse(feed)
print ("Emails: %s new" %len(atom.entries))
if __name__ == "__main__":
f = auth() # Do auth and then get the feed
if(len(sys.argv) > 1):
countmail(f)
else:
readmail(f) # Let the feed be chewed by feedparse
username = "your_gmail_username_here"
password = "your_gmail_password_here"
execpi 600 /path/to/gmail-parser.py
Traceback (most recent call last):
File "./gmail-parser.py", line 5, in <module>
import feedparser # For parsing the feed
ImportError: No module named 'feedparser'
sudo apt-get install python3-feedparser
Traceback (most recent call last):
File "./gmail-parser.py", line 62, in <module>
f = auth() # Do auth and then get the feed
File "./gmail-parser.py", line 30, in auth
f = opener.open(_URL)
File "/usr/lib/python3.5/urllib/request.py", line 472, in open
response = meth(req, response)
File "/usr/lib/python3.5/urllib/request.py", line 582, in http_response
'http', request, response, code, msg, hdrs)
File "/usr/lib/python3.5/urllib/request.py", line 504, in error
result = self._call_chain(*args)
File "/usr/lib/python3.5/urllib/request.py", line 444, in _call_chain
result = func(*args)
File "/usr/lib/python3.5/urllib/request.py", line 696, in http_error_302
return self.parent.open(new, timeout=req.timeout)
File "/usr/lib/python3.5/urllib/request.py", line 472, in open
response = meth(req, response)
File "/usr/lib/python3.5/urllib/request.py", line 582, in http_response
'http', request, response, code, msg, hdrs)
File "/usr/lib/python3.5/urllib/request.py", line 510, in error
return self._call_chain(*args)
File "/usr/lib/python3.5/urllib/request.py", line 444, in _call_chain
result = func(*args)
File "/usr/lib/python3.5/urllib/request.py", line 590, in http_error_default
raise HTTPError(req.full_url, code, msg, hdrs, fp)
urllib.error.HTTPError: HTTP Error 401: Unauthorized
Traceback (most recent call last):
File "/home/vastone/gmail_parser.py", line 62, in <module>
f = auth() # Do auth and then get the feed
File "/home/vastone/gmail_parser.py", line 30, in auth
f = opener.open(_URL)
File "/usr/lib/python3.5/urllib/request.py", line 472, in open
response = meth(req, response)
File "/usr/lib/python3.5/urllib/request.py", line 582, in http_response
'http', request, response, code, msg, hdrs)
File "/usr/lib/python3.5/urllib/request.py", line 504, in error
result = self._call_chain(*args)
File "/usr/lib/python3.5/urllib/request.py", line 444, in _call_chain
result = func(*args)
File "/usr/lib/python3.5/urllib/request.py", line 693, in http_error_302
fp.read()
File "/usr/lib/python3.5/http/client.py", line 458, in read
s = self.fp.read()
File "/usr/lib/python3.5/socket.py", line 576, in readinto
return self._sock.recv_into(b)
File "/usr/lib/python3.5/ssl.py", line 937, in recv_into
return self.read(nbytes, buffer)
File "/usr/lib/python3.5/ssl.py", line 799, in read
return self._sslobj.read(len, buffer)
File "/usr/lib/python3.5/ssl.py", line 583, in read
v = self._sslobj.read(len, buffer)
OSError: [Errno 0] Error
python3-openssl
python3-requests
python3-urllib3
Traceback (most recent call last):
File "/home/jedi/conky/gmail_parser.py", line 23, in <module>
maxlen = sys.argv[3]
IndexError: list index out of range
ruby
libruby
#!/usr/bin/ruby
require 'net/imap'
IMAP_USER = "your_gmail_username"
IMAP_PASS = "your_gmail_password"
IMAP_SERVER = "imap.gmail.com"
SSL = true
PORT = 993
IS_EXCHANGE = false
IMAP_FOLDER = "INBOX"
CONKYFIED = true
NEW_COLOR = "green"
SENDER_COLOR = "grey"
SUBJ_COLOR = "white"
def conkify(text,color)
text = "${color #{color}}#{text} $color"
return text
end
def get_messages(conn)
imap = conn
imap.search(["NOT", "DELETED", "UNSEEN"]).each do |message_id|
envelope = imap.fetch(message_id, "ENVELOPE")[0].attr["ENVELOPE"]
from, subject = envelope.from[0].name == nil ? envelope.from[0].mailbox : envelope.from[0].name, envelope.subject
CONKYFIED == true ? puts("#{conkify(from,SENDER_COLOR)} $alignr#{conkify(subject,SUBJ_COLOR)}") : puts("#{from} #{subject}")
end
end
imap = Net::IMAP.new(IMAP_SERVER,port = PORT, usessl = SSL)
imap.login(IMAP_USER,IMAP_PASS)
imap.examine(IMAP_FOLDER)
IS_EXCHANGE == true ? counts = imap.search(["NOT", "DELETED", "UNSEEN"]).size : counts = imap.status(IMAP_FOLDER, ["UNSEEN"])["UNSEEN"]
counts > 0 ? ( puts("New Messages: #{CONKYFIED == true ? conkify(counts,NEW_COLOR) : counts}"); get_messages(imap) ) : ( puts("No new messages") )
imap.disconnect
exit
IMAP_USER = "your_gmail_username"
IMAP_PASS = "your_gmail_password"
NEW_COLOR = "green"
SENDER_COLOR = "grey"
SUBJ_COLOR = "white"
CONKYFIED = true
CONKYFIED = false
chmod 755 /path/to/check-gmail.rb
execpi 600 /path/to/check-gmail.rb
@PackRat @VastOne
You've got following installed?Code: [Select]python3-openssl
python3-requests
python3-urllib3
Install if missing and re-run the script!
Cheers!!!
Folks, AFAIK there's currently something libssl breaking python. Might be that driving you mad?
python-urllib3
python-requests
python-feedparser
python check-gmail.py "gmail_username" "gmail_password" "3"
#!/bin/bash
gmail_login="your_gmail_login_name" #login name
gmail_password="your_gmail_login_password" #pass
dane="$(wget --secure-protocol=TLSv1 --timeout=3 -t 1 -q -O - \
https://${gmail_login}:${gmail_password}@mail.google.com/mail/feed/atom \
--no-check-certificate | grep 'fullcount' \
| sed -e 's/.*<fullcount>//;s/<\/fullcount>.*//' 2>/dev/null)"
if [ -z "$dane" ]; then
echo "No connection"
else
echo "$dane message(s)"
fi
${color #E2CF3B} ${execi 20 /home/vastone/mail-notify}
#!/usr/bin/env python2
import sys
import socket
import urllib
import errno
import os
import signal
from xml.dom import minidom
from functools import wraps
username = "your_gmail_username"
password = "your_gmail_password"
label = str(sys.argv[1])
limit = int(sys.argv[2])
class TimeoutError(Exception):
pass
def timeout(seconds=10, error_message=os.strerror(errno.ETIME)):
def decorator(func):
def _handle_timeout(signum, frame):
raise TimeoutError(error_message)
@wraps(func)
def wrapper(*args, **kwargs):
signal.signal(signal.SIGALRM, _handle_timeout)
signal.alarm(seconds)
try:
result = func(*args, **kwargs)
finally:
signal.alarm(0)
return result
return wrapper
return decorator
GMAIL_URL = 'https://'+urllib.quote(username)+':'+urllib.quote(password)+'@mail.google.com/mail/feed/atom/'+urllib.quote(label)+'/'
def utfEncode(string):
return unicode(string).encode('utf-8')
def printEmails(emails):
for email in emails['emails']:
print 'Sender: %s' %(utfEncode(email['address']))
print 'Subject: %s' %utfEncode(email['title'])
print 'Summary: %s\n' %utfEncode(email['summary'])
@timeout(10)
def getGmail(label,maxCount):
url = GMAIL_URL
try:
xml = urllib.urlopen(url)
dom = minidom.parse(xml)
except:
print '\nError: Could not get emails\n'
exit()
mail = []
for node in dom.getElementsByTagName('entry'):
if maxCount == 0:
break
author = node.getElementsByTagName('author')[0]
mail.append({
'title' : node.getElementsByTagName('title')[0].firstChild.data,
'summary': node.getElementsByTagName('summary')[0].firstChild.data,
'sender' : author.getElementsByTagName('name')[0].firstChild.data,
'address': author.getElementsByTagName('email')[0].firstChild.data
})
maxCount -= 1
count = dom.getElementsByTagName('fullcount')[0].firstChild.data
return {
'emails' : mail,
'labelname' : label,
'labelcount': count
}
printEmails(getGmail(label,limit))
username = "your_gmail_username"
password = "your_gmail_password"
chmod 755 /path/to/check-gmail.py
execi 300 python2 /path/to/check-gmail.py INBOX 5
python2 /path/to/check-gmail.py INBOX 5
vastone@vsido:~$ python2 ./check-gmail.py INBOX 5
Error: Could not get emails
That happened to me once or twice as well. Re-run the script and it returns the results. Retry it, chances are it'll work.Code: [Select]vastone@vsido:~$ python2 ./check-gmail.py INBOX 5
Error: Could not get emails
I cannot debug anything further... this is an epic script and I hope to get it working
Well done man...
V-Ger
import sys
import socket
import urllib
import errno
import os
import signal
from xml.dom import minidom
from functools import wraps
Still does not work for me.. restarted it several dozen times and even rebootedNo, it's not a missing module problem. Had it been a module missing thingy python would have mentioned it in the error. Most likely Google is blocking the log-in attempt. If you are using your Google account password in the script then you'll have to change the account setting to allow non-Google apps access to your account. More information here,
Is there something new in the requirements from the import section?Code: [Select]import sys
import socket
import urllib
import errno
import os
import signal
from xml.dom import minidom
from functools import wraps
sudo python2 get-pip.py
sudo python3 get-pip.py
sudo pip2 install feedparser
sudo pip3 install feedparser
Hi hakerdefoHi there,
It is definitely urllib/libssl that snap pointed out that is the issue. I am now on the machine that has sid running and just did an update and was told that libssl would be updated and that a bug is going to break python... nice.
I will try your new solutions but I already have my google acct setup as Access for less secure apps and have verified with earlier scripts (ruby one) that it works as advertised.. It must be noted that I cannot change my google acct to any other setting. IOW, I do not have the option to go with different passwords for a more secure environment
I will get back with feedback
More weirdness...Strange indeed! As I've mentioned in my second last post you can use python modules from PyPI instead of Debian unstable whenever a script needs a module.
I have disabled the check-gmail.py line from my conky script but yet the script just keeps on running... I do not see it in Task Manager or in top as a process running
The message
Error:Could not get emails
is explicit to the check-gmail.py script and when I delete the contents of that file and save it, only then does conky remove that message from my conky widget
I cannot access to setup app passwords even after having less secure apps turned off for 24 hours
Google sucks with a lot of their bullshit and I am tired of it all
I appreciate all your help and would like to see this script (check-gmail.py) working but my patience has run out
Hopefully in the long run the original issue with python and urllib/libssl will work itself out and the original gmail-parser.py can be used again