How to read inbox mails from Microsoft Outlook using python macOS? - python

I want to verify whether I am receiving an email from a "sender" with a "subject" and a particular "email" template. I have seen help links with win32 module that works for windows. I want to know the way to read the mails from my Microsoft Outlook from macOS.

I had something similar using appscript library. You would need to have it installed.
pip install appscript
The sample code is something like this, you may to need to extend it for your use case.
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 ID>'}})
msg.open()
msg.activate()
if __name__ == '__main__':
make_msg("Sample text")
Let me know if you need more clarification.

Related

I can't Read Outlook Email with Python on Linux

I need to do an email automation. For this I need to read an email from Outlook and then send it after configuring some data.
The problem is that all the tutorials I've seen say to use the Outlook application installed on the computer. As I use Linux I can't do this. To read the email using Gmail, I did the following:
import datetime
from imap_tools import MailBox, AND
user = "myemail#gmail.com"
password = "anypassword"
#This password is an "App Password" that I need to configure within Gmail.
my_email = MailBox("imap.gmail.com").login(user, password)
today = datetime.date.today()
list_emails = my_email.fetch(AND(from_="", date=today, subject=""))
for email in list_emails:
print(email.text)
How can I adapt the code for Outlook?
PS: In Gmail it is possible to set an "App Password". I didn't get this in Outlook.

How to store a password in my python script but have it obscured from any users when deployed to Github?

I've been trying to work this one out for a while now but keep finding imperfect solutions - I think what I want to do is possible but maybe I'm not phrasing my Google search correctly.
I have a Python script that sends a user an email notification - in order to send said email I need to provide a password in the script to send the email. The code works perfectly but it requires that I pass the password into the script:
def send_email():
import smtplib
import ssl
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
sender_email = "my-generic-email#gmail.com"
receiver_email = "recipient#gmail.com"
password = "my_password_here"
message = MIMEMultipart("alternative")
message["Subject"] = "subject_here"
message["From"] = sender_email
message["To"] = receiver_email
# Create the plain-text and HTML version of your message
text = f"""\
Plain text body here
"""
# Create secure connection with server and send email
context = ssl.create_default_context()
with smtplib.SMTP_SSL("smtp.gmail.com", 465, context=context) as server:
server.login(sender_email, password)
server.sendmail(
sender_email, receiver_email, message.as_string()
)
I don't want to store the password as plain text for obvious reasons. I've thought of environment variables but this wouldn't work as this is going to be deployed on GitHub for other people to use (or install as an EXE) so this would break the email functionality.
I've tried looking at PyCryptodome but anything I've found so far suggests encrypting the password with a key but then storing the key in the script to decrypt the password when you use it. This seems like a bad idea to me as surely any novice (like me!) would be able to easily decrypt this because the key is stored in the script.
Is anyone able to help push me in the right direction? I'm completely out of ideas as frankly I know hardly anything about password storing/security so not even sure what I should be Googling!
If others have to use your password to be able to use your script, it's impossible. If the computer can read it, then the user will also find a way to read it.
I recommend using a E-Mail service where the user can enter their own API key or just let them enter their own GMail credentials.
Correct me if I'm wrong, but I think there's no way to use your password in this case unless you write an API and send the E-Mail from your server. But don't forget that in this case, the user might be able to use your API as a way to send spam.
TL;DR: Let the users use their own passwords.

Push notification from python to android

