python 邮件发送及发送短信验证码
import os
import random
import smtplib
from email.mime.multipart import MIMEMultipart
from email.header import Header
from email.mime.text import MIMEText
import openpyxl
import requests
def send_email(user_name, pwd, message, to):
"""
:param user_name: 发送者的用户名
:param pwd: 密码
:param message: 内容
:param to: 发送给谁
"""
# 连接邮件服务器 每个邮件的服务器地址不一样 这里使用163邮箱
connect = smtplib.SMTP_SSL('smtp.163.com', 465)
# 登陆
connect.login(user_name, pwd)
# 发送邮件
connect.sendmail(user_name, to, message.as_string())
# 关闭连接
connect.quit()
def write_email(user_name, to):
"""
:param user_name: 发送者
:param to: 接收者
:return:
"""
# 创建邮件对象
email = MIMEMultipart()
# 邮件的基础设置
email['Subject'] = Header('xmy的作业', 'utf-8').encode()
email['To'] = to
email['From'] = f'{user_name} <{user_name}>'
# 添加文本
text = MIMEText('成绩单在附件中,请注意查收', 'plain', 'utf-8')
email.attach(text)
# 这里测试 创建了一个Excel文件
write_excel('file/test.xlsx')
# 打开这个文件
with open('file/test.xlsx', 'rb') as file:
file1 = MIMEText(file.read(), 'base64', 'utf-8')
file1['Content-Disposition'] = ' attachment; filename="test.xlsx"'
# 将这个文件添加到邮件对象中
email.attach(file1)
return email
def random_score():
return [random.randint(0, 100) for _ in range(3)]
def write_excel(file_path):
"""
:param file_path: 写的文件路径
:return:
"""
if os.path.exists(file_path):
print('打开')
wb = openpyxl.load_workbook(file_path)
else:
wb = openpyxl.Workbook()
wb.save(file_path)
student_table = [
['姓名', '语文', '数学', '英语'],
['001', *random_score()],
['002', *random_score()],
['003', *random_score()],
['004', *random_score()],
['005', *random_score()],
['006', *random_score()]
]
sheet1 = wb.active
for i in range(1, len(student_table)+1):
for j in range(1, len(student_table[0])+1):
sheet1.cell(i, j).value = student_table[i-1][j-1]
wb.save(file_path)
def send_messag(tel, message):
"""调用螺丝帽短信网关发送短信
:param tel: 接收短信的手机号
:param message: 短信内容
"""
resp = requests.post(
url='http://sms-api.luosimao.com/v1/send.json',
auth=('api', 'key-授权码'),
data={
'mobile': tel,
'message': message
},
timeout=3,
verify=False
)
return resp.json()
if __name__ == '__main__':
user_name = '发送者邮箱地址'
pwd = '发送者的邮箱授权码' # 可以在你使用的邮箱设置中找到开启
to = '接收者的邮箱' # 可以写多个分号隔开
send_email(user_name, pwd, write_email(user_name, to), to)
result = send_messag('接收者手机号', f'xmy的作业已经发送到你的邮箱【铁壳测试】')
print(result)