一个python的邮件发送脚本,自动,定时,可以附件发送,抄送,附有说明文件

‘‘‘
设要排序的数组A[0]....A[N-1],首先任意选取一个数据(通常选用数组的第一个数)作为关键数据,然后
将所有比它小的数都放到前面,所有比它大的数都放到它后面,这个过程称为一趟快速排序,值得注意的是,
快速排序不是一种稳定的排序算法,也就是说,多个相同的值得相对位置也许会在算法结束时产生变动。
‘‘‘

#!/bin/env python
# -*- coding: utf-8 -*-

import datetime
import smtplib
import os,sys
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from email.mime.base import MIMEBase
from optparse import OptionParser

EMAILHOME=sys.path[0]
#sender name and password
sendername=""
senderpass=""
#list of all receiver (include cc-receiver)
receiverlist=[]
receivertmplist=[]
receivercctmplist=[]

#get the username and pasword
#no try catch here
def getUserAndPass(senderfile):
    upf=open(senderfile)
    username=upf.readline()
    password=upf.readline()
    upf.close()
    return (username.strip(os.linesep),password.strip(os.linesep))

#get the receiver list
#return the list with no ‘‘
def getReceiverList(filename):
    lif=open(filename)
    li=lif.readlines()
    lif.close()
    for x in range(len(li)):
        li[x]=li[x].strip().strip(os.linesep)
    while ‘‘ in li:
        li.remove(‘‘)
    return (li)

#get content of the mail
def getContent(filename):
    contenttmp=‘‘
    if os.path.exists(filename):
        contentf=open(filename)
        contenttmp=contentf.read()
        contentf.close()
    return contenttmp

#parameters process
parser = OptionParser()

parser.add_option(‘-s‘, ‘--sender‘, dest=‘sender‘,
        help=‘file for sender of the mail‘, default=None)
parser.add_option(‘-r‘, ‘--receiver‘, dest=‘receiver‘,
        help=‘list file for receivers of the mail‘,default=None)
parser.add_option(‘-p‘, ‘--cc‘, dest=‘cc‘,
        help=‘list file for receivers of carbon copy‘, default=None)
parser.add_option(‘-t‘, ‘--title‘, dest=‘title‘,
        help=‘title of the email,string‘, default=‘Auto email‘)
parser.add_option(‘-c‘, ‘--content‘, dest=‘content‘,
        help=‘content of the mail,must be a file‘,default=None)
parser.add_option(‘-a‘, ‘--attach‘, dest=‘attach‘,
        help=‘attachment of the file‘,default=None)
parser.add_option(‘-n‘, ‘--nameattach‘, dest=‘nameattach‘,
        help=‘name for attachment of the file‘,default=None)
parser.add_option(‘-l‘, ‘--server‘, dest=‘server‘,
        help=‘log in to the server‘,default=‘smtp.163.com‘)
parser.add_option(‘-i‘, ‘--info‘, dest=‘info‘,
        help=‘information of the content,string,but not file‘,default=‘Auto email‘)
parser.add_option(‘-f‘, ‘--form‘, dest=‘form‘,
        help=‘form of the content,html or plain‘,default=‘plain‘)

(options, args) = parser.parse_args()

#get sender infor
if not options.sender:
    if os.path.exists(EMAILHOME+r‘/sender.list‘):
        (sendername,senderpass)=getUserAndPass(EMAILHOME+r‘/sender.list‘)
        if sendername.strip()=="" or senderpass.strip()=="":
            print ("no sender!")
            exit(0)
    else:
        print ("no sender!")
        exit(0)
else:
    if os.path.exists(options.sender):
        (sendername,senderpass)=getUserAndPass(EMAILHOME+r‘/sender.list‘)
        if sendername.strip()=="" or senderpass.strip()=="":
            print ("no sender!")
            exit(0)
    else:
        print ("the file for sender list does not exists!")
        exit(0)

#get list of all receiver
if not options.receiver:
    if os.path.exists(EMAILHOME+r‘/receiver.list‘) or os.path.exists(EMAILHOME+r‘/receivercc.list‘):
        if os.path.exists(EMAILHOME+r‘/receiver.list‘):
            receivertmplist= getReceiverList(EMAILHOME+r‘/receiver.list‘)
        if os.path.exists(EMAILHOME+r‘/receivercc.list‘):
            receivercctmplist= getReceiverList(EMAILHOME+r‘/receivercc.list‘)
        receiverlist=receivertmplist+receivercctmplist
        if len(receiverlist)==0:
            print ("no receiver!")
            exit(0)
    else:
        print ("no receiver list file!")
        exit(0)
