Python: ValueError: microsecond must be in 0..999999 while using win32com - python

I'm currently trying calculate the leadtime of all outlook messages within a specific outlook folder using python. In general the script runs fine however, after roundabout 2000 emails I received the following error (part of code):
import win32com.client as win32
import pandas as pd
from datetime import date
import time
outlook = win32.Dispatch("Outlook.Application").GetNamespace("MAPI")
folder = outlook.Folders("example#example.com")
inbox = folder.Folders("Inbox")
messages = inbox.Items
df = pd.DataFrame()
index = 0
for msg in messages:
if (msg.SenderEmailType != "EX"):
print(str(msg.subject))
print('Begin date:', msg.SentOn.strftime('%Y-%m-%d'))
print('End date:',msg.LastModificationTime.strftime('%Y-%m-%d'))
df.at[index, 'Subject'] = msg.subject
df.at[index, 'Begin date'] = msg.SentOn.strftime('%Y-%m-%d')
df.at[index, 'End date'] = msg.LastModificationTime.strftime('%Y-%m-%d')
I encounterd the following error:
Traceback (most recent call last):
File "C:\Users\USER\Desktop\MailCounts.py", line 24, in <module>
print('End date:',msg.LastModificationTime.strftime('%Y-%m-%d'))
File "C:\Users\USER\AppData\Local\Programs\Python\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
I tried to debug it by selecting the specific email and put it into another outlook folder and then loop over it. But then it works fine without errors. So it seems to be folder specific?!
I have searched for several answers on the errors and the method in general. But as far as I can see, this answer was never asked before with a suitable answer.
Thanks in advance!

Related

Python: Type Error, but I don't know what to change! Question for Someone who know many about Smtplib

I wanted to do an Email writer. I saw a tutorial and this came out:
import smtplib
import os
user = os.getenv("SMTP_USER")
pwd = os.getenv("SMTP_PWO")
mail_text = "Hallo, \n\ndas ist ein Test!\n\n"
subject = "Python Mail"
MAIL_FROM = "x.muelfellner#outlook.de"
RCPT_TO = input("Empfänger: ")
DATA = "From:%s\nTo:%s\nSubject:%s\n\n%" \
(MAIL_FROM,RCPT_TO,subject,mail_text)
server = smtplib.SMTP("secure.emailsrvr.com:587")
server.starttls()
server.login(user,pwd)
server.sendmail(MAIL_FROM,RCPT_TO,DATA)
server.quit()
But when I'm running the code there's an Error. Here:
Traceback (most recent call last):
File "/home/pi/Bookshelf/Pyton/SendEmail.py", line 12, in <module>
(MAIL_FROM,RCPT_TO,subject,mail_text)
TypeError: 'str' object is not callable
I don't know what i have to change! Can someone help me?
Your problem isn't related to smtplib; it's just a syntax error.
You're inadvertently trying to call a string (I removed the \ continuation):
DATA = "From:%s\nTo:%s\nSubject:%s\n\n%"(MAIL_FROM,RCPT_TO,subject,mail_text)
It should be
DATA = "From:%s\nTo:%s\nSubject:%s\n\n%s" % (MAIL_FROM,RCPT_TO,subject,mail_text)
to format a string.

influxdb python OverflowError: timestamp out of range for platform time_t

