08 February 2008

Email a directory

This is how I email a directory to myself -- I cd to the directory and type this command there. Also, I set up a Gmail filter and put unique words into this script that the filter will recognize. So the directory will be tarred, gzipped and sent to my Gmail account and will arrive in a specific label. Works with Python 2.5
#! /usr/bin/env python2.5
# -*- Python -*-

import os
import datetime
import smtplib
import tarfile
import mimetypes
from email import Encoders
from email.MIMEBase import MIMEBase
from email.MIMEMultipart import MIMEMultipart
import tempfile
import getpass, socket


me = getpass.getuser() + '@' + socket.gethostname()
if not getpass.getuser() or not  socket.gethostname():
    print "Can't set email From"
    sys.exit(1)


def main():
    dirname = os.path.basename(os.getcwd())
    try:
        preferredname = raw_input('Default: [%s]\nPreferred Name: ' %
                                  dirname)
    except (KeyboardInterrupt, EOFError):
        pass
    else:
        dirname = preferredname.strip()

    
    to = "YOUR-EMAIL-ADDRESS"
    archive_name = os.path.join(tempfile.gettempdir(),
                                "%s.tar.gz" % dirname)
    now = datetime.datetime.today()    

    print "Creating message..."
    msg = MIMEMultipart()
    msg["Subject"] = "%s %s Backup [%d-%02d-%02d]" % (
        socket.gethostname(), dirname, now.year, now.month, now.day)
    msg["From"] = me
    msg["To"] = to
    # message has body:
    # this can be used to direct this backup email to a Gmail Filter
    # YOUR GMAIL FILTER WORD
    msg.preamble = "%s %s Backup" % (socket.gethostname(), dirname)
    msg.epilogue = ""

    if os.path.exists(archive_name):
        os.remove(archive_name)

    print "Creating gzipped-tar file..."
    tar = tarfile.open(archive_name, "w:gz")
    tar.add(".")
    tar.close()


    print "Attaching MIME to message..."
    ctype, encoding = mimetypes.guess_type("%s.tar.gz" % dirname)
    maintype, subtype = ctype.split("/", 1)
    mime = MIMEBase(maintype, subtype)
    fp = open(archive_name, "rb")
    mime.set_payload(fp.read())
    fp.close()
    Encoders.encode_base64(mime)
    mime.add_header('Content-Disposition', 'attachment',
                    filename=os.path.basename(archive_name))
    msg.attach(mime)

    print "Sending message..."
    s = smtplib.SMTP()
    s.connect()
    s.sendmail(me, [to], msg.as_string())
    s.close()

    os.remove(archive_name)


if __name__ == "__main__":
    main()