Tuesday 12 April 2016

Checking email Remotely thru python ( Complete Solution )

This is done in three scripts one in bash rest other 2 in python:

Bash script for cron job and calling the entire procedure: (where the credits.txt is user1 pass1 sequence, all arranged like this)

user1 pass1
user2 pass2
.......

Bash Script:

#!/bin/bash

> /home/admin/mailstatus.txt

count=0

while IFS=' ' read -r f1 f2
do
a=($f1 $f2)
for ((i=0; i<${#a[@]}; i+=2)); do
 ./working1.py ${a[i]} ${a[i+1]}
done
let count=$count+1
done < /home/admin/credits.txt

minimumsize=$count

actualsize=$(wc -c < /home/admin/mailstatus.txt)
if [ $actualsize -gt $minimumsize ]; then
 value=$(cat /home/admin/credits.txt | awk 'NR==3{print $2}')
 ./sendnew.py $value
else
echo "This script ran correctly at -- > $(date)" >> /home/admin/logfile
fi

Check the box:

#!/usr/bin/python

import sys
import poplib, re 

if len(sys.argv) < 3:
    sys.exit(-1)

class Logger(object):
    def __init__(self):
        self.terminal = sys.stdout
        self.log = open("/home/admin/mailstatus.txt", "a")
    def write(self, message):
        self.log.write(message)  

sys.stdout = Logger()

# Change this to your needs 
POPHOST = "pop.gmail.com" 
POPUSER = sys.argv[1] 
POPPASS = sys.argv[2]

# How many lines of message body to retrieve
MAXLINES = 10

# Headers we're actually interrested in
rx_headers  = re.compile(r"^(From|Subject)")

try:

    # Connect to the POPer and identify user
    pop = poplib.POP3_SSL(POPHOST)
    pop.user(POPUSER)

    # Authenticate user
    pop.pass_(POPPASS)

    # Get some general informations (msg_count, box_size)
    stat = pop.stat()

    output = stat[0]
    check = stat[1]/1000000

    if output > 0 and check >15:

    #print "" * 30
    print "" * 30
    print "-" * 30

    # Print some useless information
    print "Checked %s for oversized emails" % (POPUSER)
    print "-" * 30
    print ("There are total: %d message(s), which is consuming %d MB's" % (stat[0], check))    
    print "-" * 30

for n in range(stat[0]):

  msgnum = n+1

        # Retrieve headers
        response, lines, bytes = pop.top(msgnum, MAXLINES)

        # Print message info and headers we're interrested in
        print " || ".join(filter(rx_headers.match, lines))
        print "-" * 30

    # Commit operations and disconnect from server
    pop.quit()
    print "" * 30

Getting the report:

#!/usr/bin/python

import smtplib, os, sys
from email.MIMEMultipart import MIMEMultipart
from email.MIMEText import MIMEText

if len(sys.argv) < 2:
    sys.exit(-1)

fromaddr = 'admin@nasheikh.com'
toaddrs  = ['naveed@nasheikh.com', 'tamy@nasheikh.com']

# Credentials (if needed)
username = 'admin@nasheikh.com'
password = sys.argv[1]

raport_file = open('/home/admin/mailstatus.txt','rb')
alert_msg = raport_file.read()
raport_file.close()

msg = MIMEMultipart()
msg['From'] = fromaddr
msg['To'] = ", ".join(toaddrs)
msg['Subject'] = "Boxes Mail Status"

body = alert_msg
msg.attach(MIMEText(body, 'plain'))

text = msg.as_string()

# The actual mail send
server = smtplib.SMTP_SSL('smtp.gmail.com:465')
server.login(username,password)
server.sendmail(fromaddr, toaddrs, text)


server.quit()

This marks the end of tutorial !