I've been trying to print the email's body from the emails that I receive in Outlook for a while, but I'm having the following error:
Traceback (most recent call last):
File "c:\Users\RMBORGE\Desktop\PythonLib\tempCodeRunnerFile.python", line 10, in <module>
print(message.body)
File "C:\Users\RMBORGE\AppData\Roaming\Python\Python39\site-packages\win32com\client\dynamic.py", line 543, in __getattr__
ret = self._oleobj_.Invoke(retEntry.dispid,0,invoke_type,1)
pywintypes.com_error: (-2147467259, 'Unspecified error', None, None)
Could someone help me?
Please see my code below:
from email import message
import email
import win32com.client as client
outlook = client.Dispatch('Outlook.Application').GetNameSpace("MAPI")
inbox = outlook.GetDefaultFolder(6)
messages = inbox.Items
message = messages.GetLast()
print(message.body)
Please remember that Outlook folders may contain different kind of items - mails, documents, notes and etc. Before accessing any properties specific to a particular item type I'd recommend checking the MessageClass property first to make sure that you deal with a mail item and the required property exists for the item chosen.
See How to determine type of an outlook item in python for more information.
Another possible reason is security triggers in the Outlook object model. Read more about that in the Outlook Object Model Security Warnings article. Possible routes to avoid such triggers are:
Use a low-level API on which Outlook is based on - Extended MAPI. Or just consider using any wrapper around that API such as Redemption.
Use components for turning on/off security issues in Outlook, see Outlook Security Manager.
Use group policy to configure security issues when dealing with OOM.
Install any antivirus software with latest databases.
Related
I am attempting to run a python script to automate sending emails but I keep running into this error.
Any suggestions on how to fix this?
import smtplib
from email import message
from_addr = 'myemail#gmail.com'
to_addr = 'myemail#gmail.com'
subject = 'Test Email'
body = 'Test'
msg = message.Message()
msg.add_header('from', from_addr)
msg.add_header('to', to_addr)
msg.add_header('subject', subject)
msg.set_payload(body)
server = smtplib.SMTP('smtp.gmail.com', 587)
server.login(from_addr, 'password')
The error:
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "C:\Program `Files\WindowsApps\PythonSoftwareFoundation.Python.3.10_3.10.1264.0_x64__qbz5n2kfra8p0\lib\smtplib.py", line 716, in login`
raise SMTPNotSupportedError(
smtplib.SMTPNotSupportedError: SMTP AUTH extension not supported by server.
I'm not shure, but for gmail you need https://myaccount.google.com/lesssecureapps Allow less secure apps: ON setting.
Or you need Google APIs for authentication: https://developers.google.com/gmail/api/quickstart/python
I was having the same issue. Google recent ended support for "allow less secure apps" and the commonly recommended answer of using an app password also does not appear to work reliably either (it will work sometimes, but then gmail will start rejecting the authentication a day or two later).
Google's suggested quickstart guide (https://developers.google.com/gmail/api/guides/sending) is incomplete but does eventually work. In that process, you will get an error because you did not redirect the URI. You'll need to add this to the approved URIs within your google API console and then follow the link again.
You will hit a 2nd issue because your user will not be approved to use your own project. You will need to add your gmail account as a test user.
Once you have the URI forwarding correctly and you are approved to use your own app, you will then get an error (HTTP Error 403) because the Gmail API will not be activated. Go back to the google API console and enable the Gmail API. Finally, you can run the quickstart.py file again and it will complete without errors.
I have not yet tested this solution for actually sending email, but it does appear to grant your app full access to the email account that you set up. I also do not know if this is a long term solution or if there are tokens which will time out.
Based on the difficulty of this, it seems that finding another email SMTP service may be a better solution if that's possible for your situation.
You can get your app password to login your account via smtp. This solves the issue for less secure app feature.
Coming towards your error it might be due to something is not supported but here I see you have not started TLS connection. Starting TLS connection can solve this error if there's no other issue.
server = smtplib.SMTP('smtp.gmail.com', 587)
server.starttls()
server.login(from_addr, 'password') # here you can need to use app password
This should solve the error most of the time if other things are correct.
I want to automate downloading a zipfile on another organization's sharepoint site that they have shared with my organization, inviting us as a guest using a generic company email address so we can access the files. To gain access, I provide the company email address as username and its associated AD password which authenticates access through our MS 365 organization account.
This works fine manually, but when attempting to do it through shareplum I get a credentials error.
Here is my code:
from shareplum import Site
from shareplum import Office365
from shareplum.site import Version
sharepointUsername = 'elvis.presley#suspiciousminds.org'
sharepointPassword = 'oogabooga123'
sharepointSite = 'https://abc.sharepoint.com/sites/ClientLogin/Shared Documents/Graceland/'
authcookie = Office365(website, username=sharepointUsername,
password=sharepointPassword).GetCookies()
site = Site(sharepointSite, version=Version.v365, authcookie=authcookie)
And here is the error:
Traceback (most recent call last):
File "<string>", line 11, in <module>
File "C:\arcgispro-py3-clone2\lib\site-packages\shareplum\office365.py", line 88, in get_cookies
sectoken = self.get_security_token(self.username, self.password)
File "C:\arcgispro-py3-clone2\lib\site-packages\shareplum\office365.py", line 80, in get_security_token
raise Exception('Error authenticating against Office 365. Error from Office 365:', message[0].text)
Exception: ('Error authenticating against Office 365. Error from Office 365:', 'AADSTS50126: Error validating credentials due to invalid username or password.')
Any clue as why this is not working? I've checked the credentials several times using them to log in manually and it works every time (obviously the example does not have the real username/password)?
You’re not alone, this seems to be a common issue with shareplum over the past 6 months. There’s an open issue on GitHub. The code owner is aware and is having difficulty debugging the issue.
GitHub issue: https://github.com/jasonrollins/shareplum/issues/84
I recommend working closely with the code owner to debug and resolve the issue on GitHub, or using a different library/solution altogether. Another user commented on the issue and referenced a solution that utilizes the requests library to retrieve a file that you may find useful: https://github.com/jasonrollins/shareplum/issues/84#issuecomment-627986466 .
I have a instrument at work that emails me a file containing raw data, I can go into my email and download them easily enough but when I have multiple files (which it sends as multiple emails) it gets a bit tedious.
I'm looking at using python and imaplib to login to my email account, search for emails from a known email address within the past day or so and then download any attachments to a directory. So I thought a script might help here.
I've setup a gmail account and altered the settings so that I can connect using imap from a shell, however I'm lost as to where to go from here.
Could someone point me in the right direction as to what I need to do to make this happen.
Here is a repository that is forked off imaplib (made compatible with Python3.6, did not test other versions)
https://github.com/christianwengert/mail
The following snippet checks all unseen messages, then returns their attachments:
server = IMAPClient(imap, use_uid=True, ssl=993)
server.login(username, password)
server.select_folder('INBOX')
message_ids = server.search([b'NOT', b'SEEN']) # UNSEEN
messages = server.fetch(message_ids, data=['ENVELOPE', 'BODYSTRUCTURE', 'RFC822.SIZE'])
for mid, content in messages.items():
bodystructure = content[b'BODYSTRUCTURE']
text, attachments = walk_parts(bodystructure, msgid=mid, server=server)
HTH
I want to do a "simple" task in Outlook, with a Python script, but I'm usually in PHP and it's a little bit difficult for me.
Here is the task:
Open Outlook (it's ok for that)
Check a specific account, example: test#test.com
Open the last mail
I want to open the "real" message windows at screen, not just to access to the content.
Is it possible?
For your second requirement, could the account be a shared inbox?
Here is the code for the rest:
import win32com.client
outlook = win32com.client.Dispatch("Outlook.Application").GetNamespace("MAPI")
inbox = outlook.GetDefaultFolder(6)
messages = inbox.Items
message = messages.GetLast()
message.display()
Here is another example with exchangelib in python:
https://medium.com/#theamazingexposure/accessing-shared-mailbox-using-exchangelib-python-f020e71a96ab
Here is the snippet to get the last email. I did it using a combination of order by and picking the first one or the last one depending on how you order by:
from exchangelib import Credentials, Account, FileAttachment
credentials = Credentials('FirstName.LastName#Some_Domain.com', 'Your_Password_Here')
account = Account('FirstName.LastName#Some_Domain.com', credentials=credentials, autodiscover=True)
filtered_items = account.inbox.filter(subject__contains='Your Search String Here')
print("Getting latest email for given search string...")
for item in account.inbox.filter(subject__contains='Your Search String Here').order_by('-datetime_received')[:1]: #here is the order by clause:: you may use order_by('datetime_received')[:-1]
print(item.subject, item.text_body.encode('UTF-8'), item.sender, item.datetime_received) #item.text_body.encode('UTF-8') gives you the content of email
while trying to open the real message might be a bit of a challenge but I will update this section once I have a solution. If I may ask:: are you looking at a python only solution ?
Years back I built a simple mail form that has been working like a champ, but in the last couple months the logs show I'm getting an error when EmailMessage's send() method gets called.
I wrote a quick test to see if a stripped down version of an EmailMessage would work without error:
class TestEmail(webapp.RequestHandler):
def get(self):
fromAddress = "APPOWNEREMAIL#gmail.com"
email = mail.EmailMessage(sender=fromAddress)
email.to = self.request.get('to') + '#gmail.com'
email.subject = "Test Email"
email.body = "Testing the email system"
email.html = "<strong>Testing the <em>email</em> system</strong>"
email.check_initialized()
email.send()
Simple enough, but if I call that with:
http://MYAPPNAME.appspot.com/test-email?to=TOTALLYLEGITEMAIL
I still get the same error (note check_initialized() isn't throwing an error):
Traceback (most recent call last):
File "/base/python_runtime/python_lib/versions/1/google/appengine/ext/webapp/_webapp25.py", line 701, in __call__
handler.get(*groups)
File "/base/data/home/apps/s~myappname/3.354527616249361817/myappname.py", line 370, in get
email.send()
File "/base/python_runtime/python_lib/versions/1/google/appengine/api/mail.py", line 895, in send
raise e
ApplicationError: ApplicationError: 1 Internal error
I haven't made any recent changes to the app, it's a lightly used app well below quota, it's sending as the email associated with the app owner and after spending a few hours scrutinizing the code, I'm still no closer to an answer.
Even more distressing, every Google search I come up with offers no new help. The best I could find was this question: Google app engine send mail service raises exception which sounds exactly like my problem, but in that case there wasn't a solution, the problem just went away.
Any idea how I can track this one down? Let me know if I need to clarify anything. Thanks!
What is your appid?
There is currently an issue that sending mail from an application whose appid is the same as the owner's gmail name will fail. eg, I have a gmail address "moishel at gmail dot com"; if I created an app whose appid is 'moishel' (before version 1.6.0) it will fail when trying to send mail. Note that this problem does not exist for apps created with version 1.6.0 or after.
Here's the issue: http://code.google.com/p/googleappengine/issues/detail?id=5320