else:
    if os.path.exists(options.receiver) or os.path.exists(options.cc):
        if os.path.exists(options.receiver):
            receivertmplist= getReceiverList(options.receiver)
        if os.path.exists(options.cc):
            receivercctmplist= getReceiverList(options.cc)
        receiverlist=receivertmplist+receivercctmplist
        if len(receiverlist):
            print ("no receiver from the list file!")
            exit(0)
    else:
        print ("receiver list file does not exist!")
        exit(0)

if  options.attach and not options.nameattach:
    print ("give a name to the attachment!")
    exit(0)

#make a mail
mailall=MIMEMultipart()    

#content of the mail
if options.content:
    mailcontent =getContent(options.content)
    mailall.attach(MIMEText(mailcontent,options.form,‘utf-8‘))
elif options.info:
    mailcontent = str(options.info)
    mailall.attach(MIMEText(mailcontent,options.form,‘utf-8‘))

#attachment of the mail
if options.attach:
    mailattach =getContent(options.attach)
    if mailattach !=‘‘:
        contype = ‘application/octet-stream‘
        maintype,subtype=contype.split(‘/‘,1)
        attfile=MIMEBase(maintype,subtype)
        attfile.set_payload(mailattach)
        attfile.add_header(‘Content-Disposition‘,‘attachment‘,options.nameattach)
        print ("attach file prepared!")
        mailall.attach(attfile)

#title,sender,receiver,cc-receiver,
mailall[‘Subject‘]=options.title
mailall[‘From‘]=sendername
mailall[‘To‘]=str(receivertmplist)
if len(receivercctmplist) !=0:
    mailall[‘CC‘]=str(receivercctmplist)

#get the text of mailall
fullmailtext=mailall.as_string()
print ("prepare fullmailtext ok.")
mailconnect = smtplib.SMTP(options.server)
try:
    mailconnect.login(sendername,senderpass)
except Exception as e:
    print ("error when connect the smtpserver with the given username and password !")
    print (e)
    exit(0)

print ("connect ok!")

try:
    mailconnect.sendmail(sendername, receiverlist, fullmailtext)
except Exception as e:
    print ("error while sending the email!")
finally:
    mailconnect.quit()

print (‘email to ‘+str(receiverlist)+‘ over.‘)

print (‘***‘*80)

说明:

#mail.py使用方法:

1,本脚本同目录下文件介绍:
sender.list:邮件发送者邮箱和密码,第一行账号(如[email protected]),第二行密码(必须项,不能为空)
receiver.list:邮件接收者列表,每行一个收件人(如[email protected])
receivercc.list:邮件抄送者列表,每行一个收件人(如[email protected])

调用方法举例1:
把发件人和收件人信息(sender.list和receiver.list)填好后,在mail.py所在目录执行
python mail.py  -s sender.list -r receiver.list

2,其它帮助信息获得方法:
在mail.py所在目录执行:python mail.py -h
显示:
Options:
  -h, --help            show this help message and exit
  -s SENDER, --sender=SENDER                                     //配置本脚本发件人信息存放的文件的路径  如 /tmp/tmp/list.list
                        file for sender of the mail
  -r RECEIVER, --receiver=RECEIVER                               //配置本脚本收件人列表存放的文件的路径  如 /tmp/tmp/list.list
                        list file for receivers of the mail
  -p CC, --cc=CC        list file for receivers of carbon copy   //配置抄送收件人列表存放的文件的路径  如 /tmp/tmp/list.list
  -t TITLE, --title=TITLE                                        //配置邮件的标题,字符串(不能有空格)
                        title of the email,string
  -c CONTENT, --content=CONTENT                                  //配置邮件的内容,文件路径(和-i冲突时,-i参数无效)
                        content of the mail,must be a file
  -a ATTACH, --attach=ATTACH                                     //配置邮件的附件,文件路径(有附件时,必须配置-n参数)
                        attachment of the file
  -n NAMEATTACH, --nameattach=NAMEATTACH                         //配置邮件的附件名称,字符串(不能有空格)(有附件时,必须配置本参数)
                        name for attachment of the file
  -l SERVER, --server=SERVER                                     //配置邮件的服务器,默认是smtp.163.com
                        log in to the server
  -i INFO, --info=INFO  information of the content,string,but not file //配置邮件的内容,字符串(不能有空格)(和-c冲突时,本参数无效)
  -f FORM, --form=FORM  form of the content,html or plain        //配置邮件的内容的类型,默认是plain
  
调用方法举例2:
在mail.py所在目录执行:
python mail.py  -s /root/tmp/sender.list -r /root/tmp/receiver.list -p /root/tmp/receivercc.list  -t test_the_py -c /root/tmp/content.log -a /root/tmp/attch.log -n attachname1.log

