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: 发送给谁
"""
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)
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)