ravecoder
ravecoder

Reputation: 201

Use python to connect to outlook and read emails and attachments then write them to an output file

I am trying to connect to outlook using python and read emails and write them to an output file along with all the corresponding attachments.

This is what I have so far:

import win32com.client
import unicodecsv as csv
import os

output_file = open('./outlook_farming_001.csv','wb')
output_writer = csv.writer(output_file, delimiter=';', encoding='latin2')

outlook = win32com.client.Dispatch("Outlook.Application").GetNamespace("MAPI")
inbox = outlook.GetDefaultFolder(6).Folders.Item("Security Availabilities")
messages = inbox.Items

for i, message in enumerate(messages):
    try:

        sender = message.SenderName
        sender_address = message.SenderEmailAddress
        sent_to = message.To
        date = message.LastModificationTime
        subject = message.subject
        body = message.body

        attachments = message.Attachments
        attachment = attachments.Item(1)
        for attachment in message.Attachments:
            attachment.SaveAsFile(os.path.join(output_file, str(attachment)))

        output_writer.writerow([
            sender,
            sender_address,
            subject,
            body,
            attachment])

    except Exception as e:
        ()

output_file.close()

Without the attachment stuff in the code- it works fine. I am able to read all the emails from my specific subfolder.

However, I am unable to read, save and display attachments along with their corresponding emails.

Upvotes: 2

Views: 9606

Answers (1)

Jim Eisenberg
Jim Eisenberg

Reputation: 1500

I think your mistake is in using str(attachment) in the filename - this will cause trouble because it should give some sort of '<COMObject <unknown>>' string.

Instead, use the following:

    for attachment in message.Attachments:
        attachment.SaveAsFile(os.path.join(output_file, attachment.FileName))

I hope this helps!

Upvotes: 3

Related Questions