zhasm
10/29/2011 - 3:17 AM

attachment mailer, send attachment via localhost/gmail

attachment mailer, send attachment via localhost/gmail

#!/usr/bin/env python

"""attachment mailer, send attachment via localhost/gmail"""

import os
import re
import sys
import smtplib
# For guessing MIME type based on file name extension
import mimetypes
from hashlib import md5
from optparse import OptionParser

from email import encoders
from email.message import Message
from email.mime.audio import MIMEAudio
from email.mime.base import MIMEBase
from email.mime.image import MIMEImage
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from email import Utils

COMMASPACE = ', '
gmail_user = 'rex@zhasm.com'
gmail_passwd = ''
default_sender ="rex@zhasm.com"
default_recepient="rex@zhasm.com"


def pre(f,t,s,a):
    print "From: %s" %f
    print "To: %s" %t
    print "Subject: %s" %s
    print "Attachment: %s" %a
    print "sending..."


def main():
    parser = OptionParser(usage="""\
Send the contents of a directory as a MIME message.

Usage: %prog [options]

Unless the -o option is given, the email is sent by forwarding to your local
SMTP server, which then does the normal delivery process.  Your local machine
must be running an SMTP server.
""")
    parser.add_option('-a', '--archive',
                      type='string', action='store', dest='filename',
                      help="""Filename to be attached (Required)""")

    parser.add_option('-f', '--from',
                      type='string', action='store', metavar='SENDER',dest='sender',
                      default=default_sender,
                      help='email from address.')

    parser.add_option('-t', '--to',
                      type='string', action='store', metavar='RECIPIENT',
                      default=default_recepient, dest='recipients', 
                      help='To address,  you may provide a list of emailadresses seperated by [,;\s]+.')

    parser.add_option('-s', '--subject',
                      type='string', action='store', metavar='SUBJECT',
                      dest='subject',
                      help='default subject is the filename to be attached'
                      )

    opts, args = parser.parse_args()
    if not opts.filename:
        parser.print_help()
        sys.exit(1)
    filename= opts.filename
    # Create the enclosing (outer) message
    outer = MIMEMultipart()
    outer['To'] = ', '.join(re.split(r'[;,\s]+',opts.recipients))
    outer['From'] = opts.sender
    outer['Subject']="%s" % (opts.subject)
    outer['Message-ID']=Utils.make_msgid().replace("@","__.rex@")
    if filename :
        # Guess the content type based on the file's extension.  Encoding
        # will be ignored, although we should check for simple things like
        # gzip'd or compressed files.
        ctype, encoding = mimetypes.guess_type(filename)
        if ctype is None or encoding is not None:
            # No guess could be made, or the file is encoded (compressed), so
            # use a generic bag-of-bits type.
            ctype = 'application/octet-stream'
        maintype, subtype = ctype.split('/', 1)

        fp = open(filename, 'rb')
        content=fp.read()
        hash=md5()
        hash.update(content)
        #outer['Subject']="%s MD5 %s" % (filename, hash.hexdigest())
        msg = MIMEBase(maintype, subtype)
        msg.set_payload(content)
        fp.close()
            # Encode the payload using Base64
        encoders.encode_base64(msg)
        # Set the filename parameter
        msg.add_header('Content-Disposition', 'attachment', filename=filename.replace("/","_"))
        outer.attach(msg)
    # Now send or store the message
    pre(opts.sender, opts.recipients, outer['Subject'], filename)

    composed = outer.as_string()
    try:
        s = smtplib.SMTP('localhost')
        s.sendmail(opts.sender, opts.recipients, composed)
        s.quit()
    except Exception, e:
        print "Warning: ", str(e)
        print "tring gmail server instead"
        s = smtplib.SMTP('smtp.gmail.com', 587)
        s.ehlo()
        s.starttls()
        s.ehlo()
        s.login(gmail_user, gmail_passwd)
        s.sendmail(opts.sender, opts.recipients, composed)
        s.quit()
    
    print "Sent!\n"

if __name__ == '__main__':
    main()