Python poplib.POP3_SSL 例子

下面是用来展示poplib.POP3_SSL的示例,这些示例源自于开源Python项目。你可以对你喜欢的示例点赞。你的投票将帮助我们的系统选出更多高人气的例子。

你可以在poplib库中check out出所有可用的函数/类,或者尝试搜索这个函数。

示例一:

def mkmailbox(debug=0):username = config.usernamepassword = 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 = Nonetry: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 eventsself.popConnectionFailure = Truesummary = '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:passreturn None# POP connection successfulmsg = '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 failureif self.popConnectionFailure:self.sendEmailPingEvent( 'epPopConnectionClear', self.options.pophost, msg )self.popConnectionFailure = Falsereturn connection

示例三:

def _do_pop(self, server, user, password, apop, ssl):'''Read a series of messages from the specified POP server.'''import getpass, poplib, sockettry: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 messagestry:if ssl:klass = poplib.POP3_SSLelse:klass = poplib.POP3server = klass(server)except socket.error:self.logger.exception('POP server error')return 1if 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 messageserver.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_SSLelse:self.pop3 = poplib.POP3self.data = Noneself.moredata = Noneself.identifier = Noneself.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 parseroptparser = 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 configcfgparser = 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 configif 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):passelse:# write empty config filefor 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 paramsif len(args) == 0:optparser.error('specify input SIS file')sis_input = args[0]if len(args) == 1:if options.inplace:sis_output = sis_inputelse: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.capsif 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 paramsimei = options.imeiif not imei:optparser.error('use -i/--imei option or add IMEI to the config file')
print 'Using IMEI: %s' % imei
# resolve sis_output paramsparams = dict(imei=imei, caps='+'.join(caps))# convert all {x} params to lower-caselow = sis_output.lower()for param in params.keys():pos = 0while True:pos = low.find('{%s}' % param, pos)if pos < 0:breaksis_output = '%s{%s}%s' % (sis_output[:pos], param, sis_output[pos+len(param)+2:])pos += len(param)+2for param, value in params.items():sis_output = sis_output.replace('{%s}' % param, value)
email = options.emailif not email:optparser.error('use -e/--email option or add e-mail to the config file')
# open input sis filesis_input_file = open(sis_input, 'rb')
# create an URL opener with multipart POST and cookies supportcookies = 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 repeatif captcha:breakif 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 paramsparams = 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 errorpos = 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 optionsserver = options.serverif 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_SSLelse:POP3 = poplib.POP3login = options.loginif not login:login = email.split('@')[0]warning('no login specified in args or in the config file, using %s' % repr(login))passwd = options.passwdif not passwd:warning('no password specified in args or in the config file, prompting for one now')from getpass import getpasspasswd = getpass('Password for %s: ' % repr(login))
print 'Waiting for request confirmation...'
confirmed = Falsewhile 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 sethead, body = parse_email(mbox.top(idx, 8192)[1])try:if time.mktime(rfc822.parsedate(head['date'])) < reqtime:continueexcept:passif 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='):breakelse:print 'Unknown message: %s' % head['subject']# next emailcontinueif options.verbose:print '* confirming'
# confirmh = opener.open(ln[19:])data = h.read()h.close()
if os.path.split(sis_input)[-1] in data:confirmed = Trueif options.verbose:print '* request confirmed'
mbox.dele(idx)mbox.quit()
if confirmed:breaktime.sleep(3.0)print 'Waiting for signed file...'downloaded = Falsetext = '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 sethead, body = parse_email(mbox.top(idx, 8192)[1])try:if time.mktime(rfc822.parsedate(head['date'])) < reqtime:continueexcept:passif 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='):breakelse:if 'signing has failed' in ' '.join(body):mbox.quit()sys.exit('error: %s' % ' '.join(body).strip())
print 'Unknown message: %s' % head['subject']# next emailcontinueif options.verbose:print '* downloading sis file'
# downloadh = opener.open(ln[15:])data = h.read()h.close()
# save as output sish = open(sis_output, 'wb')h.write(data)h.close()downloaded = Trueif options.verbose:print '* saved as %s' % sis_output
break
mbox.quit()
if downloaded:breaktime.sleep(6.0)
print 'Saved as: %s' % sis_output

使用SSL登录qq邮箱

