使用imap下载新电子邮件附件的Python脚本 [英] Python Script for downloading new email attachments using imap
问题描述
导入电子邮件 导入imaplib 导入操作系统
import email import 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.可能是此错误的原因.我认为self是在 init 函数的该行下方定义的.
I have the above code currently, and at line 12 it says self is not defined. What could be the reason for this error. I think self is defined below that line in the init function.
推荐答案
好吧,仅通过查看代码,我就可以从一开始就看到不一致的缩进-这可能是您的主要问题.尝试在FetchEmail类中定义函数.
Well, just by looking at the code, I can see inconsistent indentation right from the start - this is probably your main problem. Try defining your functions within the FetchEmail class.
第二,将 init 函数更改为:
def __init__(self, mail_server=mail_server,
username=username,
password=password):
def __init__(self, mail_server=mail_server,
username=username,
password=password):
这实际上只是将默认值应用于 init 函数.
最后,对于我们在类中的save_attachment
函数/save_attachment(self, msg, download_folder)
,您将需要在 init 函数中或scipt的顶层(类定义之外)中调用它
this is effectively just applying default values to the init function.
Lastly, to us the save_attachment
function /save_attachment(self, msg, download_folder)
within the class, you will either need to call it within the init function or within the top-level of the scipt (outside the class definition)
- 在类定义内(在init内):
self.save_attatchment(msg,download_folder)
- 在顶层:使用
fe = FetchEmail()
创建FetchEmail
对象后,您可以像这样调用save_attachment
函数:attatchment_path = fe.save_attachment()
- Within class definition (within init):
self.save_attatchment(msg,download_folder)
- Within top level: after creating an
FetchEmail
object usingfe = FetchEmail()
then you could call thesave_attachment
function like this: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
等.
just take note, if you do this, just remember to change the reference of all your functions to self.password
, self.error
etc.
我不知道这是否行得通. 也许看看此.我认为这是您最好的选择.
I do not know whether this would work. Maybe take a look at this. I think it is your best bet.
祝一切顺利!
这篇关于使用imap下载新电子邮件附件的Python脚本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!