I have an email server hosted on AWS EC2. I am using imap_tools for retrieving email content. when I tried to get the file through the payload, I get this return;
att.payload # bytes: b'\xff\xd8\xff\xe0\'
Please how do I get the actual file path from the payload or bytes to be saved on AWS S3 and be able to read it from my table?
I can attach a file to my mail and save it on S3 but getting the attached file coming to a mail address is my challenge.
This is a function for reading email contents with imap_tools
def imap_inbox(self):
unread_inbox = []
for msg in self.mailbox.fetch():
attachments = []
for att in msg.attachments:
attachments += [{
"filename": att.filename,
"content_type": att.content_type,
"file": att.payload,
}]
msg_dict = {
"subject": msg.subject.replace("***UNCHECKED*** ", ""),
"from_mail": msg.from_,
"to_mail": msg.to[0],
"message": msg.text,
"attachments": attachments,
}
if 'RECENT' in msg.flags:
unread_inbox += [msg_dict]
return {
"unread_inbox": unread_inbox,
}
This is my function for mail_server_inbox
def mail_server_inbox(self, request, *args, **kwargs):
# imap authentication
ad_imap = self.authenticate_imap()
inbox = ad_imap.imap_inbox()
unread_inbox = inbox.get("unread_inbox")
for msg in unread_inbox:
mail_instance = None
file_name = None
try:
attachments = msg.pop("attachments", [])
msg = {
**msg,
}
attachments = list(
map(
lambda att: {
**att,
},
attachments,
)
)
# saving the attachments in the Documents table
Document.objects.bulk_create(list(
map(lambda att: Document(**att), attachments)
))