python - Python iMAP 电子邮件访问的格式正确的示例?

标签 python email imap

tldr:有人可以告诉我如何正确格式化此 Python iMAP 示例以使其正常工作吗?

来自 https://docs.python.org/2.4/lib/imap4-example.html

import getpass, imaplib

M = imaplib.IMAP4()
M.login(getpass.getuser(), getpass.getpass())
M.select()
typ, data = M.search(None, 'ALL')
for num in data[0].split():
    typ, data = M.fetch(num, '(RFC822)')
    print 'Message %s\n%s\n' % (num, data[0][1])
M.close()
M.logout()

假设我的电子邮件是“email@gmail.com”,密码是“password”,这看起来应该如何?我尝试了 M.login(getpass.getuser(email@gmail.com), getpass.getpass(password)) 它超时了。在这里完成 newb,所以我很可能错过了一些明显的东西(比如先创建一个 iMAP 对象?不确定)。

最佳答案

这是我用来从我的邮箱中获取 logwatch 信息的脚本。 Presented at LFNW 2008 -

#!/usr/bin/env python

''' Utility to scan my mailbox for new mesages from Logwatch on systems and then
    grab useful info from the message and output a summary page.

    by Brian C. Lane <bcl@brianlane.com>
'''
import os, sys, imaplib, rfc822, re, StringIO

server  ='mail.brianlane.com'
username='yourusername'
password='yourpassword'

M = imaplib.IMAP4_SSL(server)
M.login(username, password)
M.select()
typ, data = M.search(None, '(UNSEEN SUBJECT "Logwatch")')
for num in data[0].split():
    typ, data = M.fetch(num, '(RFC822)')
#   print 'Message %s\n%s\n' % (num, data[0][1])

    match = re.search(  "^(Users logging in.*?)^\w",
                        data[0][1],
                        re.MULTILINE|re.DOTALL )
    if match:
        file = StringIO.StringIO(data[0][1])
        message = rfc822.Message(file)
        print message['from']
        print match.group(1).strip()
        print '----'

M.close()
M.logout()

关于python - Python iMAP 电子邮件访问的格式正确的示例?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/315362/

相关文章:

python 语法错误 无效语法

java - Android - 从应用程序发送电子邮件崩溃电子邮件 - 强制关闭

java - 当 java 中已存在电子邮件时,如何在 INBOX 文件夹的复制操作中跳过电子邮件?

php - 通过 IMAP 的 Gmail 优先收件箱?

python - Pandas 使用未对齐的索引进行选择

python - 通过 Web Scraping Python 检索 Imgur 图像链接

python - 如何在 python 3.4 中安装 - .whl 文件

C# 和 Lotus Notes

Java Mail 不发送电子邮件

python - 电子邮件中的奇怪字符无法被 imap 服务器摄取