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

1. 主要使用了 poplib 组件

 

# -*- 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()
 

优点: 可以输出内容

缺点: 只检测一次

 

 

2. 使用第三方插件 chilkat

 

# -*- 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

 

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

 

 

优点: 可以多次检测

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

 

 

 

3. 检测邮件,返回未读数值

 

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)
 

 

 

4. 很好的返回主题和内容

 

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()
 

参考: http://www.doughellmann.com/PyMOTW/imaplib/

 

 

 

 

 

 

 

  • 3
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Python微信企业邮箱发送邮件需要使用第三方库,常用的有smtplib、email、os等库。 首先需要导入所需的库,并定义发件人、收件人、邮件主题和内容等信息。使用email库创建一个MIMEText对象,将邮件内容存储在该对象的msg属性中。接着使用smtplib库创建SMTP对象,连接到企业邮箱服务器,使用用户名和密码登录。最后调用SMTP对象的sendmail方法,将邮件发送给收件人。 可能会遇到企业邮箱发件人地址需要通过审核的问题,需要在企业邮箱后台进行设置。 下面是一个简单的python微信企业邮箱发送邮件的示例代码: ```python import smtplib from email.mime.text import MIMEText import os # 发件人、收件人、邮件主题、邮件内容等信息 sender = 'xxx@yourcompany.com' receiver = 'xxx@othercompany.com' subject = 'Python发送企业邮件' content = '这是一封测试邮件,仅供参考。' # 创建MIMEText对象,邮件内容存储在该对象的msg属性中 msg = MIMEText(content) msg['Subject'] = subject msg['From'] = sender msg['To'] = receiver # 定义企业邮箱服务器和用户名、密码 smtp_server = 'smtp.exmail.qq.com' user_name = 'your_username' password = 'your_password' # 使用SMTP对象连接到企业邮箱服务器,并进行登录验证 smtp_obj = smtplib.SMTP(smtp_server, 587) smtp_obj.ehlo() smtp_obj.starttls() smtp_obj.login(user_name, password) # 发送邮件 smtp_obj.sendmail(sender, receiver, msg.as_string()) # 关闭连接 smtp_obj.quit() ``` 需要注意的是,在实际使用时,需要将代码中的发件人、收件人、企业邮箱服务器、用户名和密码等信息替换为自己的实际信息。同时,还需要考虑邮件附件、邮件格式等问题。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值