[英]Python Script for downloading new email attachments using imap
導入電子郵件導入imaplib import os
class FetchEmail():
connection = None
error = None
mail_server="outlook.office365.com"
username="me@domain.com"
password="'Password'"
self.save_attachment(self,msg,download_folder)
def __init__(self, mail_server, username, password):
self.connection = imaplib.IMAP4_SSL(mail_server)
self.connection.login(username, password)
self.connection.select(readonly=False) # so we can mark mails as read
def close_connection(self):
"""
Close the connection to the IMAP server
"""
self.connection.close()
def save_attachment(self, msg, download_folder="/tmp"):
"""
Given a message, save its attachments to the specified
download folder (default is /tmp)
return: file path to attachment
"""
att_path = "No attachment found."
for part in msg.walk():
if part.get_content_maintype() == 'multipart':
continue
if part.get('Content-Disposition') is None:
continue
filename = part.get_filename()
att_path = os.path.join(download_folder, filename)
if not os.path.isfile(att_path):
fp = open(att_path, 'wb')
fp.write(part.get_payload(decode=True))
fp.close()
return att_path
def fetch_unread_messages(self):
"""
Retrieve unread messages
"""
emails = []
(result, messages) = self.connection.search(None, 'UnSeen')
if result == "OK":
for message in messages[0].split(' '):
try:
ret, data = self.connection.fetch(message,'(RFC822)')
except:
print ("No new emails to read.")
self.close_connection()
exit()
msg = email.message_from_string(data[0][1])
if isinstance(msg, str) == False:
emails.append(msg)
response, data = self.connection.store(message, '+FLAGS','\\Seen')
return emails
self.error = "Failed to retreive emails."
return emails
我目前有上面的代碼,在第12行它說自我沒有定義。 這可能是造成這種錯誤的原因。 我認為self定義在init函數中的那一行下面。
好吧,只要查看代碼,我就可以從一開始就看到不一致的縮進 - 這可能是你的主要問題。 嘗試在FetchEmail類中定義您的函數。
其次,將init函數更改為:
def __init__(self, mail_server=mail_server, username=username, password=password):
這實際上只是將默認值應用於init函數。 最后,對於類中的save_attachment
函數/ save_attachment(self, msg, download_folder)
,您將需要在init函數內或scipt的頂級函數內調用它(在類定義之外)
self.save_attatchment(msg,download_folder)
fe = FetchEmail()
創建FetchEmail
對象之后,您可以像這樣調用save_attachment
函數: attatchment_path = fe.save_attachment()
這是我實現init的方式 :
class FetchEmail():
def __init__(self,
mail_server="outlook.office365.com",
username="rnandipati@jmawireless.com",
password="'RNjma17!'"):
self.error = None
self.connection = None
self.mail_server = mail_server
self.username = username
self.password = password
self.connection = imaplib.IMAP4_SSL(mail_server)
self.connection.login(username, password)
self.connection.select(readonly=False) # so we can mark mails as readread
def close_connection(self): ...
請注意,如果你這樣做,只需記住將所有函數的引用更改為self.password
, self.error
等。
我不知道這是否有效。 也許看看這個 。 我認為這是你最好的選擇。
祝一切順利!
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.