最近研究邮件透明加密技术,,需要使用脚本自动发送邮件测试,于是使用python写了一个小程序。程序可以自动选择不定数量的附件,随机选择主题,随机选择正文,然后自由组合发送,非常适合邮件方面的测试任务。顺便说一下邮件透明加密技术和市场上的其他邮件加密技术相比再部署上非常简单。”透明“二字就是部署不改变用户原有习惯,目前的产品有天御云安的隐密邮,网址是https://mail.tyyunan.com/, 各位感兴趣的可以看一下。
# -*- coding: utf-8 -*-
__version__ = ‘‘‘Python-based smtp Client
Copyright (C) 2018 Chunyu Cao
This is free software; see LICENSE file for copying conditions. There is NO
warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
‘‘‘
# py .\smtp_client.py 10.115.5.68 25 [email protected] 123456 recv_name BASE64 --send_num 1
import time
import random
import json
import smtplib
import os
import argparse
import base64
from urllib import request
from urllib import error
from email.mime.text import MIMEText
from email.mime.application import MIMEApplication
from email.mime.multipart import MIMEMultipart
from email.mime.image import MIMEImage
from email import encoders
from email.message import Message
from email.charset import Charset
from email.charset import QP
from email.charset import BASE64
from email.charset import SHORTEST
subject = [‘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))
raise
class SmtpClient:
def __init__(self,args,file_path,subject_file_name,text_file_name):
self.args = args
smtplib.Debug = args.debug
self.recv_name =[]
data = []
self.text_file_name = text_file_name
with 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 = SHORTEST
charset.body_encoding = encode_type
self.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 = SHORTEST
charset.body_encoding = encode_type
text_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_name
self.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_name
self.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,"[email protected]",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!‘)
raise
def 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))
raise
def logout(self):
try:
self.smtp.close()
except Exception as e:
print(‘logout fail! Error:‘+str(e))
raise
def main(args):
print(args)
file_dir = os.getcwd()
send_num = args.send_num
if args.encode_type == ‘QP‘:
encode_type = QP
elif args.encode_type == ‘BASE64‘:
encode_type = BASE64
else:
encode_type = -1
while 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 -= 1
print(‘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=‘[email protected]‘,
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
时间: 2024-10-10 14:50:02