Value Error: Microsecond must be in 0..999999 - python

Hi i am using the library win32com.client to read emails from an outlook sharedmailbox and i get a value error:Microsecond must be in 0..999999. I tried formatting the "ReceivedDate" as "%Y-%D-%M %H:%M:%S" with no luck. do you know what else i can try?
Question 2: im trying to count how many emails have not been replied to but i dont see a property for that in the documentation. SO i went with reading all that have a "FlagRequest" marked as completed. I would have the representatives go with this process as a way to tell if the emails have been complete.
import win32com.client
def readEmail():
outlook = win32com.client.Dispatch("Outlook.Application").GetNamespace("MAPI")
folder = outlook.Folders.Item('SharedMailbox, TEST')
inbox = folder.Folders.Item('Inbox')
messages = inbox.Items
counter = 0
for message in messages:
rcvd_dt = message.ReceivedTime
if message.FlagRequest != 'Follow up' and str(rcvd_dt) >= '2020-06-01 00:00:00':
counter +=1
print(counter)
print(received_dt)
traceback:
Traceback (most recent call last):
File "C:/Users/TEST/PycharmProjects/TEST/Metrics.py", line 422, in <module>
main()
File "C:/Users/TEST/PycharmProjects/TEST/Metrics.py", line 409, in main
readEmail()
File "C:/Users/TEST/PycharmProjects/TEST/Metrics.py", line 89, in readEmail
rcvd_dt = message.ReceivedTime
File "C:\Program Files (x86)\Python37-32\lib\site-
packages\win32com\client\dynamic.py", line 516, in __getattr__
ret = self._oleobj_.Invoke(retEntry.dispid,0,invoke_type,1)
ValueError: microsecond must be in 0..999999
What i tried:
rcvd_dt= datetime.strptime(str(rcvd_dt.split('.')[0], '%Y-%m-%d %H:%M:%S')
but get error:
valueerror: time data '2' does not match format %Y-%m-%d %H:%M:%S.%f'
if i try:
rcvd_dt= datetime.strptime(str(rcvd_dt.split('.')[0], '%Y-%m-%d %H:%M:%S.%f')
i get :
valueerror: time data '2020-06-16 08:53:56' does not match format %Y-%m-%d.%f'

Related

pywintypes.com_error. in Outlook. I am creating an outlook appointment, it errors on assigning time. Says that the object doesn't support method

I have this code:
import win32com.client
import pythoncom
import datetime
def saveMeeting(start, end, subject, location, attachments, recipients):
outlook = win32com.client.Dispatch("Outlook.Application", pythoncom.CoInitialize())
ns = outlook.GetNamespace("MAPI")
session = ns.Session
## Find the accounts that are of exchange type
acc = []
for account in session.Accounts:
if account.AccountType == 0: #0 - outlookExchange, 1 - outlookIMAP, 2 - outlookPop3
#print(account)
acc.append(account)
appointment = outlook.CreateItem(1) #1 - AppointmentItem
# Fill in the data needed
appointment.SendUsingAccount = acc
appointment.Start = datetime.datetime.strptime(start, "%Y-%m-%d %H:%M:%S") #yyyy-MM-dd hh:mm:ss
appointment.StartTimeZone = outlook.TimeZones("Central Standard Time")
appointment.End = datetime.datetime.strptime(end, "%Y-%m-%d %H:%M:%S") #yyyy-MM-dd hh:mm:ss
appointment.EndTimeZone = outlook.TimeZones("Central Standard Time")
appointment.Subject = f"HOLDER-{subject}"
appointment.Location = location
appointment.MeetingStatus = 1
if attachments != '':
appointment.Attachments.Add(attachments)
recipients = filter(None, recipients)
for recipient in recipients:
r = appointment.Recipients.Add(recipient)
r.Resolve()
appointment.Save()
# Only use .Display() if using tkinter
appointment.Display()
saveMeeting("2022-03-02 14:00:00", "2022-03-02 14:30:00", "Subject of the Meeting","Location", "", ["altisjessienino18#gmail.com", "ajn_dulay#smcm.edu.ph"])
But, it just gives me this error.
Traceback (most recent call last):
File "C:\Users\user\Desktop\Project\createInvite.py", line 100, in <module>
saveMeeting("2022-03-02 14:00:00", "2022-03-02 14:30:00", "Subject of the Meeting","Location", "", ["user1#gmail.com", "user2#smcm.edu.ph"])
File "C:\Users\user\Desktop\Project\createInvite.py", line 42, in saveMeeting
appointment.End = datetime.datetime.strptime(end, "%Y-%m-%d %H:%M:%S") #yyyy-MM-dd hh:mm:ss
File "C:\Users\user\AppData\Local\Programs\Python\Python38\lib\site-packages\win32com\client\dynamic.py", line 686, in __setattr__
self._oleobj_.Invoke(entry.dispid, 0, invoke_type, 0, value)
pywintypes.com_error: (-2147352567, 'Exception occurred.', (4096, 'Microsoft Outlook', 'The object does not support this method.', None, 0, -2147352567), None)
I am trying to create an Appointment using pywin32 and python. But the problem is that sometimes it works, and sometimes it does not like this code here, it seems like there is a problem that I could not see or hidden somewhere. The main issue here is that I am trying to fix the date problem (it turns to UTC+6 instead of UTC-6).
It seems you didn't format the date correctly. Try to use the following format:
"mm/dd/yyyy hh:mm AMPM"
Also it make sense to set the time zone first (before start and end of the meeting).

Retrieve Emails From Certain Date

I am trying to retrieve emails > than 12/1/2020 but get a ValueError. I tried adding .replace(microseconds=0) to str(message.ReceivedTime) but still getting this error.
error
Traceback (most recent call last):
File "C:/Users/SLID/PycharmProjects/PPC_COASplitter/PPC_Ack.py", line 178, in <module>
get_url = readEmail()
File "C:/Users/zSLID/PycharmProjects/PPC_COASplitter/PPC_Ack.py", line 144, in readEmail
if str(message.ReceivedTime) >= '2020-12-1 00:00:00' and 'P1 Cust ID 111111 File ID' in message.Subject:
File "C:\Program Files (x86)\Python37-32\lib\site-packages\win32com\client\dynamic.py", line 516, in __getattr__
ret = self._oleobj_.Invoke(retEntry.dispid,0,invoke_type,1)
ValueError: microsecond must be in 0..999999
code
def readEmail():
outlook = win32com.client.Dispatch("Outlook.Application").GetNamespace("MAPI")
folder = outlook.Folders.Item('SharedMailbox, PPC-Investigation')
inbox = folder.Folders.Item('Inbox')
messages = inbox.Items
messages.Sort("[ReceivedTime]", True)
for message in messages:
if str(message.ReceivedTime) >= '2020-12-1 00:00:00' and 'P1 Cust ID 111111 File ID' in message.Subject:
print("")
print('Received from: ',message.Sender)
print("To: ", message.To)
print("Subject: ", message.Subject)
print("Received: ", message.ReceivedTime)
print("Message: ", message.Body)
get_url = re.findall(r'(https?://[^\s]+)', message.Body)[2].strip('>')
return get_url
Firstly, you are comparing DateTime value with a string. Convert the string to a date-time value.
Secondly, never loop through all items in a folder, use Items.Restrict instead (returns a restricted Items collection):
messages = messages.Restrict("[Received] >= '1/12/2020 0:00am' ")

Python exchangelib raise ValueERROR datetime_received

I'm trying to check how many emails have been received from the specified sender.email_address the past 24 hours, but I get an error from this code
Traceback (most recent call last):
File "c:/Users/fmi/Desktop/Python/emailtest.py", line 13, in
for item in testfolder.all()
File "C:\Users\fmi\AppData\Local\Programs\Python\Python38-32\lib\site-packages\exchangelib\queryset.py", line 507, in order_by
raise ValueError("%s in order_by()" % e.args[0])
ValueError: Unknown field path '-datetime_recieved' on folders [Messages(Root(<exchangelib.account.Account object at 0x020A81F0>, '[self]', 'root', 8, 0, 62, None, 'AQMkADI2YmY4MjAwAC1mNTBkLTQyMzEtYTM0Yi04NTdmZDRhMDE0MGQALgAAA+xnYBMGPANEmpY/yEHuM6wBAEYSp+OGVQhHl3U8WgJ/ZQAAAwEBAAAAAA==', 'AQAAABYAAABGEqfjhlUIR5d1PFoCf2UAAAAcRKyn'), 'Test', 26821, 26654, 0, 'IPF.Note', 'AQMkADI2YmY4MjAwAC1mNTBkLTQyMzEtYTM0Yi04NTdmZDRhMDE0MGQALgAAA+xnYBMGPANEmpY/yEHuM6wBAEYSp+OGVQhHl3U8WgJ/ZQAAAw0rAAAA', 'AQAAABYAAABGEqfjhlUIR5d1PFoCf2UAAAAcRKxr')] in order_by()
when trying to print. I also want it to give me an alert if the email count is 0.
from exchangelib import Credentials, Account, UTC_NOW
from collections import defaultdict
from datetime import timedelta
credentials = Credentials('fmi#.dk', 'something')
a = Account('fmi#.dk', credentials=credentials, autodiscover=True)
counts = defaultdict(int)
testfolder = a.inbox.parent / 'Test'
since = UTC_NOW() - timedelta(hours=24)
for item in testfolder.all()\
.only('sender', 'subject')\
.filter(datetime_received__gt=since)\
.order_by('-datetime_received'):
if item.sender.email_address == 'info#something.dk':
counts[item.sender.email_address, item.subject] += 1
print(counts)

How to get email address of group member from LDAP using Python

I am trying to get the email addresses of AD group members of a particular LDAP group using python.
I have following code. The Print m statement writes something like below.
Output:
CN=Admin_abc20,OU=Admin ID's,OU=TEST1,DC=other_example,DC=example,DC=com
CN=leterd,OU=Employees,OU=BACD,DC=na,DC=example,DC=com
CN=mytest37,OU=Employees,OU=SUNPH,DC=na,DC=example,DC=com
CN=Doe Mestre\, John,OU=Partners & Contractors,OU=TEST1,DC=other_example,DC=example,DC=com
CN=Robin\, Mark [ABCD],OU=Partners & Contractors,OU=JJCUS,DC=na,DC=example,DC=com
CN=San Irdondo\, Paul [TEST1 Non-ABC],OU=Partners & Contractors,OU=TEST1,DC=other_example,DC=example,DC=com
My Code:
def get_group_members(group_name, ad_conn, basedn=AD_USER_BASEDN):
members = []
ad_filter = AD_GROUP_FILTER.replace('My_Group_Name', group_name)
result = ad_conn.search_s(basedn, ldap.SCOPE_SUBTREE, ad_filter)
if result:
if len(result[0]) >= 2 and 'member' in result[0][1]:
members_tmp = result[0][1]['member']
for m in members_tmp:
print m
#email = ad_conn.search_s(m, ldap.SCOPE_SUBTREE,'(objectClass=*)',['mail'])
#print email
Now when I remove comment from last 2 lines of my code to get the email address of persons, I get following error, please note that I have changed by company's ldap identifiers to example/test.
Can you please help me with this? I am a newbie to python.
Traceback (most recent call last):
File "/app/abc/python/Test_new.py", line 81, in <module>
group_members = get_group_members(group_name, ad_conn)
File "/app/abc/python/Test_new.py", line 58, in get_group_members
email = ad_conn.search_s(m, ldap.SCOPE_SUBTREE,'(objectClass=*)', ['mail'])
File "/usr/lib64/python2.6/site-packages/ldap/ldapobject.py", line 516, in search_s
return self.search_ext_s(base,scope,filterstr,attrlist,attrsonly,None,None,timeout=self.timeout)
File "/usr/lib64/python2.6/site-packages/ldap/ldapobject.py", line 510, in search_ext_s
return self.result(msgid,all=1,timeout=timeout)[1]
File "/usr/lib64/python2.6/site-packages/ldap/ldapobject.py", line 436, in result
res_type,res_data,res_msgid = self.result2(msgid,all,timeout)
File "/usr/lib64/python2.6/site-packages/ldap/ldapobject.py", line 440, in result2
res_type, res_data, res_msgid, srv_ctrls = self.result3(msgid,all,timeout)
File "/usr/lib64/python2.6/site-packages/ldap/ldapobject.py", line 446, in result3
ldap_result = self._ldap_call(self._l.result3,msgid,all,timeout)
File "/usr/lib64/python2.6/site-packages/ldap/ldapobject.py", line 96, in _ldap_call
result = func(*args,**kwargs)
ldap.REFERRAL: {'info': 'Referral:\nldap://ab.example.com/CN=Radfde3,OU=Partners%20&%20Contractors,OU=JANBE,DC=eu,DC=example,DC=com', 'desc': 'Referral'}
I don't know much about Python but I think your problem is with the LDAP filter. Try this for the last 2 lines of code:
email = ad_conn.search_s(m, ldap.SCOPE_SUBTREE,'(&(objectClass=person)(mail=*))')
print email
I hope this helps!

Python reading date from excel throws error

I am trying to read date from excel file using xlrd module. Below is my code for this :
# Variables
myfile = '/home/mobaxterm/.git/Operation_Documentation/docs/Servicing Portal User & Certificate Inventory.xlsx'
mydate = 'Expiration Date'
row_head = 0
# Import required modules
import xlrd
import datetime
today = datetime.date.today()
book = xlrd.open_workbook(myfile)
sheet = book.sheet_by_index(1)
for col_index in range(sheet.ncols):
print xlrd.cellname(row_head,col_index),"-",
print sheet.cell(row_head,col_index).value
if sheet.cell(row_head,col_index).value == mydate:
for raw_index in range(sheet.nrows):
expire = sheet.cell(raw_index,col_index).value
print expire
expire_date = datetime.datetime(*xlrd.xldate_as_tuple(expire, book.datemode))
print 'datetime: %s' % expire_date
break
While running the code i am getting following error :
Traceback (most recent call last):
File "cert_monitor.py", line 31, in <module>
expire_date = datetime.datetime(*xlrd.xldate_as_tuple(expire, book.datemode))
File "/usr/lib/python2.6/site-packages/xlrd/xldate.py", line 61, in xldate_as_tuple
xldays = int(xldate)
ValueError: invalid literal for int() with base 10: 'Expiration Date'
Can anyone suggest what could be the issue here?
Thanks for your time.
I believe that you should only skip the header:
for raw_index in range(1, sheet.nrows):
...
You are checking that sheet.cell(row_head,col_index).value == mydate, and then you want to iterate over the rows, but you should skip row_head first - it is ==mydate, which is not a date but a simple 'Expiration Date' string.

Categories

Resources