Python imaplib to read email from outlook without using basic authentication - python

I have an old Python application that suing Imaplib to read email, download attachments from email in inbox folder, But using basic authentication like:
mail = imaplib.IMAP4_SSL(SERVER)
mail.login(EMAIL, PASSWORD)
mail.select('inbox')
But, Microsoft is about to turn off Basic Authentication for IMAP that mean I must update to OAuth 2.0 for my application to continue working. But I've searched on internet and only find example of imaplib + OAuth2 for gmail or using win32com.client which only work on Windows (my application is running on Ubuntu).
I hope that I don't have to use other library because I have to change a lot in my code.So anyone know where to find an example about using imaplib + OAuth2.0 to access outlook mail box?

Related

python read outlook emails with oauth2

I've been using basic auth to log in to my outlook email with imap.
imap = imaplib.IMAP4_SSL("imap-mail.outlook.com")
# authenticate
imap.login(username, password)
status, messages = imap.select("INBOX")
Now that Microsoft moved to oauth2 I'm getting "Login failed" messages even although the credentials are correct.
Can anyone share a code example that connects with oauth2?
I found this guide, but it only shows the steps on the account side, not the actual connection in the app.
https://docs.emailengine.app/setting-up-oauth2-with-outlook/#:~:text=Navigate%20to%20Configuration-%3EOAuth2%20and,of%20accounts%20your%20application%20supports.
Thanks
This is my solution,
follow this guide to create an app with necessary permissions.
https://docs.emailengine.app/setting-up-oauth2-with-outlook/#:%7E:text=Navigate%20to%20Configuration-%3EOAuth2%20and,of%20accounts%20your%20application%20supports
use the following code in your app.
imap = imaplib.IMAP4_SSL(imap_host, 993)
imap.debug = 4
access_token = get_access_token_to_authenticate_imap()
imap.authenticate("XOAUTH2", lambda x:generate_auth_string(
'useremail',
access_token['access_token']))
imap.select('inbox')

Python O365 Outlook Connection Issues

