How do i retrieve an attachment from Gmail and get it using python and store it here in mongodb?

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


If you really want to store all the data within MongoDB you should use GridFSBucket.upload_from_stream.

An alternative design is to store the files in something like AWS S3 and then store the links to the files in MongoDB.

IMAGE REMOVED BY MODERATOR BECAUSE IT EXPOSES USER CREDENTIALS

and im getting this error

Hi @Everett_Sobinsky,

You’ve exposed your user credentials in the previous screenshot. Please can you change your password for your Atlas cluster ASAP.

Mark

1 Like