使用python脚本读取未读的电子邮件

时间:2018-12-18 06:27:26

标签: python python-3.x smtp imaplib

我正在尝试从gmail帐户中读取所有未读的电子邮件。 上面的代码可以建立连接,但无法获取电子邮件。

我要打印每封电子邮件的内容。

我收到错误消息,因为无法将int转换为字节。

代码:

import smtplib
import time
import imaplib
import email

def read_email_from_gmail():
        mail = imaplib.IMAP4_SSL('imap.gmail.com')
        mail.login('my_mail','my_pwd')
        mail.select('inbox')

        result, data = mail.search(None, 'ALL')
        mail_ids = data[0]

        id_list = mail_ids.split()   
        first_email_id = int(id_list[0])
        latest_email_id = int(id_list[-1])


        for i in range(latest_email_id,first_email_id, -1):
            result, data = mail.fetch(i, '(RFC822)' )

            for response_part in data:
                if isinstance(response_part, tuple):
                    msg = email.message_from_string(response_part[1])
                    email_subject = msg['subject']
                    email_from = msg['from']
                    print ('From : ' + email_from + '\n')
                    print ('Subject : ' + email_subject + '\n')



print(read_email_from_gmail())

错误:

Traceback (most recent call last):
  File "C:/Users/devda/Desktop/Internship/access_email.py", line 32, in <module>
    print(read_email_from_gmail())
  File "C:/Users/devda/Desktop/Internship/access_email.py", line 20, in read_email_from_gmail
    result, data = mail.fetch(i, '(RFC822)' )
  File "C:\Users\devda\AppData\Local\Programs\Python\Python36\lib\imaplib.py", line 529, in fetch
    typ, dat = self._simple_command(name, message_set, message_parts)
  File "C:\Users\devda\AppData\Local\Programs\Python\Python36\lib\imaplib.py", line 1191, in _simple_command
    return self._command_complete(name, self._command(name, *args))
  File "C:\Users\devda\AppData\Local\Programs\Python\Python36\lib\imaplib.py", line 956, in _command
    data = data + b' ' + arg
TypeError: can't concat int to bytes
>>> 

我遵循了here上的教程

我要从图像中显示的电子邮件中提取内容 Email

2 个答案:

答案 0 :(得分:1)

我必须对您的代码进行一些更改才能使其在Python 3.5.1上运行。我在下面插入了注释。

# no need to import smtplib for this code
# no need to import time for this code
import imaplib
import email


def read_email_from_gmail():
        mail = imaplib.IMAP4_SSL('imap.gmail.com')
        mail.login('my_mail','my_pwd')
        mail.select('inbox')

        result, data = mail.search(None, 'ALL')
        mail_ids = data[0]

        id_list = mail_ids.split()   
        first_email_id = int(id_list[0])
        latest_email_id = int(id_list[-1])

        for i in range(latest_email_id,first_email_id, -1):
            # need str(i)
            result, data = mail.fetch(str(i), '(RFC822)' )

            for response_part in data:
                if isinstance(response_part, tuple):
                    # from_bytes, not from_string
                    msg = email.message_from_bytes(response_part[1])
                    email_subject = msg['subject']
                    email_from = msg['from']
                    print ('From : ' + email_from + '\n')
                    print ('Subject : ' + email_subject + '\n')

# nothing to print here
read_email_from_gmail()

也许向该博客的作者提交错误报告。

答案 1 :(得分:0)

这对我有用: 它将发件人地址,主题,内容(文本)存储到所有未读电子邮件的文件中。 代码:

import email
import imaplib
mail = imaplib.IMAP4_SSL('imap.gmail.com')
(retcode, capabilities) = mail.login('mymail','mypassword')
mail.list()
mail.select('inbox')

n=0
(retcode, messages) = mail.search(None, '(UNSEEN)')
if retcode == 'OK':

   for num in messages[0].split() :
      print ('Processing ')
      n=n+1
      typ, data = mail.fetch(num,'(RFC822)')
      for response_part in data:
         if isinstance(response_part, tuple):
             original = email.message_from_bytes(response_part[1])

            # print (original['From'])
            # print (original['Subject'])
             raw_email = data[0][1]
             raw_email_string = raw_email.decode('utf-8')
             email_message = email.message_from_string(raw_email_string)
             for part in email_message.walk():
                        if (part.get_content_type() == "text/plain"): # ignore attachments/html
                              body = part.get_payload(decode=True)
                              save_string = str(r"C:\Users\devda\Desktop\Internship\Dumpemail_" + str('richboy') + ".txt" )
                              myfile = open(save_string, 'a')
                              myfile.write(original['From']+'\n')
                              myfile.write(original['Subject']+'\n')            
                              myfile.write(body.decode('utf-8'))
                              myfile.write('**********\n')
                              myfile.close()
                        else:
                              continue

             typ, data = mail.store(num,'+FLAGS','\\Seen')

print (n)