本文共 6475 字,大约阅读时间需要 21 分钟。
最近研究邮件透明加密技术,,需要使用脚本自动发送邮件测试,于是使用python写了一个小程序。程序可以自动选择不定数量的附件,随机选择主题,随机选择正文,然后自由组合发送,非常适合邮件方面的测试任务。顺便说一下邮件透明加密技术和市场上的其他邮件加密技术相比再部署上非常简单。”透明“二字就是部署不改变用户原有习惯,目前的产品有天御云安的隐密邮,网址是https://mail.tyyunan.com/, 各位感兴趣的可以看一下。
# -*- coding: utf-8 -*-__version__ = '''Python-based smtp ClientCopyright (C) 2018 Chunyu CaoThis is free software; see LICENSE file for copying conditions. There is NOwarranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.'''# py .\smtp_client.py 10.115.5.68 25 test1@tyyunan.com 123456 recv_name BASE64 --send_num 1import timeimport randomimport jsonimport smtplibimport osimport argparseimport base64from urllib import requestfrom urllib import errorfrom email.mime.text import MIMETextfrom email.mime.application import MIMEApplicationfrom email.mime.multipart import MIMEMultipartfrom email.mime.image import MIMEImagefrom email import encodersfrom email.message import Messagefrom email.charset import Charsetfrom email.charset import QPfrom email.charset import BASE64from email.charset import SHORTESTsubject = ['s1','s2']mail_text = ['c1','c2','c3','c4','c5','c6','c7','c8','c9','c10','c11']#mail_text = ['c5']files_list = ['1.jpg','2.jpg','3.jpg','1M-good.txt','4.pdf','5.pdf','6.rar','7.docx','8.docx','9.7z','10.xlsx']#files_list = ['11.txt','12.txt','13.txt','14.txt','15.txt','20180911.txt']#files_list = ['1.jpg','1M-good.txt','5.pdf','6.rar','7.docx','8.docx','9.7z','10.xlsx']#files_list = []def save_file(file_name,data):try:with open(file_name, 'w') as fp:fp.write(data)except Exception as e:print('save file error:[{0}]'.format(e))raiseclass SmtpClient:def __init__(self,args,file_path,subject_file_name,text_file_name):self.args = argssmtplib.Debug = args.debugself.recv_name =[]data = []self.text_file_name = text_file_namewith open(file_path+os.path.sep+args.recv_name_file, 'rb') as fp:data = fp.read().decode('utf-8').split(',')for i in data:self.recv_name.append(i.strip())#self.recv_name = random.sample(self.recv_name,random.randint(0, len(self.recv_name)))#print('[{len}]:{name}\n'.format(len = len(self.recv_name),name = self.recv_name))with open(file_path+os.path.sep+'mail_subject'+os.path.sep+subject_file_name, 'rb') as fp:self.mail_subject = fp.read()with open(file_path+os.path.sep+'mail_text'+os.path.sep+text_file_name, 'rb') as fp:self.mail_text = fp.read()def construct_text_mail_text(self,encode_type):charset = Charset('utf-8')charset.header_encoding = SHORTESTcharset.body_encoding = encode_typeself.msg.add_header('Content-Type', 'text/plain',name = self.text_file_name)self.msg.set_charset(charset)self.msg.set_payload(self.msg._charset.body_encode(self.mail_text))def construct_attachment_mail_text(self,encode_type):text_msg = Message()charset = Charset('utf-8')charset.header_encoding = SHORTESTcharset.body_encoding = encode_typetext_msg.add_header('Content-Type', 'text/plain',name = self.text_file_name)text_msg.set_charset(charset)text_msg.set_payload(text_msg._charset.body_encode(self.mail_text))self.msg.attach(text_msg)def construct_attachment_msg(self,file_path,file_name):with open(file_path+os.path.sep+'mail_attach'+os.path.sep+file_name, 'rb') as fp:data = fp.read()attachment_msg = MIMEApplication(data)attachment_msg.add_header('Content-Disposition','attachment',filename = file_name)self.msg.attach(attachment_msg)def construct_text_mail_header(self):self.msg = Message()self.msg['From'] = self.args.user_nameself.msg['To'] = ";".join(self.recv_name)#self.msg['To'] = r"'xxx' " + ";".join(self.recv_name)#self.msg['X-MS-TNEF-Correlator'] = "00000000F3B7D51C2A9243419D3CDE795E89C788C4FD2100"self.msg['Subject'] = self.mail_subject.decode('utf-8')def construct_attach_mail_header(self):self.msg = MIMEMultipart('related')self.msg['From'] = self.args.user_nameself.msg['To'] = ";".join(self.recv_name)self.msg['Subject'] = self.mail_subject.decode('utf-8')def send_mail(self):try:self.smtp.sendmail(self.args.user_name,self.recv_name,self.msg.as_string())#self.smtp.sendmail(self.args.user_name,"caochunyu@tyyunan.com",self.msg.as_string())#print(self.msg.as_string())save_file(os.getcwd()+os.path.sep+'tmp_file'+os.path.sep+'tmp.eml',self.msg.as_string())print('mail send Success!')except Exception as e:print('mail send fail! Error!')raisedef login(self):try:if self.args.ssl:self.smtp = smtplib.SMTP_SSL()else:self.smtp = smtplib.SMTP()self.smtp.connect(self.args.host,self.args.port)self.smtp.login(self.args.user_name,self.args.user_pass)except Exception as e:print('login fail! Error:'+str(e))raisedef logout(self):try:self.smtp.close()except Exception as e:print('logout fail! Error:'+str(e))raisedef main(args):print(args)file_dir = os.getcwd()send_num = args.send_numif args.encode_type == 'QP':encode_type = QPelif args.encode_type == 'BASE64':encode_type = BASE64else:encode_type = -1while send_num > 0:random_files_list = random.sample(files_list,random.randint(0, len(files_list)))print('attachment num is [{0}]'.format(len(random_files_list)))random_subject = subject[random.randint(0, len(subject)-1)]random_text = mail_text[random.randint(0, len(mail_text)-1)]mail_client = SmtpClient(args,file_dir,random_subject,random_text)if len(random_files_list) == 0:mail_client.construct_text_mail_header()mail_client.construct_text_mail_text(encode_type)else:mail_client.construct_attach_mail_header()mail_client.construct_attachment_mail_text(encode_type)for mail_attachment in random_files_list:mail_client.construct_attachment_msg(file_dir,mail_attachment)mail_client.login()mail_client.send_mail()mail_client.logout()send_num -= 1print('remain mail num is [{0}]'.format(send_num))time.sleep(1)if __name__ == '__main__':args = argparse.ArgumentParser( __version__)args.add_argument('host', default='localhost',help='mail server hostanme')args.add_argument('port', default=25,type=int,help='server port')args.add_argument('user_name', default='xxx@xxx.com',help='user name')args.add_argument('user_pass', default='123456',help='user pass')args.add_argument('recv_name_file', default='recv_name',help='recv name')args.add_argument('encode_type', default='BASE64',help='input msg text encode type:BASE64|QP|7or8bit')args.add_argument('--send_num',default=1,type=int,help='mail send num')args.add_argument('--ssl', action='store_true',help='Use SSL')args.add_argument('--debug', type=int,help='Debug level 1-5')args.add_argument('--verbose', action='store_true', default=False,help='Disable verbose mode')main(args.parse_args())
转载于:https://blog.51cto.com/14208524/2378912