Send mail(smtp) in Python

# -*- coding: utf-8 -*-
import sys
import os
from time import strftime, localtime
import getopt
import smtplib
from email.MIMEText import MIMEText
from optparse import OptionParser

__version__ = u'0.0.1'
__author__ = u'MeaCulpa '
__all__ = [u'sendmail']

CHARSET = 'utf8'

def main(argv=None):

    default_input = os.path.join(os.getcwd(), u'test', u'testmail.txt')
    RECIPIENT = ''
    
    # parse commandline options
    optparse = OptionParser(version=__version__)
                        
    optparse.add_option('-i', '--inputfile',
                        dest = "inputfile",
                        metavar = "FILE",
                        default = default_input,
                        help = "file to post content to e-mail")
                        
    optparse.add_option('-r', '--recipient',
                        dest = "recipient",
                        default = RECIPIENT,
                        help = "e-mail recipient")   

    optparse.add_option("-q", "--quiet",
                        action = "store_false", 
                        dest = "verbose", 
                        default = True,
                        help = "don't print status messages to stdout")

    opts, args = optparse.parse_args()

    if args:
        optparse.error(u'invalid arguments')

    # if no option print help()
    if len(sys.argv) == 1:
        optparse.print_help()
    else:
        doRealThings(args)    
        sendmailfromfile(opts.inputfile, opts.recipient)

def doRealThings(args):
    print "---" + strftime(u' %Y-%m-%d %H:%M:%S ', localtime()) + "---"
    
def sendmailfromfile(filename, recipient):

    smtpserver = ''
    AUTHREQUIRED = 1 # if need to use SMTP AUTH set to 1
    SENDER = ''    
    # for SMTP AUTH, set SMTP username here
    smtpuser = ''
    # for SMTP AUTH, set SMTP password here
    smtppass = ''
                                           
    # Set up a MIMEText object (it's a dictionary)
    mmsg = open(filename, 'r').read()
    msg = MIMEText(mmsg, 'plain', CHARSET)

    # Can use add_header or set headers directly ...
    msg['Subject'] = 'Automated mail: ' + strftime(u'%Y-%m-%d', localtime()) + ' GMT+8'
    # Following headers are useful to show the email correctly
    # in your recipient's email box, and to avoid being marked
    # as spam. They are NOT essential to the snemail call later
    msg['From'] = SENDER
    msg['Reply-to'] = SENDER
    msg['To'] = recipient  

    # Establish an SMTP object and connect to your mail server
    s = smtplib.SMTP(smtpserver)
#        s = smtplib.SMTP_SSL(smtpserver)
    # Send the email - real from, real to, extra headers and content ...
    if AUTHREQUIRED:
        s.login(smtpuser, smtppass)
    print "Posting: " + filename
    print "     to: " + recipient
    smtpresult = s.sendmail(SENDER,recipient, msg.as_string())
    s.close()
    if smtpresult:
      errstr = ""
      for recip in smtpresult.keys():
          errstr = """Could not delivery mail to: %s"""
      print u' Result: failed! ' + errstr
    else:
        print u' Result: success!'

if __name__ == "__main__":
    sys.exit(main())

0 comments:

Post a Comment

| More

Twitter Updates