python 下载邮件附件,使用imap下载新电子邮件附件的Python脚本

导入电子邮件

导入imaplib

导入操作系统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函数中定义的。在

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值