I am trying to write a script in Python to grab new emails from a specific folder and save the attachments to a shared drive to upload to a database. Power Automate would work, but the file size limit to save the attachment is a meager 20 MB. I am able to authenticate the token, but am getting the following error when trying to grab the emails:
Unauthorized for url.
The token contains no permissions, or permissions can not be understood.
I have included the code I am using to connect to Microsoft Graph.
(credentials and tenant_id are correct in my code, took them out for obvious reasons
from O365 import Account, MSOffice365Protocol, MSGraphProtocol
credentials = ('xxxxxx', 'xxxxxx')
protocol = MSGraphProtocol(default_resource='reporting.triometric#xxxx.com')
scopes_graph = protocol.get_scopes_for('message_all_shared')
scopes = ['https://graph.microsoft.com/.default']
account = Account(credentials, auth_flow_type='credentials', tenant_id="**", scopes=scopes,)
if account.authenticate():
print('Authenticated')
mailbox = account.mailbox(resource='reporting.triometric#xxxx.com')
inbox = mailbox.inbox_folder()
for message in inbox.get_messages():
print(message)
I have already configured the permissions through Azure to include all the necessary 'mail' delegations.
The rest of my script works perfectly fine for uploading files to the database. Currently, the attachments must be manually saved on a shared drive multiple times per day, then the script is run to upload. Are there any steps I am missing? Any insights would be greatly appreciated!
Here are the permissions:
auth_flow_type='credentials' means you are using client credentials flow.
In this case you should add Application permissions rather than Delegated permissions.
Don't forget to click on "Grant admin consent for {your tenant}".
UPDATE:
If you set auth_flow_type to 'Authorization', it will use auth code flow which requires the delegated permission.

Parse an outlook mail from a specific sender in python in Mac OS

I am trying to fetch some details that I get in a mail for a specific fellow developer. I wanted to create a python script to trigger of some actions as & when a mail comes from him with a specific subject.
Currently I am stuck on reading the mail part.
On some google searching, I came across appscript which can help me achieving the same, I need help as to how to use this library for parsing the said email.
I am trying to do something like this:
from appscript import app, k
def make_msg(text):
outlook = app('Microsoft Outlook')
msg = outlook.make(
new=k.outgoing_message,
with_properties={
k.subject: 'Test Email',
k.plain_text_content: text})
msg.make(
new=k.recipient,
with_properties={
k.email_address: {
k.name: '<My name>',
k.address: '<My email address>'}})
msg.open()
msg.activate()
if __name__ == '__main__':
make_msg("Sample text")
I need help as to how to read from a mail sent from a specific sender with a specific subject.
Appscript documentation: http://appscript.sourceforge.net/py-appscript/doc_3x/appscript-manual/index.html
Or if any other library can be used for the same in Mac OS Outlook application, also will be helpful.

Sending email using python script from an Azure server

Using a python script, I am trying to send an email.
The mail part of the script looks like -
import smtplib
sender = 'abc.xyz#company.com'
receiver = 'abc.xyz#company.com'
message = """From: From Person <abc.xyz#company.com>
To: To Person <abc.xyz#company.com>
Subject: Inbound Folder Check - Alert
Unchanged even after an hour, please check
"""
smtpObj = smtplib.SMTP('smtp.office365.com',587)
smtpObj.starttls()
smtpObj.login('def#company.onmicrosoft.com','Password')
smtpObj.sendmail(sender, receiver, message)
The error that I am getting is -
raise SMTPDataError(code, resp) smtplib.SMTPDataError: (554, b'5.2.0
STOREDRV.Submission.Exception:SendAsDeniedE
xception.MapiExceptionSendAsDenied; Failed to process message due to a
permanent exception with message Cannot submit message. ...,
20.52176:140FCC8414001010640 10000, 20.50032:140FCC848417101069010000, 0.35180:0A006586, 255.23226:6E010000,
255.27962:0A000000, 255.27962:0E000000, 255.31418:0A00EB87, 16.55847:69000000, 1
7.43559:0000000090010000000000000D00000000000000, 20.52176:140FCC84140010100A00F 736, 20.50032:140FCC84841710100A00F836, 0.35180:8C010000, 255.23226:40000730, 25
5.27962:32000000, 255.17082:DC040000, 0.27745:9A010000, 4.21921:DC040000, 255.27 962:FA000000, 255.1494:0A00070E, 0.37692:01000100, 0.44092:01000100, 0.41232:010 00100, 0.60208:01000100, 0.37136:01000100, 0.34608:01000100, 0.55056:01000100, 0 .42768:01000100, 0.56112:05000780, 0.52807:00000000, 4.33016:DC040000, 7.40748:0 10000000000010C00000000, 7.57132:000000000000000005000780, 1.63016:32000000, 4.3 9640:DC040000, 8.45434:EC5537826FAD8844ABBA433565F1D57205000780, 5.10786:0000000 031352E32302E313232382E3032303A564931505230314D42323939303A38616433323065392D646
338612D343530642D386265322D62646464616261333932613900602005000780,
255.1750:4B01 0000, 255.31418:0A004C82, 0.22753:50010000, 255.21817:DC040000, 4.60547:DC040000 , 0.21966:B4100000, 4.30158:DC040000 [Hostname=abc]')
Only help I got on the internet was from the page - https://support.microsoft.com/en-us/help/3132755/554-5-2-0-storedrv-deliver-exception-objectnotfoundexception-mapiexcep
And it seems to say clutter is enabled but the folder is not present in the mailbox and suggests to turn off the clutter option which didn’t help.
PS - This works from my local machine within my company network but it is something to do with running it from Azure server.
First of all, please follow the offical document How to set up a multifunction device or application to send email using Office 365 to make sure whether set up correctly.
Secondly, if you were using Azure VM to send mail via SMTP, you can refer to this document Understand outbound SMTP problems in Azure VMs to try to fix your issue.
Meanwhile, for coding, there are some resources that may helps.
Python: Send Email via Office 365
Send email on App Service using Office 365 (O365) in PHP
Sending email from an Azure App Service using an O365 SMTP server in C#
Or using some packages directly like python-o365: GitHub and PyPI.
Finally, there is a service named SendGrid which be used for email service. You can use it to send mail in your scenario on Azure, please refer to the offical tutorial to know How to Send Email Using SendGrid with Azure (C#). For Python, you can code via its REST API or sendgrid python library.

Sending email from an web2py on GAE

I am trying to send a mail from my web2py app hosted on GoogleAppEngine. But it is not working. I used the mail function that was given with the web2py. Does anybody how to do this?
I read in the GAE Documentation that python mail library would not work with GAE and GAE mail library has to be used. Does it also applies to web2py mail?
Thanks
The web2py gluon.tools.Mail class (that is used by the Auth module too) works on GAE and non-GAE out of the box. You just need to pass the correct settings:
mail=Mail()
mail.settings.server="smtp.example.com:25" or "gae"
mail.settings.sender="you#example.com"
mail.settings.tls=True or False
mail.settings.login="you:password"
It supports multiple encodings, MIME and attachments.
The web2py gluon.tools.Mail class works on GAE.
See code snippet gluon.tools
line 310
try:
if self.settings.server == 'gae':
from google.appengine.api import mail
result = mail.send_mail(sender=self.settings.sender, to=to,
subject=subject, body=text)
This is the correct settings to work on GAE
mail=Mail()
mail.settings.server="gae"
mail.settings.sender="you#example.com" #This must be the email address of a registered
#administrator for the application, or the address
#of the current signed-in user.
mail.settings.login="you:password"
See
http://code.google.com/intl/en/appengine/docs/python/mail/emailmessagefields.html
sender
The email address of the sender, the From address. This must be the email address of a registered administrator for the application, or the address of the current signed-in user. Administrators can be added to an application using the Administration Console. The current user's email address can be determined with the Users API.
Sorry! My english is very poor. I hope to help.
Celso Godinho (celso.gcosta#gmail.com)
Brazil World Cup champion soccer 2010
You should use the native App Engine mailer:
http://code.google.com/appengine/docs/python/mail/sendingmail.html

Categories

Resources