Hello, im new to mongodb. So, what I want to do is to retrieve an attachment from Gmail which is an excel file and I want to store it here in mongodb. Here’s my code:
import imaplib
import email
import os
from email.header import decode_header
from pymongo import MongoClient
IMAP_SERVER = 'imap.gmail.com'
IMAP_PORT = 993
EMAIL = ' '
PASSWORD = ' '
mail = imaplib.IMAP4_SSL(IMAP_SERVER, IMAP_PORT)
mail.login(EMAIL, PASSWORD)
mail.select('inbox')
status, messages = mail.search(None, 'ALL')
latest_email_id = messages[0].split()[-1] # Fetch the latest email ID
status, data = mail.fetch(latest_email_id, '(RFC822)')
msg = email.message_from_bytes(data[0][1])
subject = decode_header(msg["Subject"])[0][0]
if isinstance(subject, bytes):
subject = subject.decode()
`Preformatted text`sender = msg.get("From")
print('Subject:', subject)
print('From:', sender)
for part in msg.walk():
if part.get_content_maintype() == 'multipart':
continue
if part.get('Content-Disposition') is None:
continue
filename = part.get_filename()
if filename:
folder_name = "attachments"
if not os.path.isdir(folder_name):
os.mkdir(folder_name)
filepath = os.path.join(folder_name, filename)
open(filepath, 'wb').write(part.get_payload(decode=True))
print(f"Attachment '{filename}' saved at '{filepath}'")
client = MongoClient("mongodb+srv://user:<pass>@cluster0.pmutnmy.mongodb.net/projectpy")
db = client.get_database("spreadsheet")
collection = db.spreadsheet