Skip to content

A community-supported supercharged document management system: scan, index and archive all your documents

Merge remote-tracking branch 'paperless/dev' into feature-consume-eml

phail47851ddd3f54
diff --cc src/paperless_mail/mail.py
index 8beb17382,2b3267aeb..a8476234e
--- a/src/paperless_mail/mail.py
+++ b/src/paperless_mail/mail.py
@@@ -155,51 -156,62 +156,77 @@@ class MailAccountHandler(LoggingMixin)
self.log("debug", f"Processing mail account {account}")
total_processed_files = 0
+ try:
+ with get_mailbox(
+ account.imap_server,
+ account.imap_port,
+ account.imap_security,
+ ) as M:
+
- with get_mailbox(
- account.imap_server,
- account.imap_port,
- account.imap_security,
- ) as M:
-
- try:
- M.login(account.username, account.password)
-
- except UnicodeEncodeError:
- self.log("debug", "Falling back to AUTH=PLAIN")
try:
- # rfc2595 section 6 - PLAIN SASL mechanism
- client: IMAP4 = M.client
- encoded = (
- b"\0"
- + account.username.encode("utf8")
- + b"\0"
- + account.password.encode("utf8")
- )
- # Assumption is the server supports AUTH=PLAIN capability
- # Could check the list with client.capability(), but then what?
- # We're failing anyway then
- client.authenticate("PLAIN", lambda x: encoded)
-
- # Need to transition out of AUTH state to SELECTED
- M.folder.set("INBOX")
- except Exception:
+ M.login(account.username, account.password)
++
++ except UnicodeEncodeError:
++ self.log("debug", "Falling back to AUTH=PLAIN")
++ try:
++ # rfc2595 section 6 - PLAIN SASL mechanism
++ client: IMAP4 = M.client
++ encoded = (
++ b"\0"
++ + account.username.encode("utf8")
++ + b"\0"
++ + account.password.encode("utf8")
++ )
++ # Assumption is the server supports AUTH=PLAIN capability
++ # Could check the list with client.capability(), but then what?
++ # We're failing anyway then
++ client.authenticate("PLAIN", lambda x: encoded)
++
++ # Need to transition out of AUTH state to SELECTED
++ M.folder.set("INBOX")
++ except Exception:
++ self.log(
++ "error",
++ "Unable to authenticate with mail server using AUTH=PLAIN",
++ )
++ raise MailError(f"Error while authenticating account {account}")
+ except Exception as e:
self.log(
"error",
- "Unable to authenticate with mail server using AUTH=PLAIN",
+ f"Error while authenticating account {account}: {e}",
+ exc_info=False,
)
- raise MailError(f"Error while authenticating account {account}")
- except Exception:
- self.log("error", "Unable to authenticate with mail server")
- raise MailError(f"Error while authenticating account {account}")
+ raise MailError(
+ f"Error while authenticating account {account}",
+ ) from e
+ self.log(
+ "debug",
+ f"Account {account}: Processing "
+ f"{account.rules.count()} rule(s)",
+ )
+
+ for rule in account.rules.order_by("order"):
+ try:
+ total_processed_files += self.handle_mail_rule(M, rule)
+ except Exception as e:
+ self.log(
+ "error",
+ f"Rule {rule}: Error while processing rule: {e}",
+ exc_info=True,
+ )
+ except MailError:
+ raise
+ except Exception as e:
self.log(
- "debug",
- f"Account {account}: Processing " f"{account.rules.count()} rule(s)",
+ "error",
+ f"Error while retrieving mailbox {account}: {e}",
+ exc_info=False,
)
- for rule in account.rules.order_by("order"):
- try:
- total_processed_files += self.handle_mail_rule(M, rule)
- except Exception as e:
- self.log(
- "error",
- f"Rule {rule}: Error while processing rule: {e}",
- exc_info=True,
- )
-
return total_processed_files
- def handle_mail_rule(self, M, rule: MailRule):
- def handle_mail_rule(self, M: MailBox, rule):
++ def handle_mail_rule(self, M: MailBox, rule: MailRule):
self.log("debug", f"Rule {rule}: Selecting folder {rule.folder}")
@@@ -289,113 -313,76 +331,113 @@@
processed_attachments = 0
- for att in message.attachments:
+ if (
+ rule.consumption_scope == MailRule.ConsumptionScope.EML_ONLY
+ or rule.consumption_scope == MailRule.ConsumptionScope.EVERYTHING
+ ):
+ os.makedirs(settings.SCRATCH_DIR, exist_ok=True)
+ _, temp_filename = tempfile.mkstemp(
+ prefix="paperless-mail-",
+ dir=settings.SCRATCH_DIR,
+ )
+ with open(temp_filename, "wb") as f:
+ f.write(message.obj.as_bytes())
- if (
- not att.content_disposition == "attachment"
- and rule.attachment_type
- == MailRule.AttachmentProcessing.ATTACHMENTS_ONLY
- ):
- self.log(
- "debug",
- f"Rule {rule}: "
- f"Skipping attachment {att.filename} "
- f"with content disposition {att.content_disposition}",
- )
- continue
-
- if rule.filter_attachment_filename:
- # Force the filename and pattern to the lowercase
- # as this is system dependent otherwise
- if not fnmatch(
- att.filename.lower(),
- rule.filter_attachment_filename.lower(),
+ self.log(
+ "info",
+ f"Rule {rule}: "
+ f"Consuming eml from mail "
+ f"{message.subject} from {message.from_}",
+ )
+
+ async_task(
+ "documents.tasks.consume_file",
+ path=temp_filename,
+ override_filename=pathvalidate.sanitize_filename(
+ message.subject + ".eml",
+ ),
+ override_title=message.subject,
+ override_correspondent_id=correspondent.id if correspondent else None,
+ override_document_type_id=doc_type.id if doc_type else None,
- override_tag_ids=[tag.id] if tag else None,
++ override_tag_ids=tag_ids,
+ task_name=message.subject[:100],
+ )
+ processed_attachments += 1
+
+ if (
+ rule.consumption_scope == MailRule.ConsumptionScope.ATTACHMENTS_ONLY
+ or rule.consumption_scope == MailRule.ConsumptionScope.EVERYTHING
+ ):
+ for att in message.attachments:
+
+ if (
+ not att.content_disposition == "attachment"
+ and rule.attachment_type
+ == MailRule.AttachmentProcessing.ATTACHMENTS_ONLY
):
+ self.log(
+ "debug",
+ f"Rule {rule}: "
+ f"Skipping attachment {att.filename} "
+ f"with content disposition {att.content_disposition}",
+ )
continue
- title = self.get_title(message, att, rule)
+ if rule.filter_attachment_filename:
+ # Force the filename and pattern to the lowercase
+ # as this is system dependent otherwise
+ if not fnmatch(
+ att.filename.lower(),
+ rule.filter_attachment_filename.lower(),
+ ):
+ continue
- # don't trust the content type of the attachment. Could be
- # generic application/octet-stream.
- mime_type = magic.from_buffer(att.payload, mime=True)
+ title = self.get_title(message, att, rule)
- if is_mime_type_supported(mime_type):
+ # don't trust the content type of the attachment. Could be
+ # generic application/octet-stream.
+ mime_type = magic.from_buffer(att.payload, mime=True)
- os.makedirs(settings.SCRATCH_DIR, exist_ok=True)
- _, temp_filename = tempfile.mkstemp(
- prefix="paperless-mail-",
- dir=settings.SCRATCH_DIR,
- )
- with open(temp_filename, "wb") as f:
- f.write(att.payload)
+ if is_mime_type_supported(mime_type):
- self.log(
- "info",
- f"Rule {rule}: "
- f"Consuming attachment {att.filename} from mail "
- f"{message.subject} from {message.from_}",
- )
+ os.makedirs(settings.SCRATCH_DIR, exist_ok=True)
+ _, temp_filename = tempfile.mkstemp(
+ prefix="paperless-mail-",
+ dir=settings.SCRATCH_DIR,
+ )
+ with open(temp_filename, "wb") as f:
+ f.write(att.payload)
- async_task(
- "documents.tasks.consume_file",
- path=temp_filename,
- override_filename=pathvalidate.sanitize_filename(
- att.filename,
- ),
- override_title=title,
- override_correspondent_id=correspondent.id
- if correspondent
- else None,
- override_document_type_id=doc_type.id if doc_type else None,
- override_tag_ids=tag_ids,
- task_name=att.filename[:100],
- )
+ self.log(
+ "info",
+ f"Rule {rule}: "
+ f"Consuming attachment {att.filename} from mail "
+ f"{message.subject} from {message.from_}",
+ )
- processed_attachments += 1
- else:
- self.log(
- "debug",
- f"Rule {rule}: "
- f"Skipping attachment {att.filename} "
- f"since guessed mime type {mime_type} is not supported "
- f"by paperless",
- )
+ async_task(
+ "documents.tasks.consume_file",
+ path=temp_filename,
+ override_filename=pathvalidate.sanitize_filename(
+ att.filename,
+ ),
+ override_title=title,
+ override_correspondent_id=correspondent.id
+ if correspondent
+ else None,
+ override_document_type_id=doc_type.id if doc_type else None,
- override_tag_ids=[tag.id] if tag else None,
++ override_tag_ids=tag_ids,
+ task_name=att.filename[:100],
+ )
+
+ processed_attachments += 1
+ else:
+ self.log(
+ "debug",
+ f"Rule {rule}: "
+ f"Skipping attachment {att.filename} "
+ f"since guessed mime type {mime_type} is not supported "
+ f"by paperless",
+ )
return processed_attachments