Yazılarım‎ > ‎

pyhton gmail tar.gz mail monster

5 Şub 2012 18:13 tarihinde Ugur ARPACI tarafından yayınlandı   [ 5 Şub 2012 18:15 güncellendi ]

    I have designed gmail tar.gz mail monster script in order to automatize sending relatively massive amount of file transfer over gmail. This script is born in the need of my photograph sessions, which produces hundreds of .jpeg files that need to be transferred to some mail accounts. From now on, I simply compress image files with tar.gz and put all of them in a directory. Inside that newly created directory, I run the following script.

  •     create a directory that includes tar.gz files that will be transferred
  •     put the python file inside that directory
  •     create a file named 'account.conf', and populate it with your sender account username and password in separate lines as follows:
   
     username
     password

    
  •     run the script, all tar.gz files inside that directory will be posted to the mail address that you provide in the beginning of the execution.



#!/usr/bin/env python
# -*- coding: utf-8 -*-
from datetime import datetime
import smtplib
import random
import string
from email.MIMEText import MIMEText
from email.Header import Header
from email.Utils import parseaddr, formataddr
from email.MIMEMultipart import MIMEMultipart
from email.MIMEBase import MIMEBase
from email.Utils import COMMASPACE, formatdate
from email import Encoders
import sys,os
import re
import gzip
import shlex

#assume gmail file limit is 20 MB
GMAIL_FILE_LIMIT = 20000000L 

session = None
msg = None

def send_files(recipient='',files=[]):
    global session
    global msg
    print "Logging in gmail..."
    session = smtplib.SMTP('smtp.gmail.com',587)
    session.ehlo()
    session.starttls()
    session.ehlo()
    session.login(username,password)
    print "Logged in to the gmail_smtp."
    sendList = []
    mailTempBuffer = 0L
    msg = None
    msg = initializeMsg(msg)
    for filename in files:  
        if not isFileValid(filename):
            print str(filename) + " seems MORE than 20 mb , FAIL TO SEND, over capacity, file skipped..."
            continue
        if GMAIL_FILE_LIMIT > mailTempBuffer+os.path.getsize(filename):
            mailTempBuffer = mailTempBuffer + os.path.getsize(filename)
            sendList.append(filename)
            continue
        else:
            send_mail(sendList)
            mailTempBuffer = 0L
            sendList = []
            msg = None
            msg = initializeMsg(msg)
            mailTempBuffer = mailTempBuffer + os.path.getsize(filename)
            sendList.append(filename)
    if sendList:
        send_mail(sendList)
    session.quit()
    print "Logged out from gmail"

def send_mail(sendList):
    global session
    global msg
    informationMessage = "Following files are in process...\n"
    for mailItem in sendList:
        informationMessage = informationMessage + "[" + str(mailItem) + "]" + "\n"
    print informationMessage 
    for mailItem in sendList:
        appendAttachment(mailItem)
    print "mail is sending..."
    session.sendmail(username,[recipient],msg.as_string())
    
def initializeMsg(msg):
    msg = MIMEMultipart()
    msg['From'] = username
    msg['To'] = recipient
    msg['Subject'] = message
    msg['Date'] = formatdate(localtime=True)
    msg.attach(MIMEText(message))
    return msg
    
def appendAttachment(mailItem):
    global session
    global msg
    filePtr = open(mailItem,"rb")
    part = MIMEBase('application', "octet-stream")
    part.set_payload( filePtr.read() )
    Encoders.encode_base64(part)
    part.add_header('Content-Disposition', 'attachment; filename="%s"' % mailItem)
    print "[" + mailItem + "]" +  " is attaching..."
    msg.attach(part)
    filePtr.close()
    print "[" + mailItem + "]" +  " is attached."

def getFiles():
    allFiles = os.listdir(".")
    allTarFiles = []
    for tars in allFiles:
        if 'tar.gz' in tars:
            allTarFiles.append(tars)
    return allTarFiles

def isFileValid(filename):
    if os.path.getsize(filename) < GMAIL_FILE_LIMIT:
        return True
    return False

f=open("account.conf","r")
username = f.readline()
password = f.readline()
f.close()
username = username.rstrip('\n')
password = password.rstrip('\n')

if len(sys.argv) < 2:
    print "USAGE: python send-files-over-mail.py <destination@gmail.com> <message>"
    sys.exit(1)

files = getFiles()
message = sys.argv[len(sys.argv)-1]
recipient = sys.argv[1] 

send_files(recipient,files)



Č
ċ
ď
send-files-over-mail.py
(3k)
Ugur ARPACI,
5 Şub 2012 18:13