#!/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:邮件发送者邮箱和密码,第一行账号(如example@example.com),第二行密码(必须项,不能为空)
receiver.list:邮件接收者列表,每行一个收件人(如example@example.com)
receivercc.list:邮件抄送者列表,每行一个收件人(如example@example.com)

调用方法举例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文件里的收件人列表。  

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

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

    实例一:利用SMTP与EMAIL实现邮件发送,带附件(完整代码) __author__ = 'Administrator'#coding=gb2312 from email.Header import ...

  2. CentOS/Linux内存占用大,用Shell脚本自动定时清除/释放内存

    CentOS/Linux内存占用大,用Shell脚本自动定时清除/释放内存来自:互联网 时间:2020-03-22 阅读:114以下情况可能造成Linux内存占用过高服务配置存在直接分配错误,或隐性分 ...

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

    一.背景 在我之前的博客 git学习--> Gitlab如何进行备份恢复与迁移? (地址:http://blog.csdn.net/ouyang_peng/article/details/770 ...

  4. ROS 5.x自动定时备份并发送到邮箱(实用)

    博主使用ROS已经有很长一段时间了,但经常会忘记备份配置与数据库,加上ROS本身自带的User-Man数据库并不是非常稳定,1年中总会出现1-2次数据丢失的情况.所以费了一定功夫才找到真正可用自动备份 ...

  5. 如何手动写一个Python脚本自动爬取Bilibili小视频

    如何手动写一个Python脚本自动爬取Bilibili小视频 国庆结束之余,某个不务正业的码农不好好干活,在B站瞎逛着,毕竟国庆嘛,还让不让人休息了诶-- 我身边的很多小伙伴们在朋友圈里面晒着出去游玩 ...

  6. centos 7 keepalived故障邮件通知实战(附Python邮件发送脚本)

    centos 7 keepalived故障邮件通知实战(附Python邮件发送脚本) #####################     sendmail.py  begin     ######## ...

  7. python 邮件发送 脚本

    import smtplib from email.header import Header from email.mime.text import MIMEText from_addr = 'XXX ...

  8. 用Node+wechaty写一个爬虫脚本每天定时给女(男)朋友发微信暖心话

    wechatBot 微信每日说,每日自动发送微信消息给你心爱的人 项目介绍 灵感来源 在掘金看到了一篇<用Node + EJS写一个爬虫脚本每天定时女朋友发一封暖心邮件>后, 在评论区偶然 ...

  9. python SMTP邮件发送(转载)

    Python SMTP发送邮件 SMTP(Simple Mail Transfer Protocol)即简单邮件传输协议,它是一组用于由源地址到目的地址传送邮件的规则,由它来控制信件的中转方式. py ...

随机推荐

  1. C# - 多线程 之 信号系统

    基础概览 多线程之信号系统命名空间 using System.Threading; 线程同步类的继承层次关系图 终止状态和非终止状态 在终止状态下,被WaitOne()阻塞的线程会逐个得到释放.如果一 ...

  2. C#开发微信门户及应用(2)--微信消息的处理和应答

    微信应用如火如荼,很多公司都希望搭上信息快车,这个是一个商机,也是一个技术的方向,因此,有空研究下.学习下微信的相关开发,也就成为计划的安排事情之一了.本系列文章希望从一个循序渐进的角度上,全面介绍微 ...

  3. c语言实现输入一组数自动从大到小排列

    #include <stdio.h>main(){    int x;    printf("请输入要排序数字个数:");    scanf("%d" ...

  4. 一分钟搞定AlloyTouch图片轮播组件

    轮播图也涉及到触摸和触摸反馈,同时,AlloyTouch可以把惯性运动打开或者关闭,并且设置min和max为运动区域,超出会自动回弹. 除了一般的竖向滚动,AlloyTouch也可以支持横向滚动,甚至 ...

  5. Oracle Sales Cloud:报告和分析(BIEE)小细节2——利用变量和过滤器传参(例如,根据提示展示不同部门的数据)

    在上一篇随笔中,我们建立了部门和子部门的双提示,并将部门和子部门做了关联.那么,本篇随笔我们重点介绍利用建好的双提示进行传参. 在操作之前,我们来看一个报告和分析的具体需求: [1] 两个有关联的提示 ...

  6. 【代码笔记】iOS-UILable电子表显示

    一,效果图. 二,代码. RootViewController.h #import <UIKit/UIKit.h> @interface RootViewController : UIVi ...

  7. (九)Maven坐标详解

    Maven的一个核心的作用就是管理项目的依赖,引入我们所需的各种jar包等.为了能自动化的解析任何一个Java构件,Maven必须将这些Jar包或者其他资源进行唯一标识,这是管理项目的依赖的基础,也就 ...

  8. Learning the standard of C++11

    It's a very useful website of en.cppreference.com. It lists a huge number of information about the l ...

  9. 转载: 黄聪:C#中 Excel列字母与数字的转换

    using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.T ...

  10. favicon.ico 404

    favicon.ico是一个图标文件.就是浏览网站时显示在地址栏的那个图标. 类似是百度的 显示在网站地址最前面的一张图片 可以在网站根目录(TOMCAT_HOME/webapps/ROOT/favi ...