0

I use the code below to extract the attachment from an email, but the problem is that I need to extract an attachment inside an email which is already an attachment of an email. It goes like this :

email -> email (as an attachment) -> attachment

Can someone help ? I have a shit ton of email attachment to extract...

The code I used:

from pathlib import Path  #core python module
import win32com.client  #pip install pywin32

# Create output folder
output_dir = Path.cwd() / "Output"
output_dir.mkdir(parents=True, exist_ok=True)

# Connect to outlook
outlook = win32com.client.Dispatch("Outlook.Application").GetNamespace("MAPI")

# Connect to folder
#inbox = outlook.Folders("youremail@provider.com").Folders("Inbox")
inbox = outlook.GetDefaultFolder(6)
# https://docs.microsoft.com/en-us/office/vba/api/outlook.oldefaultfolders
# DeletedItems=3, Outbox=4, SentMail=5, Inbox=6, Drafts=16, FolderJunk=23

# Get messages
messages = inbox.Items

for message in messages:
    subject = message.Subject
    body = message.body
    attachments = message.Attachments

    # Create separate folder for each message
    target_folder = output_dir / str(subject)
    target_folder.mkdir(parents=True, exist_ok=True)

    # Write body to text file
    Path(target_folder / "EMAIL_BODY.txt").write_text(str(body))

    # Save attachments
    for attachment in attachments:
        attachment.SaveAsFile(target_folder / str(attachment))

I tried to add a loop, to get the item inside the item. It didn't work

  • "didn't work" is not a helpful problem description. What happens when you run your code, and what did you expect to happen instead? Any errors? See [ask]. – Robert Nov 10 '22 at 16:02
  • Hi sorry for the absence of details. So I get the following error : Error: [WinError 123] The filename, directory name, or volume label syntax is incorrect and python project\exatraction outlook.py", line 30, in target_folder.mkdir(parents=True, exist_ok=True) File "C:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.10_3.10.2288.0_x64__qbz5n2kfra8p0\lib\pathlib.py", line 1175, in mkdir self._accessor.mkdir(self, mode). I was expecting the programm to run, get the attachment in the email which is also an attachment (file type : outlook item file) inside an email – Alec Ric Nov 10 '22 at 16:30
  • So you are trying to create an invalid folder name. This has nothing to do with email or attachments. My guess is that you have a colon in the subject, maybe from a `Re:` prefix. Windows doesn't allow colons in file or folder names. Clean up the names before you try to create files and folders. – Robert Nov 10 '22 at 16:36

1 Answers1

0

The problematic lines of code are:

  # Create separate folder for each message
    target_folder = output_dir / str(subject)
    target_folder.mkdir(parents=True, exist_ok=True)

Make sure that the Subject property value doesn't contain forbidden symbols. Windows (and linux) has a number of symbols forbidden to use in folder and file names. See What characters are forbidden in Windows and Linux directory names? for more information.

Second, you need to check the attachment type by checking the Attachment.Type property to make sure that you deal with a real file attached, not URL or linked attachments.

4096, 'Microsoft Outlook', "Cannot save the attachment. You don't have appropriate permission to perform this operation."

Make sure that you pass a valid file path to the SaveAsFile method. You must specify the full attachment file name including the name part. Most probably you are only specifying the directory name, but you need to concatenate the directory and file name (you may use the DisplayName property of the attachment object for the filename).

Eugene Astafiev
  • 47,483
  • 3
  • 24
  • 45
  • I got rid of the subject in the message to see if it would work, but now I have the following problem. ile "c:\Users\arichards\python project\exatraction outlook.py", line 38, in attachment.SaveAsFile(target_folder / str(attachment)) File ">", line 2, in SaveAsFile pywintypes.com_error: (-2147352567, 'Exception occurred.', (4096, 'Microsoft Outlook', "Cannot save the attachment. You don't have appropriate permission to perform this operation.", None, 0, -2147287035), None) – Alec Ric Nov 10 '22 at 17:09
  • What is the exact value passed to the `SaveAsFile` method? – Eugene Astafiev Nov 10 '22 at 17:27