[英]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.