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

#!/bin/env python
# -*- coding: utf-8 -*-
 
 
import datetime
import smtplib
import os,sys
from email.mime.text  import MIMEText
from email.MIMEMultipart  import MIMEMultipart
from email.MIMEBase  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 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,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,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文件里的收件人列表。
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
好的,下面是一个简单的邮件定时发送脚本: ```python import smtplib from email.mime.text import MIMEText from email.mime.multipart import MIMEMultipart from email.mime.application import MIMEApplication from cryptography.fernet import Fernet from datetime import datetime, timedelta import time # 密密钥,可以使用 Fernet.generate_key() 生成 key = b'your_key_here' # 发件人和收件人信息 sender_email = 'sender@example.com' receiver_email = 'receiver@example.com' # 邮件主题和正文 subject = 'Test Email' body = 'This is a test email.' # 创建密器对象 cipher = Fernet(key) # 邮件主题和正文 encrypted_subject = cipher.encrypt(subject.encode()).decode() encrypted_body = cipher.encrypt(body.encode()).decode() # 创建邮件对象 msg = MIMEMultipart() msg['From'] = sender_email msg['To'] = receiver_email msg['Subject'] = encrypted_subject # 添密正文 msg.attach(MIMEText(encrypted_body)) # 添附件 with open('attachment.txt', 'rb') as f: attachment = MIMEApplication(f.read(), _subtype='txt') attachment.add_header('Content-Disposition', 'attachment', filename='attachment.txt') msg.attach(attachment) # 设置定时发送时间 schedule_time = datetime.now() + timedelta(minutes=10) # 进入循环,等待定时发送 while True: current_time = datetime.now() if current_time >= schedule_time: break time.sleep(60) # 发送邮件 with smtplib.SMTP('smtp.gmail.com', 587) as smtp: smtp.starttls() smtp.login(sender_email, 'your_password_here') smtp.send_message(msg) print('Email sent successfully.') ``` 说明: 1. 首先需要安装 `cryptography` 模块,可以使用 `pip install cryptography` 进行安装。 2. 在脚本中定义了密密钥 `key`,需要自己生成并填入。 3. 定义了发件人和收件人信息。 4. 定义了邮件主题和正文,然后使用密器对象 `cipher` 进行密。 5. 创建邮件对象 `msg`,并添密正文和附件。 6. 设置定时发送时间 `schedule_time`,这里设置了当前时间的 10 分钟后。 7. 进入循环,等待定时发送,每隔一分钟检查一次时间。 8. 到了定时发送时间后,使用 SMTP 协议发送邮件。 9. 打印发送成功的提示信息。 注意:这里使用了 Gmail 的 SMTP 服务器,需要先在 Gmail 中开启“允许较不安全的应用程序访问您的帐户”选项,才能使用脚本发送邮件
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值