将会把/root/tmp/content.log作为文件内容,
把/root/tmp/attch.log作为附件,
把attachname1.log作为附件名称,
把test_the_py作为邮件标题的邮件;
从/root/tmp/sender.list文件里的发件人,
发送到/root/tmp/receiver.list和/root/tmp/receivercc.list文件里的收件人列表。  

时间: 2024-08-05 11:18:51

一个python的邮件发送脚本,自动,定时,可以附件发送,抄送,附有说明文件的相关文章

python实现邮件发送完整代码(带附件发送方式)

实例一:利用SMTP与EMAIL实现邮件发送,带附件(完整代码) __author__ = 'Administrator'#coding=gb2312 from email.Header import Headerfrom email.MIMEText import MIMETextfrom email.MIMEMultipart import MIMEMultipartimport smtplib, datetime def SendMailAttach(): msg = MIMEMultip

Git学习-->如何通过Shell脚本自动定时将Gitlab备份文件复制到远程服务器?

一.背景 在我之前的博客 git学习--> Gitlab如何进行备份恢复与迁移? (地址:http://blog.csdn.net/ouyang_peng/article/details/77070977) 里面已经写清楚了如何使用Gitlab自动备份功能.  但是之前的备份功能只是备份到Gitlab服务运行的那台服务器上,如果哪一天那台服务器的磁盘损坏了的话,数据无法取出,那么对于公司来说是一匹无法想象的损失,因为 代码是公司的重要资产,需要以防万一. 代码是公司的重要资产,需要以防万一. 代

嵌入式linux下自动定时检测硬盘空间并删除旧文件脚本

#! /bin/sh while true; do i=`df -h | egrep '/mnt/yourpath'| awk '{print $5}' | cut -d "%" -f1 -` if [ "$i" -ge 90 ] then echo "disk nearly full" cd /mnt/yourpath for file1day in `ls -d */ | sort -n | cut -d "/" -f1

python 发邮件的脚本

不加参数,可以 输出帮助 ,及使用方法. 秘送的也是成功的.在收件与抄送 不会显示. # coding: utf-8 import sys import os import smtplib from email.mime.multipart import MIMEMultipart from email.mime.text import MIMEText from email.mime.base import MIMEBase from email import encoders from sm

如何把一个Python脚本加入Windows右键菜单

例如我有一个Python程序,叫getPath.py,用来获得我选中的文件的全路径名称. getPath.py import sys if __name__ == '__main__': if len(sys.argv)!= 2: sys.exit('argv error!') ##sys.argv[1]就是输入的带路径文件名. ##后面是对sys.argv[1]的处理 怎么把这个脚本加入Windows的右键菜单呢? 先写一个批处理: myPath.bat c:\Python34\python.

线上一个简单检测Ping状态的邮件报警脚本

Step1.安装sendmail来发邮件 # yum -y install sendmail # /etc/init.d/sendmail start # chkconfig sendmail on Step2.安装邮件客户端 # yum -y install mutt 2.1添加发件人信息,如下 # vim /etc/Muttrc set charset="utf-8"           #设置发邮件编码 set envelope_from=yes set rfc2047_para

禅道及其数据库自动备份及短信、邮件通知脚本

一.添加SMTP服务器 在需要发送自动报警的服务器上修改如下文件,增加如下两行 # vim /etc/mail.rc set [email protected] smtp=smtp.126.com set smtp-auth-user=doteyplay smtp-auth-password=*** smtp-auth=login     当然,这里的SMTP服务器也可以使用别的,比如QQ的,但是QQ只能发几卦,在测试的时候,总报错:smtp-server: 454 Error: authent

备份脚本及定时自动执行

1.首先自己建一个目录,我建的目录路径为/root/bak/bakmysql 建立目录步骤: cd /root(切换路径到root目录下)→mkdir bak(新建名称为bak的文件夹)→cd bak(进入bak目录下)→mkdir bakmysql(新建名为bakmysql的文件夹) 2.写备份脚本 #!/bin/bash ## 定义变量back_dir=/root/bak/bakmysqldate=$(date +%Y%m%d%H%M) ## 进入备份目录cd $back_direcho "

Python脚本用于定时关闭网易云音乐PC客户端

本文主要讲述如何使用Python在指定的秒数后关闭Windows上运行的程序(此程序以网易云音乐为例).本文的背景是昨晚发现网易云音乐的PC客户端没有定时关闭的功能,可以使用Python编写一个简单的脚本,用于定时关闭这样的计划任务.经过改良后,可以对此做一些有用的扩展,用于日常运维中. 为什么使用Python来做这件事? 用cmd.计划任务或者批处理做这件事不可以吗?如果说忽略过程,只看结果的话,这些方式确实可能更简单也能达到目的,但是通过Python来做可以从过程和结果两个方面获得很多好处: