Using Python to access outlook with win32com - python

I'm struggling with python integration with outlook using win32com.client.
All I am trying to do is get the most recent email from outlook and (at the moment) retrieve and print the name of the attachment
The code I'm trying to use:
import win32com.client
outlook = win32com.client.Dispatch("Outlook.Application").GetNamespcae("MAPI")
inbox = outlook.GetDefaultFolder(6)
message = inbox.GetLast()
att = message.Attachmets
print (att.filename)
Output
com_error: (-2147221005, 'Invalid class string', None, None)
Any help would really be appreciated.

The error is Outlook can't be found on the system but You have also misspelled GetNamespace, you have GetNamespcae
Change inbox.GetLast(), to messages = inbox.Items then message = messages.GetLast()
Example
import win32com.client
outlook = win32com.client.Dispatch("Outlook.Application").GetNamespace("MAPI")
inbox = outlook.GetDefaultFolder(6)
messages = inbox.Items
messages.Sort('[ReceivedTime]', False)
message = messages.GetLast()
for attachment in message.Attachments:
print(attachment.FileName)
Here is another example with filter https://stackoverflow.com/a/57931132/4539709

Related

Read attachments data from email using python

I'm attempting to use code to read an email and its attachments. I can read the email using Python's extract msg module, but not the attachment content. I am printing the attachments variable but its showing list object and not the content. The code for this is provided below. Please share your thoughts on this.
import extract_msg
import glob
import re
f = glob.glob('Time Off -DAYS.msg')
for filename in f:
msg = extract_msg.Message(filename)
msg_from = msg.sender
msg_date = msg.date
msg_subj = msg.subject
msg_message = msg.body
attachments = msg.attachments
msg_to = msg.to
print("To:-",msg_to)
print("From:-",msg_from)
print ("Date:-",msg.date)
print(attachments)
attachments data: Email has 2 attachments
[<extract_msg.attachment.Attachment object at 0x0000024444C9FEF0>, <extract_msg.attachment.Attachment object at 0x0000024444E39C50>]
you use multiple libraries to reading Email Data
smtplib , imaplib, pywin32
I use pywin32 here and use Outlook
to reading and downloading Emails and Attachments:
first, you have to install and import the module:
pip install pywin32
import win32com.client
second Establish a Connection:
outlook = win32com.client.Dispatch("Outlook.Application").GetNamespace("MAPI")
third Read the Email:
# Access to the email in the inbox
messages = inbox.Items
# get the first email
message = messages.GetFirst()
# get the last email
#message = messages.GetLast()
# to loop thru the email in the inbox
while True:
try:
print(message.subject) # get the subject of the email
# if you use messages.GetFirst() earlier
message = messages.GetNext()
# if you use messages.GetPrevious() earlier
#message = messages.GetPrevious()
except:
# if you use messages.GetFirst() earlier
message = messages.GetNext()
# if you use messages.GetPrevious() earlier
#message = messages.GetPrevious()
The above example shows how to print the subject of all of the emails in the Inbox.
Below are some of the common properties:
message.subject
message.senton # return the date & time email sent
message.senton.date()
message.senton.time()
message.sender
message.SenderEmailAddress
message.Attachments # return all attachments in the email
Download and Email Attachment:
attachments = message.Attachments
# return the first item in attachments
attachment = attachments.Item(1)
# the name of attachment file
attachment_name = str(attachment).lower()
attachment.SaveASFile(path+ '\\' + attachment_name)
I hope that works fine for you
for more information check this link and this link

Download the attachment only from the from latest outlook email using Python?

