ITPub博客

首页 > Linux操作系统 > Linux操作系统 > python 发送邮件脚本(支持多附件和群邮件)

python 发送邮件脚本(支持多附件和群邮件)

原创 Linux操作系统 作者:steven_hua 时间:2016-10-19 15:24:33 0 删除 编辑
# -*- coding: UTF-8 -*-
# Auth: sxhua
# Usage: python sendmail.py -t sxhua@tudou.com,abc@tudou.com -s "Daily Report" -c "dbreport_20161019.lst"  -a "dbreport2_20161019.lst","dbreport_20161019.lst"

import sys
import time
import getopt
import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
#from email.MIMEBase import MIMEBase
#from email import Encoders


mail_host="xxx.xxx.xxx.xxx"
mail_user="sxhua"
#mail_pass="xxxxxx"
mail_postfix="tudou.com"



def Usage():
    print 'PyTest.py usage:'
    print '-h, --help: print help message.'
    print '-v, --version: print script version'
    print '-t, --to: mail to address'
    print '-s, --subject: mail subject'
    print '-c, --content: mail content'
    print '-cf, --contentfile: file name for mail content'
    print '-a, --attach: mail attachment list and use "," as separator'


def Version():
    print 'mail.py 1.0.0.1 by sxhua'


def readFile(spath):
    
    try:
        f=open(spath,"r") # Opens file for reading
        content="Dear DBA, \n"
        for line in f:
            content=content + line

        f.close()
    except Exception, e:
        #print str(e)
        content=spath
    
    return content


def sendMail(to_list,sub,content,attach_list=[]):
    #me="hello"+"<"+mail_user+"@"+mail_postfix+">"
    me="Oracle Software Owner "
    
    # structure MIMEMultipart as root container
    msg = MIMEMultipart()

    # mail header
    msg['Subject'] = sub
    msg['From'] = me
    msg['To'] = ";".join(to_list)
    msg['date']=time.strftime('%a, %d %b %Y %H:%M:%S %z')

    # mail body
    try:
        contentFile=readFile(content)
        body=MIMEText(contentFile)
        msg.attach(body)
    except Exception, e:  
        print str(e)
        return False

    # attachment list add mail
    for x in attach_list:
        try:
            att = MIMEText(open(x, 'rb').read(), 'base64', 'UTF-8')
            att["Content-Type"] = 'application/octet-stream'
            att["Content-Disposition"] = 'attachment; filename='+x+'.txt'
            msg.attach(att)
        except IOError, e:
            print "info: No such file '"+x+"' ."
        except Exception,e:
            print e

    #
    try:
        server = smtplib.SMTP()
        server.connect(mail_host)
        #server.login(mail_user,mail_pass)
        server.sendmail(me, to_list, msg.as_string())
        server.close()
        return True
    except Exception, e:  
        print str(e)
        return False



def main(argv):
    try:
        opts, args = getopt.getopt(argv[1:], 'hvt:s:c:a:', ['to=', 'subject=', 'content=', 'attach='])
    except getopt.GetoptError, err:
        print str(err)
        Usage()
        sys.exit(2)


    mailto="sxhua@tudou.com"
    mail_subject="hello"
    mail_content="hello, this is the mail content" #mail_body
    str_mail_attachs="123.txt"

    for o, a in opts:
        if o in ('-h', '--help'):
            Usage()
            sys.exit(1)
        elif o in ('-v', '--version'):
            Version()
            sys.exit(0)
        elif o in ('-t', '--to'):
            mailto=a
        elif o in ('-s','--subject'):
            mail_subject=a
        elif o in ('-c','--content'):
            mail_content=a
        elif o in ('-cf','--contentfile'):
            mail_content=a
        elif o in ('-a','--attach'):
            str_mail_attachs=a
        else:
            print 'unhandled option'
            Usage()
            sys.exit(3)
    return mailto,mail_subject, mail_content,str_mail_attachs

if __name__ == '__main__':
    mailto,mail_subject, mail_content,str_mail_attachs = main(sys.argv)
    print mail_subject
    print mail_content
    print str_mail_attachs
    print mailto
    attach_list=str_mail_attachs.split(',')
    mailto_list=mailto.split(',')
    if sendMail(mailto_list,mail_subject,mail_content,attach_list):
        print "Send Mail Success"
    else:
        print "Send Mail Failure"
sendmail.py

来自 “ ITPUB博客 ” ,链接:https://blog.itpub.net/807718/viewspace-2126741/ ,如需转载,请注明出处,否则将追究法律责任。

请登录后发表评论 登录
全部评论

注册时间:2008-05-16

  • 博文量
    117
  • 访问量
    190322