Python poplib.POP3_SSL使用示例相关推荐

  1. python开源项目及示例代码

    1 算法 1.1 字符串处理 re 正则表达式的标准库. StringIO / cStringIO 以读写文件的方式来操作字符串(有点类似于内存文件). cStringIO 是 C 语言实现的,提供高 ...

  2. python项目实例代码-python开源项目及示例代码

    下面列出的各种 Python 库/模块/工具,如果名称带超链接,说明是第三方的:否则是 Python 语言内置的. 1 算法 1.1 字符串处理 re 正则表达式的标准库. StringIO / cS ...

  3. Python 开源库及示例代码

    Python 开源库及示例代码 更多干货 分布式实战(干货) spring cloud 实战(干货) mybatis 实战(干货) spring boot 实战(干货) React 入门实战(干货) ...

  4. python元组(tuple)使用示例+常用方法+列表(list)和元组(tuple)的异同?

    python元组(tuple)使用示例+常用方法+列表(list)和元组(tuple)的异同? 元组(tuple) # 元组类似列表,元组里面的元素也是进行索引计算. # 列表里面的元素的值可以修改, ...

  5. python中typing.NamedTuple示例

    python中typing.NamedTuple示例 from typing import * # 导入依赖项 class Friend(NamedTuple): """ ...

  6. python画图代码星星-Python中turtle作图示例

    在Python里,海龟不仅可以画简单的黑线,还可以用它画更复杂的几何图形,用不同的颜色,甚至还可以给形状填色. 一.从基本的正方形开始 引入turtle模块并创建Pen对象: >>> ...

  7. python的用途实例-python assert的用处示例详解

    使用assert断言是学习python一个非常好的习惯,python assert 断言句语格式及用法很简单.在没完善一个程序之前,我们不知道程序在哪里会出错,与其让它在运行最崩溃,不如在出现错误条件 ...

  8. python如何更新包_python如何更新包 python更新包代码示例

    python如何更新包?本篇文章小编给大家分享一下python更新包代码示例,代码介绍的很详细,小编觉得挺不错的,现在分享给大家供大家参考,有需要的小伙伴们可以来看看. Python安装新包,pip是 ...

  9. python调用ipython_在IPython中执行Python程序文件的示例

    简单使用了一下之后,我觉得如果有机会(公司里面编码是极不自由的,也无所谓,我在公司不做数据分析),我肯定是更喜欢使用IPython作为我的Python shell环境了.简单的接触发现了不少我喜欢的功 ...

最新文章

  1. 二叉树的前序,中序,后序的递归、迭代实现
  2. 这场编程语言的发布会,不参加可太亏了!
  3. Nature子刊:提高作物产量?农作物微生物组是关键
  4. Linux网络基础1
  5. python交叉编译第三方库_第三方库交叉编译
  6. SQL Server 中数据查询注意事项
  7. android 启动速度优化终极方案
  8. 广告域名审核之后跳转技术:点击域名A页面iframe框架下的链接,域名A跳转到域名B...
  9. Android输入系统(三)InputReader的加工类型和InputDispatcher的分发过程
  10. msm8909相关事宜
  11. Java8 Lamdba表达式 002
  12. 使用Java进行查询hugegraph_HugeGraph Examples
  13. HashSet集合和TreeSet集合
  14. 使用OAuth 2 / OpenID Connect的SSO的Spring Boot 2本机方法
  15. 八大排序算法的python实现(三)冒泡排序
  16. html 文本溢出,确定HTML元素的内容是否溢出
  17. python telnetlib详解 执行循环命令_Python3+telnetlib实现telnet客户端
  18. php自动按天清空库存,swoole+PHP实现自动取消订单,还原库存等操作
  19. 地产cio揭秘:帆软大商业智能解决方案如何助力地产行业信息化
  20. 软件版本 —— Alpha、Beta、RC、Stable版本的区别

热门文章

  1. WPF 使用 SharpDx 异步渲染
  2. 面向Web的数据挖掘
  3. 视频的码率、帧率、分辨率之间的区别
  4. 机器学习之构造决策树
  5. OS101:图灵机、通用图灵机与bootsect
  6. Lg手机在linux刷机,LG G3卡刷刷机详细图文教程
  7. mPEG-HSA;甲氧基聚乙二醇人血清白蛋白;HSA-PEG简介
  8. 女工程师独家揭秘:双11秘密武器阿里云数据库团队故事
  9. 媒体观点 | 手机拍照“神仙打架”背后,厂商死磕计算摄影到底在比什么?
  10. 访美著名医学中心后,清华董家鸿院士提出了“4I战略”