Python实例讲解 -- 接收邮件 (亲测)

[b]1. 主要使用了 poplib 组件[/b]

# -*- coding: utf-8 -*-

import poplib
from email import parser

host = 'pop.gmail.com'
username = 'mine@gmail.com'
password = '*******'

pop_conn = poplib.POP3_SSL(host)
pop_conn.user(username)
pop_conn.pass_(password)

#Get messages from server:
messages = [pop_conn.retr(i) for i in range(1, len(pop_conn.list()[1]) + 1)]

# Concat message pieces:
messages = ["\n".join(mssg[1]) for mssg in messages]

#Parse message intom an email object:
messages = [parser.Parser().parsestr(mssg) for mssg in messages]
for message in messages:
print message['Subject']
pop_conn.quit()


优点: 可以输出内容
缺点: 只检测一次

[b]2. 使用第三方插件 chilkat[/b]

# -*- coding: utf-8 -*-

import sys
import chilkat

host = 'pop.gmail.com'
username = 'mine@gmail.com'
password = '******'

# The mailman object is used for receiving (POP3)
# and sending (SMTP) email.
mailman = chilkat.CkMailMan()

# Any string argument automatically begins the 30-day trial.
success = mailman.UnlockComponent("30-day trial")
if (success != True):
print "Component unlock failed"
sys.exit()

# Set the GMail account POP3 properties.
mailman.put_MailHost(host)
mailman.put_PopUsername(username)
mailman.put_PopPassword(password)
mailman.put_PopSsl(True)
mailman.put_MailPort(995)

# Read mail headers and one line of the body.
# To get the full emails, call CopyMail instead (no arguments)
bundle = mailman.GetAllHeaders(1)

if (bundle == None ):
print mailman.lastErrorText()
sys.exit()

for i in range(0,bundle.get_MessageCount()):
email = bundle.GetEmail(i)

# Display the From email address and the subject.
print email.ck_from()
print email.subject() + "\n"


安装见附件

主页:http://www.chilkatsoft.com/products.asp

安装:http://www.chilkatsoft.com/installPython27.asp

[color=red]安装很简单,点击 showPythonPath.bat 测试一下环境,然后复制 _chilkat.pyd 和 chilkat.py 到 Python27\Lib\site-packages\ 下就可以[/color]

优点: 可以多次检测

缺点: 只可以看到来源和主题,无法看到内容

[b]3. 检测邮件,返回未读数值[/b]

def gmail_checker(username,password):
import imaplib,re
i=imaplib.IMAP4_SSL('pop.gmail.com')
try:
i.login(username,password)
x,y=i.status('INBOX','(MESSAGES UNSEEN)')
messages=int(re.search('MESSAGES\s+(\d+)',y[0]).group(1))
unseen=int(re.search('UNSEEN\s+(\d+)',y[0]).group(1))
return (messages,unseen)
except:
return False,0

# Use in your scripts as follows:

messages,unseen = gmail_checker('mine@gmail.com','******')
print "%i messages, %i unseen" % (messages,unseen)


[b]4. 很好的返回主题和内容[/b]

import imaplib
import email

def extract_body(payload):
if isinstance(payload,str):
return payload
else:
return '\n'.join([extract_body(part.get_payload()) for part in payload])

conn = imaplib.IMAP4_SSL("pop.gmail.com", 993)
conn.login("mine@gmail.com", "******")
conn.select()
typ, data = conn.search(None, 'UNSEEN')
try:
for num in data[0].split():
typ, msg_data = conn.fetch(num, '(RFC822)')
for response_part in msg_data:
if isinstance(response_part, tuple):
msg = email.message_from_string(response_part[1])
subject=msg['subject']
print(subject)
payload=msg.get_payload()
body=extract_body(payload)
print(body)
typ, response = conn.store(num, '+FLAGS', r'(\Seen)')
finally:
try:
conn.close()
except:
pass
conn.logout()


参考: [url]http://www.doughellmann.com/PyMOTW/imaplib/[/url]
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值