python模拟登录qq邮箱

来源:互联网 发布:印度 撤军 知乎 编辑:程序博客网 时间:2024/04/28 07:33

     前两天做一个任务,要写一个收取qq邮箱邮件的脚本。开始认为挺简单,后来发现还是有一些坑在里面。

    首先使用python尝试模拟登录qq邮箱,发现普通用户已经不能通过账号密码模拟登录qq邮箱了。要用到授权码。(具体查看qq邮箱账号设置) 首先打开qq邮箱生成授权码,然后模拟登录中使用此授权码登录。

  • 接收服务器:

pop.exmail.qq.com(使用SSL,端口号995)

发送服务器:

smtp.exmail.qq.com(使用SSL,端口号465)

这是企业邮箱。个人邮箱的话服务器地址没有exmail,并且个人邮箱需要用到授权码。


#!/usr/bin/python# -*- coding:utf-8 -*-import poplib, pprint, email, sys, time, email, time, smtplib, imaplibfrom datetime import datetime, timedelta, datefrom email.mime.text import MIMEText  from email.header import Header#设置命令窗口输出使用UTF-8编码reload(sys)sys.setdefaultencoding( "utf-8" )# 第三方 SMTP 服务  注意这是企业邮箱  如果是个人邮箱,密码要用授权码,服务器地址没有exmailmail_smtp_host= "smtp.exmail.qq.com"  # 设置smtp服务器  mail_pop_host= "pop.exmail.qq.com"# 设置pop服务器mail_user= ""    # 用户名  mail_pass= ""  # 口令,QQ邮箱是输入授权码,在qq邮箱设置 里用验证过的手机发送短信获得,不含空格 '''/*DISCRIPTION *Decoding charsert * ARGUMENTS * string need be Decodinged * RETURN * NOTES */'''def Decoding(str):if(str[0][1] == None): return unicode(str[0][0], 'gb18030')else: return unicode(str[0][0], str[0][1])'''/*DISCRIPTION *Send the mail to the unsubmit * ARGUMENTS * string need be Decodinged * RETURN * NOTES */'''def  SendEmail():sender = ''  receivers = ['']  # 接收邮件,可设置为你的QQ邮箱或者其他邮箱    message = MIMEText('a test for python', 'plain', 'utf-8')  message['From'] = Header("ppyy", 'utf-8')  message['To'] =  Header("you", 'utf-8')    subject = 'my test'  message['Subject'] = Header(subject, 'utf-8')  try:    smtpObj = smtplib.SMTP_SSL(mail_smtp_host, 465)     smtpObj.login(mail_user,mail_pass)      smtpObj.sendmail(sender, receivers, message.as_string())   smtpObj.quit()    print u"邮件发送成功"  except smtplib.SMTPException,e:    print e  def GetEmail():try:pp = poplib.POP3_SSL(mail_pop_host)pp.user(mail_user)pp.pass_(mail_pass)ret =pp.stat()print u"登录成功"except:print "can't connect to mailserver"#遍历邮件的标题# emailMsgNum, emailSize = pp.stat()# for i in xrange(1, emailMsgNum+1):# ret = pp.retr(i)# mail = email.message_from_string("\n".join(ret[1]))# subject = email.Header.decode_header(mail['subject'])# MailSubject = Decoding(subject)# print MailSubject                  ret = pp.retr(2)msg = email.message_from_string("\n".join(ret[1]))print msg.get_payload()# down = pp.retr(1)# print 'lines:', len(down)# for line in down[1]:#  print linepp.quit()GetEmail();


0 0