Good news, everyone!
Today I'll be delivering an error to the stack overflow community, that i really didnt fix or find any solution by myself. and this is my first question here.
i am working with an influxdb v1.8 and using the python module influxdb, to get the data and work with it in python.
There is data with timestamps in the 1950s until today stored in the database. but I can only get data using query time conditions like
"select * from \"my_measurement\" where \"time\" >= '1970-01-01T00:00:00Z'"
if i want data before 1970 the following error msg occurred:
OverflowError: timestamp out of range for platform time_t
the error msg was raised by:
timestamp = datetime.datetime.utcfromtimestamp(epoch_s)
At InfluxDB frequently asked questions is the minimum timestamp at 1677-09-21T00:12:43.145224194Z, which makes sense because the data exists and I can visualize the data using Grafana. i also tried the query string from Grafana which looks something like this
q='SELECT * FROM "my_measurement" WHERE time >= -1243409701000ms and time <= 1627595446000ms GROUP BY time(30d) fill(null)'
and guess what, the same error.
here is some explicit code:
from influxdb import InfluxDBClient
client = InfluxDBClient(ip, port, user_name, pw, db_name)
q = 'SELECT * FROM "air_temperature_01h_dwd_historical" WHERE "STATIONS_ID"=$STATIONS_ID AND "station_name"=$station_name AND "type"=$type AND "time" >= \'1950-01-01T00:00:00Z\' AND "time" < \'1960-01-01T00:00:00Z\''
bind_params = {'STATIONS_ID': '1303', 'station_name': 'Essen-Bredeney', 'type': '01h'}
p = client.query(q, bind_params=bind_params).get_points() # crash
Traceback (most recent call last):
File "<ipython-input-112-edd8923b846b>", line 1, in <module>
p = client.query(q, bind_params=bind_params).get_points()
File "C:\ProgramData\Anaconda3\lib\site-packages\influxdb\client.py", line 521, in query
response = self.request(
File "C:\ProgramData\Anaconda3\lib\site-packages\influxdb\client.py", line 358, in request
response._msgpack = msgpack.unpackb(
File "msgpack/_unpacker.pyx", line 195, in msgpack._cmsgpack.unpackb
File "C:\ProgramData\Anaconda3\lib\site-packages\influxdb\client.py", line 1248, in _msgpack_parse_hook
timestamp = datetime.datetime.utcfromtimestamp(epoch_s)
OverflowError: timestamp out of range for platform time_t
if i leave out the time parameter, the error occurs also, as well as do not using bind_params by concatting the query string with the parameters.
please, someone out there, help! push me in the chamber of understanding

TypeError: '_Folders' object is not callable

I'm using win32.client and trying to manipulate email body text.
This was working today but I think when testing I might have broken Outlook! When I try to call an index of a _Folders object, I get a type error that it is uncallable.
I use indexes to get into my nested folders. This was working until tonight and I haven't changed any of the code.
import win32com.client
import urllib.parse
import webbrowser
from pyshorteners import Shortener
application = win32com.client.Dispatch('Outlook.Application')
namespace = application.GetNamespace('MAPI')
# 6 is the number for the main inbox
inbox_folder = namespace.GetDefaultFolder(6)
# had to create multiple objects of subfolders to get to specific directory
inbox = inbox_folder.Folders
mobile_folder = inbox(3)
mobile_folder_directory = mobile_folder.Folders
mobile_script_folder = mobile_folder_directory(2)
# using Items method to parse specific email files within the folder
messages = inbox_folder.Items
I get this error:
File "mail1.py", line 10, in mobile_folder = inbox_folders(3) TypeError: '_Folders' object is not callable
I was messing around with other code trying to monitor my inbox for new mail.
I ran some of this code in another file with some modifications to match my inboxes
import ctypes # for the VM_QUIT to stop PumpMessage()
import pythoncom
import win32com.client
import sys
# outlook config
SHARED_MAILBOX = "Your Mailbox Name"
# get the outlook instance and inbox folder
session = win32com.client.Dispatch("Outlook.Application").Session
user = session.CreateRecipient(SHARED_MAILBOX)
shared_inbox = session.GetSharedDefaultFolder(user, 6).Items # 6 is Inbox
class HandlerClass(object):
def OnItemAdd(self, item):
print("New item added in shared mailbox")
if item.Class == 43:
print("The item is an email!")
outlook = win32com.client.DispatchWithEvents(shared_inbox, HandlerClass)
def main():
print("Starting up Outlook watcher")
pythoncom.PumpMessages()
if __name__ == "__main__":
try:
status = main()
sys.exit(status)
except KeyboardInterrupt:
print("Terminating program..")
ctypes.windll.user32.PostQuitMessage(0)
sys.exit()
My suspicion is that it changed something with Outlook versions.
I also got something saying that a MAPIFolder object isn't callable. My research was showing this is an old, unsupported Outlook protocol.
Here's more data when I try to index my folders:
>>> inbox_folder
<win32com.gen_py.Microsoft Outlook 16.0 Object Library.MAPIFolder instance at 0x12191504>
>>> inbox = inbox_folder.Folders
>>> inbox
<win32com.gen_py.Microsoft Outlook 16.0 Object Library._Folders instance at 0x46668848>
>>> inbox(3)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: '_Folders' object is not callable
I still don't know what broke it, but it turns out that searching folders by index wasn't working anymore.
The solution was now searching by folder name:
inbox_folder = namespace.GetDefaultFolder(6)
# had to create multiple objects of subfolders to get to specific directory
inbox = inbox_folder.Folders
mobile_folder = inbox["Mobile"]
mobile_script_folder = mobile_folder.Folders["Mobile_4_4_Alpha"]
not sure why it fixed it but it did. yay!
don't know why but delete this file work in my case.
C:\Users\[user name]\AppData\Local\Temp\gen_py\[python version]\00062FFF-0000-0000-C000-000000000046x0x9x6.py
credit: https://blog.csdn.net/ericatardicaca/article/details/90721909

Python : Save Email Attachment with particular Subject at a given Location

I want to save attachments from outlook using Python, Attachment from a fixed email subject. I already searched it got an answer that is not working and I cannot comment. - Save using Win32 Outlook
I tried the code and here it is -
from win32com.client import Dispatch
import datetime as date
import os
outlook = Dispatch("Outlook.Application").GetNamespace("MAPI")
inbox = outlook.GetDefaultFolder("6")
all_inbox = inbox.Items
val_date = date.date.today()
sub_today = 'Download Attachment 1'
att_today = '1.csv'
for msg in all_inbox:
if msg.Subject == sub_today:
break
for att in msg.Attachments:
if att.FileName == att_today:
break
att.SaveAsFile(os.getcwd() + '\\1.csv')
att.ExtractFile('1.csv')
open(att)
att.WriteToFile('x')
Upon Executing it in Command Prompt I get error as -
D:\r>python attach.py
Traceback (most recent call last):
File "attach.py", line 21, in <module>
att.ExtractFile('1.csv')
File "C:\Program Files\Python37\lib\site-packages\win32com\client\dynamic.py", line 527, in __getattr__
raise AttributeError("%s.%s" % (self._username_, attr))
AttributeError: <unknown>.ExtractFile
Attachment object in OOM (att variable in your code) does not expose the ExtractFile method. Neither does it expose the WriteToFile method.

Python email bot Pyzmail/IMAPclient error

So I'm working on a Python script to extract text from an email and following these instructions to do so. This is the script thus far:
import imapclient
import pprint
import pyzmail
mymail = "my#email.com"
password = input("Password: ")
imapObj = imapclient.IMAPClient('imap.gmail.com' , ssl=True)
imapObj.login(mymail , password)
imapObj.select_folder('INBOX', readonly=False)
UIDs = imapObj.search(['SUBJECT Testing'])
rawMessages = imapObj.fetch([5484], ['BODY[]'])
message = pyzmail.PyzMessage.factory(rawMessages[5484]['BODY[]'])
However I'm getting this error:
message = pyzmail.PyzMessage.factory(rawMessages[5484]['BODY[]'])
KeyError: 5484
5484 being the ID for the email that the search function finds. I've also tried putting UIDs in instead of 5484, but that doesn't work either. Thanks in advance!
Thank you #Madalin Stroe .
I use python3.6.2 and pyzmail1.0.3 on Win10.
When I run
message = pyzmail.PyzMessage.factory(rawMessages[4]['BODY[]'])
The ERR shows like this:
Traceback (most recent call last):
File "PATH/TO/mySinaEmail.py", line 42, in <module>
message = pyzmail.PyzMessage.factory(rawMessages[4]['BODY[]'])
KeyError: 'BODY[]'
When I modified this to message = pyzmail.PyzMessage.factory(rawMessages[4][b'BODY[]']), it run well.
Try replacing ['BODY[]'] with [b'BODY[]']

Categories