Skip to content

Commit

Permalink
add README and fix flake8 warnings
Browse files Browse the repository at this point in the history
  • Loading branch information
gshirazi committed Nov 12, 2019
1 parent f51c0aa commit 51e5b01
Show file tree
Hide file tree
Showing 3 changed files with 87 additions and 26 deletions.
63 changes: 54 additions & 9 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,16 +1,16 @@
# Python Outlook (Microsoft email service) Library
Python Library to read email from live, hotmail, outlook or any microsoft email service, just dowload to yout python script folder. This library using Imaplib python to read email with IMAP protocol.
## Prerequisite Library
Please make sure you have this library installed on your system first before your running this code
## Prerequisite Libraries
Please make sure you have these libraries installed on your system first before running this code:
* email
* imaplib
* smtplib
* datetime

then rename config.py.sample to config.py and edit comment in config.py file

## Example
### To get latest Unread Message in inbox :
## Examples
### To get latest Unread Message in inbox:
```py
import outlook
mail = outlook.Outlook()
Expand All @@ -19,7 +19,7 @@ mail.inbox()
print mail.unread()
```

### To get latest Unread Message in Junk :
### To get latest Unread Message in Junk:
```py
import outlook
mail = outlook.Outlook()
Expand All @@ -28,29 +28,31 @@ mail.junk()
print mail.unread()
```

### Retrive email element :
Use `mail.select(folder)` to switch to folders other than `inbox, `junk`.
### Retrive email element:
```py
print mail.mailbody()
print mail.mailsubject()
print mail.mailfrom()
print mail.mailto()
```

### To send Message :
### To send Message:
```py
import outlook
mail = outlook.Outlook()
mail.login('emailaccount@live.com','yourpassword')
mail.sendEmail('recipient@email.com','subject','message body')
```

### To check Credentials :
### To check Credentials:
```py
import outlook
mail = outlook.Outlook()
mail.checkLogin()
```
### Reading e-mails from Outlook with Python through MAPI and get email with word 'skype id'

### Reading e-mails from Outlook with Python through MAPI and get email with word 'skype id':
```py
import Skype4Py
import outlook
Expand Down Expand Up @@ -111,3 +113,46 @@ while True:
checkingFolder('Junk')