I'm running some scripts and looking for an easy way to ping my phone once the script has finished running.
Doing some research on the web, I've seen ways of sending messages using Slack, Push bullet, twilio, email etc.
I am looking for recommendations for an easy way to send a ping/message from python to my phone.
Easy in the sense it dose not require considerable configuring of outside accounts or pay services.
I have found a much easier way, but it doesn't works on Linux. Here is a link for more details.
First you have to install notify_run:
pip install notify_run
Then you have to register:
notify-run register
It will give you a QR code (on windows the QR code doesn't works) and a link, which will take you to a website, there press the "Subscribe on this device" (Maybe you will have to refresh the site)
Then use this code:
from notify_run import Notify
notify = Notify()
notify.send('any message you want')
U can try cmd: pip install telegram-send and just send a message to your Telegram bot.
Create your telegram bot at BotFather, take a token from there, paste it to
cmd: telegram-send --configure
Usage:
import telegram_send
telegram_send.send(messages=["Hello world"])
I found this much better than any other push notification.
For more info:
Link1
Link2
I've tried a Twilio, but it's complicated and I don't think it can send you messages for free (anymore). Telegram seems an easy solution. To extend to the answer of #Nick PV, here are the steps I, as a Telegram beginner, took:
1) Get a Telegram account (free) using your phone number
Web: https://web.telegram.org
Also download the Telegram Andriod. Of course, you want the notifications on your phone after all
2) Go into settings (web or app) and set a username
This is needed to obtain an id which your bot will use to send messages to
3) Send a message to RawDataBot to get your id
Just search for RawDataBot and send any message (hi will do). Take a note of your id.
4) Create your bot (which you'll command with HTTP requests)
Now search for BotFather and send the message /start. Help is displayed. Send the message /newbot and follow the instructions. Take a note of your token to access the HTTP API
5) Send the API request using Python
You could install and use telegram-send, but if you are like me and you prefer the generic library requests which will give you the experience to handle any HTTP API, this is how to do it:
import requests
token = "token_from_step_4"
url = f"https://api.telegram.org/bot{token}"
params = {"chat_id": "id_from_step_3", "text": "Hello World"}
r = requests.get(url + "/sendMessage", params=params)
Links:
Telegram bots: https://core.telegram.org/bots
API Docs sendMessage https://core.telegram.org/bots/api#sendmessage
In the end, the easiest way I found was using Slack. It takes one Python function (about 6 lines) and an Slack account.
More details can be found here on medium
I tried pushsafer and notify-run without success on my computer (Linux Mint 19.3 tricia)
On my computer, only Slack works properly. This post comes from this Youtube video where you will see the full process in Video.
What you need first is Slack application on your device (iOs, Android, ...) and create an Slack account (if not done)
Tuto :
Create a workspace and an application (see details in this video. Sorry, I did not put the substeps here but I put this answer as a Community wiki in order to let you finish what I started :) )
Install the python library pip3 install sandesh
pip3 install sandesh
Get your webhook => https://hooks.slack.com/services/blablabla
Use this sample to send a message to Slack :
python code:
import sandesh
sandesh.send("This is my test", webhook="<put here the https link of your webhook>")
You can find the open source sandesh python module here in gitHub
You already mentioned it in your answer but Pushbullet is pretty easy:
Create a pushbullet account on their website using a gmail (I recommend not using your main one).
Install the android app and login with the same gmail. (Despite what their instructions say, you do not need to give any permissions to the Android app. Not even notifcations.)
From the website go to settings -> Account -> Create Access Token. Copy this token to use in your python script.
From python (yes you need the "py" at the end of the name)
pip install pushbullet.py (see project on pypi)
import pushbullet
pb = pushbullet.PushBullet(YOUR_ACCESS_TOKEN)
push = pb.push_note('Some Title', 'Some message you want to send')
This will pop up a notification on your Android phone with the message you specified. Works from Windows or Linux.
Using firebase fcm
One of the easiest and reliable way is to use Firebase Cloud Messaging for sending push notifications.
You can get server key from the firebase console after creating your project.
You can get device token by generating it in your device
see: https://firebase.google.com/docs/cloud-messaging/android/client (iOS, android and web)
## Install request module by running ->
# pip3 install requests
# Replace the deviceToken key with the device Token for which you want to send push notification.
# Replace serverToken key with your serverKey from Firebase Console
# Run script by ->
# python3 fcm_python.py
import requests
import json
serverToken = 'your server key here'
deviceToken = 'device token here'
headers = {
'Content-Type': 'application/json',
'Authorization': 'key=' + serverToken,
}
body = {
'notification': {'title': 'Sending push form python script',
'body': 'New Message'
},
'to':
deviceToken,
'priority': 'high',
# 'data': dataPayLoad,
}
response = requests.post("https://fcm.googleapis.com/fcm/send",headers = headers, data=json.dumps(body))
print(response.status_code)
print(response.json())
Hope you found helpful

Add image from static files to Multipart Email in Django

I am trying to send a logo with the email and have it appear in the HTML part of the email. I am building my email like this:
mail_subject = _("Subject of email %s" %
self.get_company_display())
from_email = "test#test.com"
message = EmailMultiAlternatives(mail_subject, mail_txt, from_email,
['destination#email.com'])
message.attach_alternative(mail_html, 'text/html')
message.attach('logo.png', static('myapp/images/logo.png'))
message.send()
And in my mail template I have:
<img src="cid:logo.png">
I receive the email but the image doesn't appear in the email. In fact, the email does not appear to have the image as an attachment.
Working on Python 3.4, Django 1.8.4 and sending the mails through Postfix installed on the same machine Django is running.
The EmailMessage.attach method expects to be passed the content of the file not its path, what you are actually doing is attaching the string returned by static('myapp/images/logo.png') to the message.
Use EmailMessage.attach_file instead (EmailMessage reference).
The whole purpose of yagmail (I'm the developer) is to make it really easy to send emails, especially with HTML or attachment needs.
Please try the following code:
import yagmail
yag = yagmail.SMTP(from_add, password) # add host="" and port=
contents = ['See my attachment below', '/home/static/images/logo.png']
yag.send(contents = contents)
Notice the magic here: contents is a list, where an item equal to a file path will automatically be loaded, mimetype guessed, and attached.
There's a lot more magic involved, such as easy to embed images, passwordless scripts, usernameless scripts, easy aliases, smart defaults (notice I omitted the to and subject arguments?) and much more. I advise/encourage you to read its github page :-). Feel free to raise issues or add feature requests!
You can get yagmail by using pip to install it:
pip install yagmail # Python 2
pip3 install yagmail # Python 3

Outlook / Python : Open specific message at screen

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 ?

Categories