Python poplib.POP3_SSL 例子
下面是用来展示poplib.POP3_SSL的示例,这些示例源自于开源Python项目。你可以对你喜欢的示例点赞。你的投票将帮助我们的系统选出更多高人气的例子。
你可以在poplib库中check out出所有可用的函数/类,或者尝试搜索这个函数。
示例一:
def mkmailbox(debug=0):
username = config.username
password = config.password
mailbox = poplib.POP3_SSL('pop.googlemail.com', '995')
mailbox.set_debuglevel(debug)
mailbox.user(username)
mailbox.pass_(password)
return mailbox
示例二:
def openPopConnection( self ):
"""
Retrieve a connection to a POP server
@return: object representing a connection to a POP server
@rtype: POP3 object
"""
connection = None
try:
if self.options.poplogintype == POP_LOGIN_TYPE_CLEARTEXT:
connection = poplib.POP3( self.options.pophost,
self.options.popport )
else:
connection = poplib.POP3_SSL( self.options.pophost,
self.options.popport )
connection.user( self.options.popusername )
connection.pass_( self.options.poppassword )
except Exception, e:
# Track the state of a connection failure so we can send failure
# and clear events
self.popConnectionFailure = True
summary = 'Failed to connect to POP server %s on port %d via %s.' % \
( self.options.pophost, self.options.popport,
self.options.poplogintype )
self.log.error( '%s Error message: %s' % ( summary, e.args ) )
self.sendEmailPingEvent( 'epPopConnectionFailure',
self.options.pophost, summary )
try:
if connection:
connection.quit()
except:
pass
return None
# POP connection successful
msg = 'Connected to POP server %s on port %d via %s' % \
( self.options.pophost, self.options.popport,
self.options.poplogintype )
self.log.debug( msg )
# Clear a previous failure
if self.popConnectionFailure:
self.sendEmailPingEvent( 'epPopConnectionClear',
self.options.pophost, msg )
self.popConnectionFailure = False
return connection
示例三:
def _do_pop(self, server, user, password, apop, ssl):
'''Read a series of messages from the specified POP server.
'''
import getpass, poplib, socket
try:
if not user:
user = raw_input('User: ')
if not password:
password = getpass.getpass()
except (KeyboardInterrupt, EOFError):
# Ctrl C or D maybe also Ctrl Z under Windows.
print "\nAborted by user."
return 1
# open a connection to the server and retrieve all messages
try:
if ssl:
klass = poplib.POP3_SSL
else:
klass = poplib.POP3
server = klass(server)
except socket.error:
self.logger.exception('POP server error')
return 1
if apop:
server.apop(user, password)
else:
server.user(user)
server.pass_(password)
numMessages = len(server.list()[1])
for i in range(1, numMessages+1):
# retr: returns
# [ pop response e.g. '+OK 459 octets',
# [ array of message lines ],
# number of octets ]
lines = server.retr(i)[1]
s = cStringIO.StringIO('\n'.join(lines))
s.seek(0)
self.handle_Message(Message(s))
# delete the message
server.dele(i)
# quit the server to commit changes.
server.quit()
return 0
示例四:
def __init__(self, args):
self.server = args['server']
self.account = args['account']
if args['ssl']:
self.pop3 = poplib.POP3_SSL
else:
self.pop3 = poplib.POP3
self.data = None
self.moredata = None
self.identifier = None
self.password = getpass.getpass("Enter password for %s:" % self.account)
pop3 = self.pop3(self.server)
pop3.user(self.account)
try:
pop3.pass_(self.password)
self.state = pop3.stat()
except poplib.error_proto:
raise Exception("Incorrect username/password for %s" % self.account)
finally:
pop3.quit()
BaseReader.__init__(self)
self.log.log("Starting POP3 Reader for %s" % self.account)
示例五:
def main():
'''Main opensignsis processing function.
'''
usage = 'usage: %prog [options] sis_input sis_output'
version = '%%prog %s (%s)' % (__version__, __date__)
# create parameters parser
optparser = OptionParser(usage=usage, version=version)
optparser.add_option('-i', '--imei', dest='imei',
help='IMEI of the target device')
optparser.add_option('-c', '--caps', dest='caps', metavar='CAPABILITIES',
help='list of capabilities names, separated by +')
optparser.add_option('-e', '--email', dest='email',
help='e-mail address used to retrive the signed sis file')
optparser.add_option('-s', '--server', dest='server', metavar='POP3_SERVER',
help='host[:port] of the e-mail address POP3 server, defaults to the ' \
'host part of the e-mail')
optparser.add_option('-l', '--login', dest='login', metavar='LOGIN',
help='POP3 server login name, defaults to the username part of the e-mail')
optparser.add_option('-p', '--passwd', dest='passwd', metavar='PASSWORD',
help='password associated with the login name, if ommited will cause ' \
'a prompt at runtime')
optparser.add_option('-t', '--ssl', dest='ssl', action='store_true',
help='use SSL to login to POP3 server')
optparser.add_option('-r', '--inplace', dest='inplace', action='store_true',
help='replace the input file with the output file')
optparser.add_option('-v', '--verbose', dest='verbose', action='store_true',
help='print out more information while running')
# parse config
cfgparser = ConfigParser.SafeConfigParser()
cfgoptions = {'device': ('imei',),
'email': ('email', 'server', 'login', 'passwd', 'ssl')}
cfgpath = os.path.join(os.path.dirname(__file__), 'opensignsis.config')
if os.path.exists(cfgpath):
# read config
if cfgparser.read(cfgpath):
for section, items in cfgoptions.items():
for item in items:
try:
optparser.set_default(item, cfgparser.get(section, item))
except (ConfigParser.NoSectionError, ConfigParser.NoOptionError):
pass
else:
# write empty config file
for section, items in cfgoptions.items():
cfgparser.add_section(section)
for item in items:
cfgparser.set(section, item, '')
try:
h = open(cfgpath, 'w')
cfgparser.write(h)
h.close()
except IOError, e:
warning('couldn\'t create an empty config file (%s)' % e)
# parse the parameters
options, args = optparser.parse_args()
# validate params
if len(args) == 0:
optparser.error('specify input SIS file')
sis_input = args[0]
if len(args) == 1:
if options.inplace:
sis_output = sis_input
else:
if( sis_input[-4:] == ".sis" ):
sis_output = sis_input[:-4] + "_signed.sis"
else:
optparser.error('specify output SIS file or -r/--inplace option')
elif len(args) > 2:
optparser.error('unexpected arguments')
else:
if options.inplace:
optparser.error('remove -r/--inplace option if specifying an output SIS file')
sis_output = args[1]
# process caps option
usercaps = options.caps
if usercaps is None:
usercaps = 'ALL'
warning('no caps specified, using %s' % repr(usercaps))
if usercaps.upper() == 'ALL':
usercaps = '+'.join(capabilities.keys())
caps = []
for c in usercaps.split('+'):
cap = [x for x in capabilities.keys() if x.lower() == c.lower()]
if not cap:
optparser.error('Unknown capability: %s' % c)
caps.append(cap[0])
# validate params
imei = options.imei
if not imei:
optparser.error('use -i/--imei option or add IMEI to the config file')
print 'Using IMEI: %s' % imei
# resolve sis_output params
params = dict(imei=imei, caps='+'.join(caps))
# convert all {x} params to lower-case
low = sis_output.lower()
for param in params.keys():
pos = 0
while True:
pos = low.find('{%s}' % param, pos)
if pos < 0:
break
sis_output = '%s{%s}%s' % (sis_output[:pos], param, sis_output[pos+len(param)+2:])
pos += len(param)+2
for param, value in params.items():
sis_output = sis_output.replace('{%s}' % param, value)
email = options.email
if not email:
optparser.error('use -e/--email option or add e-mail to the config file')
# open input sis file
sis_input_file = open(sis_input, 'rb')
# create an URL opener with multipart POST and cookies support
cookies = cookielib.CookieJar()
opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cookies),
MultipartPostHandler)
codeimage = tempfile.mktemp('.jpg')
wxapp = wx.PySimpleApp(0)
wx.InitAllImageHandlers()
print 'Processing security code...'
try:
while True:
if options.verbose:
print '* downloading image...'
h = opener.open('https://www.symbiansigned.com/app/Captcha.jpg')
data = h.read()
h.close()
h = open(codeimage, 'wb')
h.write(data)
h.close()
if options.verbose:
print '* opening dialog...'
dialog = CaptchaDialog(None, os.path.split(sis_input)[-1], codeimage,
'Enter security code using only\nA-F letters and 0-9 numbers')
result = dialog.ShowModal()
if result != wx.ID_OK:
sys.exit('Canceled')
captcha = dialog.code.upper().replace('O', '0')
dialog.Destroy()
# if the code is empty, download a new one and repeat
if captcha:
break
if options.verbose:
print '* no code entered, retrying with a new one...'
finally:
try:
os.remove(codeimage)
except:
pass
if options.verbose:
print '* security code: %s' % captcha
# create request params
params = dict(imei=imei,
capabilities=[capabilities[x] for x in caps],
email=email,
application=sis_input_file,
captcha=captcha,
acceptLegalAgreement='true')
print 'Sending request to Open Signed Online...'
reqtime = time.time()
h = opener.open('https://www.symbiansigned.com/app/page/public/openSignedOnline.do',
params)
data = h.read()
h.close()
# check for error
pos = data.find('<td class="errorBox">')
if pos >= 0:
t = data[pos+21:]
msg = t[:t.index('<br/>')].strip()
sys.exit('error: %s' % msg)
if options.verbose:
print '* request sent'
# validate options
server = options.server
if not server:
server = email.split('@')[-1]
warning('no POP3 server specified in args or in the config file, using %s' % repr(server))
server = server.split(':')
if options.ssl:
POP3 = poplib.POP3_SSL
else:
POP3 = poplib.POP3
login = options.login
if not login:
login = email.split('@')[0]
warning('no login specified in args or in the config file, using %s' % repr(login))
passwd = options.passwd
if not passwd:
warning('no password specified in args or in the config file, prompting for one now')
from getpass import getpass
passwd = getpass('Password for %s: ' % repr(login))
print 'Waiting for request confirmation...'
confirmed = False
while True:
if options.verbose:
print '* polling the mailbox...'
try:
mbox = POP3(*server)
mbox.user(login)
mbox.pass_(passwd)
except poplib.error_proto, e:
sys.exit('error: %s' % e)
for m in mbox.list()[1]:
idx = int(m.split()[0])
# we use top(), not retr(), so that the 'read'-flag isn't set
head, body = parse_email(mbox.top(idx, 8192)[1])
try:
if time.mktime(rfc822.parsedate(head['date'])) < reqtime:
continue
except:
pass
if head.get('from', '').lower() == 'donotreply@symbiansigned.com':
for ln in body:
if ln.startswith('Confirmation link: https://www.symbiansigned.com/app/page/public/confirmrequest.pub?code='):
break
else:
print 'Unknown message: %s' % head['subject']
# next email
continue
if options.verbose:
print '* confirming'
# confirm
h = opener.open(ln[19:])
data = h.read()
h.close()
if os.path.split(sis_input)[-1] in data:
confirmed = True
if options.verbose:
print '* request confirmed'
mbox.dele(idx)
mbox.quit()
if confirmed:
break
time.sleep(3.0)
print 'Waiting for signed file...'
downloaded = False
text = 'Your application (%s)' % os.path.split(sis_input)[-1]
while True:
if options.verbose:
print '* polling the mailbox...'
try:
mbox = POP3(*server)
mbox.user(login)
mbox.pass_(passwd)
except poplib.error_proto, e:
sys.exit('error: %s' % e)
for m in mbox.list()[1]:
idx = int(m.split()[0])
# we use top(), not retr(), so that the 'read'-flag isn't set
head, body = parse_email(mbox.top(idx, 8192)[1])
try:
if time.mktime(rfc822.parsedate(head['date'])) < reqtime:
continue
except:
pass
if head.get('from', '').lower() == 'donotreply@symbiansigned.com':
if len(body) == 0 or not text in body[0]:
continue
mbox.dele(idx)
for ln in body:
if ln.startswith('Download link: https://www.symbiansigned.com/app/page/public/downloadapplication.pub?code='):
break
else:
if 'signing has failed' in ' '.join(body):
mbox.quit()
sys.exit('error: %s' % ' '.join(body).strip())
print 'Unknown message: %s' % head['subject']
# next email
continue
if options.verbose:
print '* downloading sis file'
# download
h = opener.open(ln[15:])
data = h.read()
h.close()
# save as output sis
h = open(sis_output, 'wb')
h.write(data)
h.close()
downloaded = True
if options.verbose:
print '* saved as %s' % sis_output
break
mbox.quit()
if downloaded:
break
time.sleep(6.0)
print 'Saved as: %s' % sis_output
def main():
'''Main opensignsis processing function.
'''
usage = 'usage: %prog [options] sis_input sis_output'
version = '%%prog %s (%s)' % (__version__, __date__)
# create parameters parser
optparser = OptionParser(usage=usage, version=version)
optparser.add_option('-i', '--imei', dest='imei',
help='IMEI of the target device')
optparser.add_option('-c', '--caps', dest='caps', metavar='CAPABILITIES',
help='list of capabilities names, separated by +')
optparser.add_option('-e', '--email', dest='email',
help='e-mail address used to retrive the signed sis file')
optparser.add_option('-s', '--server', dest='server', metavar='POP3_SERVER',
help='host[:port] of the e-mail address POP3 server, defaults to the ' \
'host part of the e-mail')
optparser.add_option('-l', '--login', dest='login', metavar='LOGIN',
help='POP3 server login name, defaults to the username part of the e-mail')
optparser.add_option('-p', '--passwd', dest='passwd', metavar='PASSWORD',
help='password associated with the login name, if ommited will cause ' \
'a prompt at runtime')
optparser.add_option('-t', '--ssl', dest='ssl', action='store_true',
help='use SSL to login to POP3 server')
optparser.add_option('-r', '--inplace', dest='inplace', action='store_true',
help='replace the input file with the output file')
optparser.add_option('-v', '--verbose', dest='verbose', action='store_true',
help='print out more information while running')
# parse config
cfgparser = ConfigParser.SafeConfigParser()
cfgoptions = {'device': ('imei',),
'email': ('email', 'server', 'login', 'passwd', 'ssl')}
cfgpath = os.path.join(os.path.dirname(__file__), 'opensignsis.config')
if os.path.exists(cfgpath):
# read config
if cfgparser.read(cfgpath):
for section, items in cfgoptions.items():
for item in items:
try:
optparser.set_default(item, cfgparser.get(section, item))
except (ConfigParser.NoSectionError, ConfigParser.NoOptionError):
pass
else:
# write empty config file
for section, items in cfgoptions.items():
cfgparser.add_section(section)
for item in items:
cfgparser.set(section, item, '')
try:
h = open(cfgpath, 'w')
cfgparser.write(h)
h.close()
except IOError, e:
warning('couldn\'t create an empty config file (%s)' % e)
# parse the parameters
options, args = optparser.parse_args()
# validate params
if len(args) == 0:
optparser.error('specify input SIS file')
sis_input = args[0]
if len(args) == 1:
if options.inplace:
sis_output = sis_input
else:
if( sis_input[-4:] == ".sis" ):
sis_output = sis_input[:-4] + "_signed.sis"
else:
optparser.error('specify output SIS file or -r/--inplace option')
elif len(args) > 2:
optparser.error('unexpected arguments')
else:
if options.inplace:
optparser.error('remove -r/--inplace option if specifying an output SIS file')
sis_output = args[1]
# process caps option
usercaps = options.caps
if usercaps is None:
usercaps = 'ALL'
warning('no caps specified, using %s' % repr(usercaps))
if usercaps.upper() == 'ALL':
usercaps = '+'.join(capabilities.keys())
caps = []
for c in usercaps.split('+'):
cap = [x for x in capabilities.keys() if x.lower() == c.lower()]
if not cap:
optparser.error('Unknown capability: %s' % c)
caps.append(cap[0])
# validate params
imei = options.imei
if not imei:
optparser.error('use -i/--imei option or add IMEI to the config file')
print 'Using IMEI: %s' % imei
# resolve sis_output params
params = dict(imei=imei, caps='+'.join(caps))
# convert all {x} params to lower-case
low = sis_output.lower()
for param in params.keys():
pos = 0
while True:
pos = low.find('{%s}' % param, pos)
if pos < 0:
break
sis_output = '%s{%s}%s' % (sis_output[:pos], param, sis_output[pos+len(param)+2:])
pos += len(param)+2
for param, value in params.items():
sis_output = sis_output.replace('{%s}' % param, value)
email = options.email
if not email:
optparser.error('use -e/--email option or add e-mail to the config file')
# open input sis file
sis_input_file = open(sis_input, 'rb')
# create an URL opener with multipart POST and cookies support
cookies = cookielib.CookieJar()
opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cookies),
MultipartPostHandler)
codeimage = tempfile.mktemp('.jpg')
wxapp = wx.PySimpleApp(0)
wx.InitAllImageHandlers()
print 'Processing security code...'
try:
while True:
if options.verbose:
print '* downloading image...'
h = opener.open('https://www.symbiansigned.com/app/Captcha.jpg')
data = h.read()
h.close()
h = open(codeimage, 'wb')
h.write(data)
h.close()
if options.verbose:
print '* opening dialog...'
dialog = CaptchaDialog(None, os.path.split(sis_input)[-1], codeimage,
'Enter security code using only\nA-F letters and 0-9 numbers')
result = dialog.ShowModal()
if result != wx.ID_OK:
sys.exit('Canceled')
captcha = dialog.code.upper().replace('O', '0')
dialog.Destroy()
# if the code is empty, download a new one and repeat
if captcha:
break
if options.verbose:
print '* no code entered, retrying with a new one...'
finally:
try:
os.remove(codeimage)
except:
pass
if options.verbose:
print '* security code: %s' % captcha
# create request params
params = dict(imei=imei,
capabilities=[capabilities[x] for x in caps],
email=email,
application=sis_input_file,
captcha=captcha,
acceptLegalAgreement='true')
print 'Sending request to Open Signed Online...'
reqtime = time.time()
h = opener.open('https://www.symbiansigned.com/app/page/public/openSignedOnline.do',
params)
data = h.read()
h.close()
# check for error
pos = data.find('<td class="errorBox">')
if pos >= 0:
t = data[pos+21:]
msg = t[:t.index('<br/>')].strip()
sys.exit('error: %s' % msg)
if options.verbose:
print '* request sent'
# validate options
server = options.server
if not server:
server = email.split('@')[-1]
warning('no POP3 server specified in args or in the config file, using %s' % repr(server))
server = server.split(':')
if options.ssl:
POP3 = poplib.POP3_SSL
else:
POP3 = poplib.POP3
login = options.login
if not login:
login = email.split('@')[0]
warning('no login specified in args or in the config file, using %s' % repr(login))
passwd = options.passwd
if not passwd:
warning('no password specified in args or in the config file, prompting for one now')
from getpass import getpass
passwd = getpass('Password for %s: ' % repr(login))
print 'Waiting for request confirmation...'
confirmed = False
while True:
if options.verbose:
print '* polling the mailbox...'
try:
mbox = POP3(*server)
mbox.user(login)
mbox.pass_(passwd)
except poplib.error_proto, e:
sys.exit('error: %s' % e)
for m in mbox.list()[1]:
idx = int(m.split()[0])
# we use top(), not retr(), so that the 'read'-flag isn't set
head, body = parse_email(mbox.top(idx, 8192)[1])
try:
if time.mktime(rfc822.parsedate(head['date'])) < reqtime:
continue
except:
pass
if head.get('from', '').lower() == 'donotreply@symbiansigned.com':
for ln in body:
if ln.startswith('Confirmation link: https://www.symbiansigned.com/app/page/public/confirmrequest.pub?code='):
break
else:
print 'Unknown message: %s' % head['subject']
# next email
continue
if options.verbose:
print '* confirming'
# confirm
h = opener.open(ln[19:])
data = h.read()
h.close()
if os.path.split(sis_input)[-1] in data:
confirmed = True
if options.verbose:
print '* request confirmed'
mbox.dele(idx)
mbox.quit()
if confirmed:
break
time.sleep(3.0)
print 'Waiting for signed file...'
downloaded = False
text = 'Your application (%s)' % os.path.split(sis_input)[-1]
while True:
if options.verbose:
print '* polling the mailbox...'
try:
mbox = POP3(*server)
mbox.user(login)
mbox.pass_(passwd)
except poplib.error_proto, e:
sys.exit('error: %s' % e)
for m in mbox.list()[1]:
idx = int(m.split()[0])
# we use top(), not retr(), so that the 'read'-flag isn't set
head, body = parse_email(mbox.top(idx, 8192)[1])
try:
if time.mktime(rfc822.parsedate(head['date'])) < reqtime:
continue
except:
pass
if head.get('from', '').lower() == 'donotreply@symbiansigned.com':
if len(body) == 0 or not text in body[0]:
continue
mbox.dele(idx)
for ln in body:
if ln.startswith('Download link: https://www.symbiansigned.com/app/page/public/downloadapplication.pub?code='):
break
else:
if 'signing has failed' in ' '.join(body):
mbox.quit()
sys.exit('error: %s' % ' '.join(body).strip())
print 'Unknown message: %s' % head['subject']
# next email
continue
if options.verbose:
print '* downloading sis file'
# download
h = opener.open(ln[15:])
data = h.read()
h.close()
# save as output sis
h = open(sis_output, 'wb')
h.write(data)
h.close()
downloaded = True
if options.verbose:
print '* saved as %s' % sis_output
break
mbox.quit()
if downloaded:
break
time.sleep(6.0)
print 'Saved as: %s' % sis_output