Page 1 of 1

socket.gaierror when trying to check emails

Posted: Tue Jan 17, 2017 11:08 am
by Davies
hi all, i have this code.. which ive used previously without issue but now im just getting errors each time.

Code: Select all

#!/usr/bin/python
import poplib
from email import parser

pop_conn = poplib.POP3_SSL('pop.gmail.com')
pop_conn.user('MY_EMAIL@gmail.com')
pop_conn.pass_('MY_PASSWORD')
messages = [pop_conn.retr(i) for i in range(1, len(pop_conn.list()[1]) + 1)]
messages = ["\n".join(mssg[1]) for mssg in messages]
messages = [parser.Parser().parsestr(mssg) for mssg in messages]
for message in messages:
    if message['subject'] == 'test':
        print "received"
    else:
        print "not received"
pop_conn.quit()
it works on Pycharm (a python software and environment i use) and it works by SSH to Raspberry through winSCP/putty, but when running on raspberry i get this error.
pop_conn = poplib.POP3_SSL('pop.gmail.com')
for res in socket.getaddrinfo(self.host, self.port, 0, socket.SOCK_STREAM):
socket.gaierror: [Errno -2] Name or service not known

please help

Re: socket.gaierror when trying to check emails

Posted: Tue Jan 17, 2017 11:45 am
by Davies
a little more testing has proven this to be lack of internet connection, i was testing on rpi prior to internet connection then testing again by ssh once wifi had been established.
changing rpi to hold boot until network and disconnecting the ethernet to computer resolved this issue, im now searching for a way to test internet connection prior to checking email.

Re: socket.gaierror when trying to check emails

Posted: Tue Jan 17, 2017 11:59 am
by Davies
this should do..

Code: Select all

#!/usr/bin/python
import poplib
from email import parser
import time
import urllib

while 1:
    try:
        url = "https://www.google.com"
        urllib.urlopen(url)
        status = "Connected"
    except:
        status = "Not connected"
    print status
    if status == "Connected":
        pop_conn = poplib.POP3_SSL('pop.gmail.com')
        pop_conn.user('MY_EMAIL@gmail.com')
        pop_conn.pass_('MY_PASSWORD')
        messages = [pop_conn.retr(i) for i in range(1, len(pop_conn.list()[1]) + 1)]
        messages = ["\n".join(mssg[1]) for mssg in messages]
        messages = [parser.Parser().parsestr(mssg) for mssg in messages]
        for message in messages:
            if message['subject'] == 'test':
                print "received"
            else:
                print "not received"
        pop_conn.quit()
    time.sleep(60)