```

### Forward zoom recording email to recipients a mailing list:
Use `fwd_zoom.py`. The class `OutlookMailForwarder` defined there has the capability to filter messages based on the
received time (a time window from now -- in hours), and to do string search in email subject and body. Additionaly,
a filter can be defined to change the body before sending the email. For example, in `fwd_zoom.py`:

```py
def filter_zoom_mailbody(mailbody):
''' Returns the link to share. This filters out other info in the email such as the host-only link'''
m = re.search(r'Share recording with viewers:<br>\s*(.*)\b', mailbody)
return m.group(1)
```

To run, you can either define your `email[space]password` in `.cred` or giveemail/password in stdin upon prompt.
NOTE: Do not forget to `chmod 400 ./.cred` if the former method is used.

Example 1: With existing `.cred` with contents `test@example.com mypassword` and a small time window:
```
./fwd_zoom.py
How many hours to llok back?1
(' > Signed in as test@example.com', ['LOGIN completed.'])
looking up pattern in 3/3 most recent emails in folder zoom
1 items match subject_pattern
1 items match subject_pattern and body_pattern
skipping email_id 213 because its timedelta 6:31:25.556269 is greater than 1 hours
```

Example 2: without a `.cred` file and a large-enough time window:
```
./fwd_zoom.py
Outlook email:test@example.com
Outlook Password:
How many hours to look back?10
(' > Signed in as test@example.com', ['LOGIN completed.'])
looking up pattern in 3/3 most recent emails in folder zoom
1 items match subject_pattern
1 items match subject_pattern and body_pattern
email_id 213 is within range (6:45:22.572372 < 10:00:00)
maillsubject to send: Cloud Recording - Zoom Meeting is now available Tue, 12 Nov 2019 16:51:48 +0000
mailbody to send: https://test.zoom.us/recording/share/4abdcsefkHergre45grdgDdafdefMWd
Sending email...
email sent.
```
36 changes: 24 additions & 12 deletions fwd_zoom.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,8 +6,9 @@
import datetime
from pytz import timezone


class OutlookMailForwarder:
def __init__(self, email_addr, email_passwd, window_hours=24, folder_list=None, \
def __init__(self, email_addr, email_passwd, window_hours=24, folder_list=None,
mailing_list=None, subject_pattern='', body_pattern='', filter_body=None):
self.mail = outlook.Outlook()
self.mail.login(email_addr, email_passwd)
Expand Down Expand Up @@ -43,10 +44,12 @@ def prepare_email(self, email_id):
maildatetime.replace(tzinfo=timezone('UTC'))
timedelta = datetime.datetime.utcnow() - maildatetime
if timedelta > datetime.timedelta(0, 0, 0, 0, 0, self.window_hours):
raise ValueError('skipping email_id %s because its timedelta %s is greater than %d hours' % \
raise ValueError('skipping email_id %s because its timedelta %s is greater than %d hours' %
(email_id, str(timedelta), self.window_hours))
else:
print('email_id %s is within range (%s < %s)' % (email_id, str(timedelta), str(datetime.timedelta(0, 0, 0, 0, 0, self.window_hours))))
print('email_id %s is within range (%s < %s)' % (email_id, str(timedelta),
str(datetime.timedelta(0, 0, 0, 0, 0,
self.window_hours))))
mailsubject = mailsubject + ' ' + self.mail.maildate()
mailbody = self.mail.mailbody()
if self.filter_body is not None:
Expand Down Expand Up @@ -76,30 +79,39 @@ def lookup_pattern(self):
try:
for email_id in emails_match:
try:
(mailsubject, mailbody) = self.prepare_email(email_id)
self.send_email(mailsubject, mailbody)
(mailsubject, mailbody) = self.prepare_email(email_id)
self.send_email(mailsubject, mailbody)
except ValueError as err:
print('%s' % str(err))
continue
except Exception as err:
print('error processing matched emails in folder %s: %s' % (folder, str(err)))
continue


def filter_zoom_mailbody(mailbody):
''' Returns the link to share. This filters out other info in the email such as the host-only link'''
m = re.search(r'Share recording with viewers:<br>\s*(.*)\b', mailbody)
return m.group(1)


def main(_user, _pass, win_hours):
zoom_forwarder = OutlookMailForwarder(_user, _pass, win_hours, folder_list=['zoom'], \
mailing_list=['fwd@example.com'], \
subject_pattern='cloud recording', \
body_pattern='share recording with viewers:', \
zoom_forwarder = OutlookMailForwarder(_user, _pass, win_hours, folder_list=['zoom'],
mailing_list=['test@example.com'],
subject_pattern='cloud recording',
body_pattern='share recording with viewers:',
filter_body=filter_zoom_mailbody)
zoom_forwarder.lookup_pattern()


if __name__ == '__main__':
_user = raw_input('Outlook email:')
_pass = getpass.getpass('Outlook Password:')
win_hours = int(raw_input('how many hours?'))
try:
with open('.cred', 'r') as f:
userpass = f.readline()
(_user, _pass) = userpass.split()
except IOError:
_user = raw_input('Outlook email:')
_pass = getpass.getpass('Outlook Password:')

win_hours = int(raw_input('How many hours to look back?'))
main(_user, _pass, win_hours)
14 changes: 9 additions & 5 deletions outlook.py
Original file line number Diff line number Diff line change
Expand Up @@ -58,18 +58,22 @@ def sendEmail(self, recipient, subject, message):
"content-type: text/html"
])
content = headers + "\r\n\r\n" + message
attempts = 0
while True:
try:
self.smtp = smtplib.SMTP(config.smtp_server, config.smtp_port)
self.smtp.ehlo()
self.smtp.starttls()
self.smtp.login(self.username, self.password)
self.smtp.sendmail(self.username, recipient, content)
print(" email replied")
except:
print(" Sending email...")
continue
break
print(" email sent.")
return
except Exception as err:
print(" Sending email failed: %s" % str(err))
attempts = attempts + 1
if attempts < 3:
continue
raise Exception("Send failed. Check the recipient email address")

def list(self):
# self.login()
Expand Down

0 comments on commit 51e5b01

Please sign in to comment.