I am trying to download and save the outlook email attachment from the most recent email in a folder.
I have a code that downloads all of the attachment from a outlook folder and saves it.
Any help is appreciated.
from pathlib import Path
import win32com.client
output_dir = Path.home()/r"Documents\Test"
output_dir.mkdir(parents=True, exist_ok=True)
outlook = win32com.client.Dispatch("Outlook.Application").GetNamespace("MAPI")
inbox = outlook.GetDefaultFolder(6).folders("Sample Folder").folders("Sample Subfolder")
messages = inbox.Items
message = messages.GetFirst()
for message in messages:
if message.Subject == 'Sample Subject' or message.Subject == 'Sample Subject 2':
attachments = message.Attachments
subject = messages.GetFirst().Subject
for attachment in attachments:
attachment.SaveAsFile(output_dir / str(attachment))
I am trying to download and save the outlook email attachment from the most recent email in a folder.
To get the most recent item from the folder you need to sort the collection first by using the Sort method in the following way (VBA):
messages = inbox.Items
messages.Sort("[RecievedTime]", false)
message = messages.GetFirst()
Also iterating over all items in the folder is not really a good idea:
for message in messages:
if message.Subject == 'Sample Subject' or message.Subject == 'Sample Subject 2':
Instead, you need to use the Find/FindNext or Restrict methods of the Items class. They allows getting items that correspond to your conditions without iterating over all items in the folder. Read more about these methods in the articles that I wrote for the technical blog:
How To: Use Find and FindNext methods to retrieve Outlook mail items from a folder (C#, VB.NET)
How To: Use Restrict method to retrieve Outlook mail items from a folder

How download attachments from secondary outlook email by Python?

I need download attachment from outlook, but not from my outlook.
I need it from secondary group address (like FiTeam#email.com with pass = asdf).
Right now I have working script that downloading it from my own outlook address.
import os
path = os.path.expanduser("D:\DownloadingEmail\\replenishment")
outlook = win32com.client.Dispatch("Outlook.Application").GetNamespace("MAPI")
inbox = outlook.GetDefaultFolder(6)
messages = inbox.Items
def saveattachemnts(subject):
for message in messages:
if message.Subject.startswith(subject):
# body_content = message.body
attachments = message.Attachments
attachment = attachments.Item(1)
for attachment in message.Attachments:
attachment.SaveAsFile(os.path.join(path, str(attachment)))
if message.Subject == subject and message.Unread:
message.Unread = False
continue
saveattachemnts('Replenishment')
How can I modify it to download the attachment from inbox in FiTeam#email.com?
To access the shared inbox try the following
inbox = outlook.Folders["FiTeam#email.com"].Folders["Inbox"]
also you should fix ("D:\DownloadingEmail\\replenishment") to ("D:\\DownloadingEmail\\replenishment")
SaveAsFile(os.path.join(path, str(attachment) should be SaveAsFile(os.path.join(path, str(attachment.FileName)
message.Unread = False to message.UnRead
see my example code below-
import os
import win32com.client
path = os.path.expanduser("D:\\DownloadingEmail\\replenishment")
print(path)
outlook = win32com.client.Dispatch("Outlook.Application").GetNamespace("MAPI")
inbox = outlook.Folders["FiTeam#email.com"].Folders["Inbox"]
messages = inbox.Items
def save_attachments(subject):
for message in messages:
if message.Subject.startswith(subject):
for attachment in message.Attachments:
attachment.SaveAsFile(os.path.join(path, str(attachment.FileName)))
if message.UnRead:
message.UnRead = False
continue
save_attachments('Replenishment')
Call outlook.CreateRecipient("FiTeam#email.com"), then pass the returned Recipient object to outlook.GetSharedDefaultFolder()

Read all emails from outlook

I wanted to check how can I read all emails from outlook in python
I am using below code, but this code is reading only first mail,
import win32com.client
outlook = win32com.client.Dispatch("Outlook.Application").GetNamespace("MAPI")
inbox = outlook.GetDefaultFolder(6) # "6" refers to the index of a folder - in this case,
# the inbox. You can change that number to reference
# any other folder
messages = inbox.Items
message = messages.GetLast()
body_content = message.Body
subject = message.Subject
categories = message.Categories
print(body_content)
print(subject)
print(categories)
I tried to find a way so that we can read all emails but unable to get a solution, is anyone know how we can read all emails and store in the database.
You can iterate through the messages object to get all email content.
import win32com.client
outlook = win32com.client.Dispatch("Outlook.Application").GetNamespace("MAPI")
inbox = outlook.GetDefaultFolder(6)
messages = inbox.Items
'''message = messages.GetLast()
body_content = message.Body
subject = message.Subject
categories = message.Categories
print(body_content)
print(subject)
print(categories)'''
for message in messages:
print(message.Subject)

How to access a subfolder in Outlook inbox in Python

I have created a rule in Outlook to move all incoming messages from a particular sender to a subfolder in my Inbox.Like -
Inbox
- Subfolder
I wrote a piece of code
import win32com.client
outlook = win32com.client.Dispatch("Outlook.Application").GetNamespace("MAPI")
inbox = outlook.GetDefaultFolder(6) #6 = Inbox (without mails from the subfolder)
messages = inbox.Items
message = messages.GetLast()
body_content = message.body
print body_content #Sometimes has parsing error due to different encoding format
How can I
1) Read the mails in this particular folder inside Inbox
2) Take care of error like UnicodeEncodeError: 'charmap' codec can't encode - character maps to
print (u'\2109') issues this error too.
outlook.GetDefaultFolder(6) is "Inbox" position by default. You need to traverse the list of folders in it, so try this
inbox = outlook.GetDefaultFolder(6).Folders.Item("Your_Folder_Name")
u'\2109' looks a lot like UTF-8 encoding.
So print(body_content.encode("utf-8")) will do the trick.
outlook = win32com.client.Dispatch('outlook.application')
mapi = outlook.GetNamespace("MAPI")
inbox = mapi.GetDefaultFolder(6).Folders["SubFolder"]
mails = inbox.Items
The above method will also work.

Categories

Resources