Hi , Hope you are doing well. I was trying to extract a specific email attachment from the outlook, and inject into the dbfs loaction, but something went wrong. Could you please help. I am hereby giving the code whcih I used.
import imaplib
import email
import os
from email.header import decode_header
from email.utils import parseaddr
import base64
IMAP_SERVER = "outlook.office365.com"
IMAP_PORT = 993
EMAIL_ACCOUNT = "------------"
PASSWORD =
try:
mail = imaplib.IMAP4_SSL(IMAP_SERVER, IMAP_PORT)
mail.login(EMAIL_ACCOUNT, PASSWORD)
mail.select("inbox")
status, messages = mail.search(None, '(SUBJECT "API_Files")')
email_ids = messages[0].split()
for email_id in email_ids:
status, msg_data = mail.fetch(email_id, "(RFC822)")
for response_part in msg_data:
if isinstance(response_part, tuple😞
msg = email.message_from_bytes(response_part[1])
subject, encoding = decode_header(msg["Subject"])[0]
if isinstance(subject, bytes😞
subject = subject.decode(encoding if encoding else "utf-8")
from_ = msg.get("From")
from_email = parseaddr(from_)[1]
if msg.is_multipart():
for part in msg.walk():
content_type = part.get_content_type()
content_disposition = str(part.get("Content-Disposition"))
if "attachment" in content_disposition:
filename = part.get_filename()
if filename:
filepath = f"dbfs:/tmp{filename}"
with open(filepath, "wb") as f:
f.write(part.get_payload(decode=True))
print(f"Attachment saved to {filepath}")
else:
pass
mail.logout()
except imaplib.IMAP4.error as e:
print(f"IMAP error: {e}")