Python打印函数返回None而不是Email String

时间:2017-12-10 05:29:06

标签: function printing scope imap

我正在尝试使用imap库从我收件箱中的最新电子邮件中提取文本,然后删除该电子邮件。我想打印checkemail函数返回的电子邮件的字符串;但是,打印的字符串为None。

有人能指出我正确的方向吗?

编辑:解决方法是将raw_email列为checkemail()函数中的全局变量,并在定义的函数之前为原始电子邮件分配一个空字符串。

import imaplib
import email
import mimetypes
from email import header


def decodeHeader( headerMsg ):
    L = header.decode_header(headerMsg)
    s = ''
    for s1, chset in L:
        if(type(s1) == bytes):
            s += s1.decode(chset) if chset else s1.decode()
        else:
            s += s1
    return s



host = 'imap.gmail.com'
userid = 'emailname@gmail.com'
passwd = 'xxxxxx'

imap = imaplib.IMAP4_SSL(host, 993)
imap.login(userid, passwd)

def checkemail():
    global raw_email
    raw_email = ""
    imap.select('INBOX') #or use INBOX
    status, email_ids = imap.search(None, '(UNSEEN)')

    for num in email_ids[0].split():
        type1, data = imap.fetch(num, '(RFC822)')
        raw_email = data[0][1]
        email_msg = email.message_from_bytes(raw_email)

        type1, data = imap.fetch(num, '(UID BODY[TEXT])')
        raw_email = data[0][1]

        imap.store(num, '+FLAGS', '(\Deleted)')
        imap.expunge()
        imap.close()
        return raw_email

checkemail()
print(checkemail())

0 个答案:

没有答案