romaklimenko
11/27/2010 - 7:26 AM

A simple script to send out image files from specific folder via email. It can be used to post a lot of images on Tumblr or Posterous.

A simple script to send out image files from specific folder via email. It can be used to post a lot of images on Tumblr or Posterous.

import os
import shutil
import smtplib
import time

from email.mime.image import MIMEImage
from email.mime.multipart import MIMEMultipart

HOST = 'smtp.gmail.com'
PORT = 587

USER = 'yourusername@gmail.com'
PASSWORD = 'yourpassword'

OUTBOX_PATH = 'outbox'
SENT_PATH = 'sent'

FROM = 'yourusername@gmail.com'
TO = 'yourtumbltaccount@tumblr.com'

SLEEP_SECONDS = 30

def sendmail(file):
    # todo: check if file is an image
    f = open(os.path.join(OUTBOX_PATH, file), 'rb')
    image = MIMEImage(f.read())
    f.close()

    multipart = MIMEMultipart()
    multipart['From'] = FROM
    multipart['To'] = TO
    multipart.attach(image)

    smtp = smtplib.SMTP(HOST, PORT)
    smtp.starttls()
    smtp.login(USER, PASSWORD)
    smtp.sendmail(FROM, TO, multipart.as_string())
    smtp.quit()

    print 'The file {0} sent from {1} to {2}'.format(file, FROM, TO)

def movetosent(file):
    shutil.move(os.path.join('outbox', file), os.path.join('sent', file))
    print 'The file {0} moved to {1}'.format(file, SENT_PATH)

for file in os.listdir(OUTBOX_PATH):
    sendmail(file)
    print 'sleep for {0} seconds...'.format(SLEEP_SECONDS)
    time.sleep(SLEEP_SECONDS)
    movetosent(file)