使用python自动发送邮件

最近研究邮件透明加密技术,,需要使用脚本自动发送邮件测试,于是使用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

使用python自动发送邮件的相关文章

利用Python自动发送邮件

# -*- coding:utf-8 -*-from email.mime.text import MIMETextfrom email.header import Headerimport smtplib def send_mail(file_new): f = open(file_new,'rb') mail_body = f.read() f.close() msg = MIMEText(mail_body,'html','utf-8')  msg['Subject'] = Header(

Appium+python 自动发送邮件(1)

SMTP:简单传输协议,实在Internet上传输Email的事实标准. Python的smtplib模块提供了一种很方便的途径来发送电子邮件,它对SMTP协议进行了简单的封装. python中发送邮件除了SMTP模块外,还需用到email模块.email模块主要用来定义邮件的标题.正文.附件. 一.SMTP的方法 1.SMTP模块的方法 connect(host,port) host:指定连接的邮箱服务器 port:指定连接服务器的端口号 login(user,passwork) user:登

Python 自动发送邮件

简单邮件传输协议(SMTP)是一种协议,用于在邮件服务器之间发送电子邮件和路由电子邮件.Python提供smtplib模块,该模块定义了一个SMTP客户端会话对象,可用于使用SMTP或ESMTP侦听器守护程序向任何互联网机器发送邮件. SMTP通讯的基本流程可以概括为以下几点: 1.连接SMTP服务器 2.登陆用户名和密码 3.发送指定邮件内容 4.退出SMTP连接 一.发送纯文本格式邮件 1 #coding:utf-8 2 import sys 3 reload(sys) 4 sys.setd

python自动发送邮件

Python 的 smtplib 模块提供了发送电子邮件的功能.测试报告出来后,然后就把报告发送到邮箱. 一.先来看简单的列子 使用QQ邮箱发送邮件,使用的是授权码,需要先到QQ邮箱申请授权码. 邮箱设置-->账户 # coding:utf-8 import smtplib from email.mime.text import MIMEText # 参数配置 smtpserver = "smtp.qq.com" # 发送邮件的服务器 port = 465 # 端口 sender

Appium+python 自动发送邮件(2)

移动端执行完测试case之后,通过邮件自动发送测试报告.大体流程如下: 1.通过unittest框架的discover()发现所有测试用例 2.使用HTMLTestRunner的run()方法运行测试用例,生成HTML测试报告 3.寻找测试报告目录下的最新测试报告,返回最新测试报告的路径 4.将最新测试报告路径传给send_mail()函数,发送带HTML格式的邮件 # coding:utf-8 import unittest import time import smtplib import

python+selenium 发送邮件

import time from selenium import webdriver from selenium.webdriver import ChromeOptions from selenium.webdriver.common.keys import Keys from getpass import getpass def run(): driver.get(url='https://mail.qq.com/') # 遇到iframe,需要切换 iframe_list = driver

在服务器上使用python自动获取zabbix上图形并发送邮件

由于某些需求,需要每天发送邮件给相关人员,其中包含前一天的zabbix监控图形,每天登陆并手动发送的话很麻烦. 本着简单重复的工作交给机器做的原则,写了个python程序自动获取图形并发送. 大致的思路是: 模拟登陆zabbix ---> 找到需要的图像并下载到本地 --->使用python发送邮件 一.在服务器上模拟登陆zabbix,并且将需要的图像下载到本地 #!/usr/bin/env python # -*- coding:utf-8 -*- import HTMLParser imp

Github 大牛封装 Python 代码,实现自动发送邮件只需三行代码

*注意:全文代码可左右滑动观看 在运维开发中,使用 Python 发送邮件是一个非常常见的应用场景.今天一起来探讨一下,GitHub 的大牛门是如何使用 Python 封装发送邮件代码的. 一般发邮件方法 SMTP是发送邮件的协议,Python内置对SMTP的支持,可以发送纯文本邮件.HTML邮件以及带附件的邮件. 我们以前在通过Python实现自动化邮件功能的时候是这样的: import smtplibfrom email.mime.text import MIMETextfrom email

python之发送邮件~

在之前的工作中,测试web界面产生的报告是自动使用python中发送邮件模块实现,在全部自动化测试完成之后,把报告自动发送给相关人员 其实在python中很好实现,一个是smtplib和mail俩个模块来实现,主要如下: import smtplibfrom email.mime.text import MIMETextfrom email.mime.multipart import MIMEMultipartfrom email.mime.base import MIMEBaseimport