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

2024-06-28 11:51:32 发布

您现在位置:Python中文网/ 问答频道 /正文

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)) 而且它超时了。完全是新手,所以很可能我遗漏了一些显而易见的东西(比如先创建一个iMAP对象?不确定)。


Tags: httpscom示例dataemailloginpasswordnum
3条回答

您忘记指定IMAP主机和端口了吗?用一些东西来达到以下效果:

M = imaplib.IMAP4_SSL( 'imap.gmail.com' )

或者

M = imaplib.IMAP4_SSL()
M.open( 'imap.gmail.com' )

这是一个我用来从邮箱中获取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()
import imaplib

# you want to connect to a server; specify which server
server= imaplib.IMAP4_SSL('imap.googlemail.com')
# after connecting, tell the server who you are
server.login('email@gmail.com', 'password')
# this will show you a list of available folders
# possibly your Inbox is called INBOX, but check the list of mailboxes
code, mailboxen= server.list()
print mailboxen
# if it's called INBOX, then…
server.select("INBOX")

剩下的代码看起来是正确的。

相关问题 更多 >