1.处理邮件的发送,新增附件功能
This commit is contained in:
parent
5c9cb90957
commit
6f1da0cbb2
@ -4,12 +4,12 @@ import json
|
|||||||
import operator
|
import operator
|
||||||
import os
|
import os
|
||||||
import re
|
import re
|
||||||
from typing import Any
|
from typing import Any, List, Union
|
||||||
from obs import ObsClient
|
from obs import ObsClient
|
||||||
from copy import deepcopy
|
from copy import deepcopy
|
||||||
import pandas as pd
|
import pandas as pd
|
||||||
import pymongo
|
import pymongo
|
||||||
from fastapi import APIRouter, Depends, Request, File, UploadFile
|
from fastapi import APIRouter, Depends, Request, File, UploadFile, Form
|
||||||
from fastapi.security import OAuth2PasswordRequestForm
|
from fastapi.security import OAuth2PasswordRequestForm
|
||||||
from motor.motor_asyncio import AsyncIOMotorDatabase
|
from motor.motor_asyncio import AsyncIOMotorDatabase
|
||||||
|
|
||||||
@ -22,7 +22,7 @@ from schemas import ExtendendOAuth
|
|||||||
from utils.dingding import *
|
from utils.dingding import *
|
||||||
from utils.jianli import get_resume
|
from utils.jianli import get_resume
|
||||||
from utils.re_to_jianli import fmt_txt, getText_pdf
|
from utils.re_to_jianli import fmt_txt, getText_pdf
|
||||||
from utils.func import get_uid
|
from utils.func import get_uid, send_affix_mail, location_file
|
||||||
import crud, schemas
|
import crud, schemas
|
||||||
from datetime import datetime
|
from datetime import datetime
|
||||||
from core.configuration import *
|
from core.configuration import *
|
||||||
@ -1459,24 +1459,43 @@ async def get_str_mail(
|
|||||||
@router.post("/send_str_mail")
|
@router.post("/send_str_mail")
|
||||||
async def send_mail(
|
async def send_mail(
|
||||||
request: Request,
|
request: Request,
|
||||||
data_in: schemas.send_str_mail,
|
#data_in: schemas.send_str_mail,
|
||||||
|
user_id: str =Form(...), # 接收者的唯一id
|
||||||
|
name: str =Form(...), # 接收者的名字
|
||||||
|
email: str=Form(...), # 接收者的邮箱
|
||||||
|
email_str: str =Form(...), # 需要发送的文本内容
|
||||||
|
file:Union[List[UploadFile], None] = File(None),
|
||||||
db: AsyncIOMotorDatabase = Depends(get_database),
|
db: AsyncIOMotorDatabase = Depends(get_database),
|
||||||
current_user: schemas.UserDB = Depends(deps.get_current_user)
|
current_user: schemas.UserDB = Depends(deps.get_current_user)
|
||||||
) -> schemas.Msg:
|
) -> schemas.Msg:
|
||||||
"""发送邮件"""
|
"""发送邮件"""
|
||||||
try:
|
try:
|
||||||
|
if file == None:
|
||||||
# 发送邮件
|
# 发送邮件
|
||||||
send_str_mail(data_in.email_str, data_in.email)
|
send_affix_mail(email_str, [email])
|
||||||
|
else:
|
||||||
|
#带附件的
|
||||||
|
file_list=[]
|
||||||
|
for i in file:
|
||||||
|
contents = await i.read()
|
||||||
|
filename = i.filename
|
||||||
|
file_list.append(filename)
|
||||||
|
with open(location_file + '/' + filename, "wb") as f:
|
||||||
|
# 将获取的file文件内容,写入到新文件中
|
||||||
|
f.write(contents)
|
||||||
|
send_affix_mail(email_str, [email],file_list)
|
||||||
|
#send_str_mail(data_in.email_str, data_in.email)
|
||||||
# 保存发送邮件的记录
|
# 保存发送邮件的记录
|
||||||
now_time = str(datetime.now()).split('.')[0]
|
now_time = str(datetime.now()).split('.')[0]
|
||||||
await crud.email_record.create(db, schemas.email_record(user_id=data_in.user_id, text=data_in.email_str,
|
await crud.email_record.create(db, schemas.email_record(user_id=user_id, text=email_str,
|
||||||
times=now_time, name=data_in.name, state=1,
|
times=now_time, name=name, state=1,
|
||||||
read_status=0, type='email'))
|
read_status=0, type='email'))
|
||||||
return schemas.Msg(code=200, msg='邮件发送成功', data='')
|
return schemas.Msg(code=200, msg='邮件发送成功', data='')
|
||||||
except Exception:
|
except Exception as e:
|
||||||
|
print(e)
|
||||||
now_time = str(datetime.now()).split('.')[0]
|
now_time = str(datetime.now()).split('.')[0]
|
||||||
await crud.email_record.create(db, schemas.email_record(user_id=data_in.user_id, text=data_in.email_str,
|
await crud.email_record.create(db, schemas.email_record(user_id=user_id, text=email_str,
|
||||||
times=now_time, name=data_in.name, state=0,
|
times=now_time, name=name, state=0,
|
||||||
read_status=0, type='email'))
|
read_status=0, type='email'))
|
||||||
return schemas.Msg(code=200, msg='邮件发送失败', data='')
|
return schemas.Msg(code=200, msg='邮件发送失败', data='')
|
||||||
|
|
||||||
|
@ -1,5 +1,6 @@
|
|||||||
# -*- coding: utf-8 -*-
|
# -*- coding: utf-8 -*-
|
||||||
# This file is auto-generated, don't edit it. Thanks.
|
# This file is auto-generated, don't edit it. Thanks.
|
||||||
|
import datetime
|
||||||
import json
|
import json
|
||||||
import pprint
|
import pprint
|
||||||
from copy import deepcopy
|
from copy import deepcopy
|
||||||
@ -14,7 +15,7 @@ from alibabacloud_tea_util import models as util_models
|
|||||||
from alibabacloud_tea_util.client import Client as UtilClient
|
from alibabacloud_tea_util.client import Client as UtilClient
|
||||||
from alibabacloud_tea_openapi import models as open_api_models
|
from alibabacloud_tea_openapi import models as open_api_models
|
||||||
from core.config import Settings, Debug
|
from core.config import Settings, Debug
|
||||||
from utils import get_msec
|
|
||||||
|
|
||||||
Settings = Settings()
|
Settings = Settings()
|
||||||
Mongo = Debug()
|
Mongo = Debug()
|
||||||
@ -27,6 +28,14 @@ password = Settings.REDIS_CONF.get('password')
|
|||||||
redisdb = redis.Redis(host=host, port=port, db=db)
|
redisdb = redis.Redis(host=host, port=port, db=db)
|
||||||
myClient = pymongo.MongoClient(clientMongo)
|
myClient = pymongo.MongoClient(clientMongo)
|
||||||
|
|
||||||
|
def get_msec():
|
||||||
|
"""
|
||||||
|
获取当前日期的毫秒级时间
|
||||||
|
:return:
|
||||||
|
"""
|
||||||
|
today = datetime.date.today().strftime('%Y-%m-%d 23:59:59')
|
||||||
|
t = int(time.mktime(time.strptime(today, "%Y-%m-%d %H:%M:%S")))
|
||||||
|
return int(round(t * 1000))
|
||||||
|
|
||||||
def get_token():
|
def get_token():
|
||||||
"""
|
"""
|
||||||
|
@ -3,9 +3,12 @@
|
|||||||
import json
|
import json
|
||||||
import os
|
import os
|
||||||
import random
|
import random
|
||||||
|
import sched
|
||||||
import threading
|
import threading
|
||||||
import time
|
import time
|
||||||
import datetime
|
import datetime
|
||||||
|
from email.mime.application import MIMEApplication
|
||||||
|
from email.mime.multipart import MIMEMultipart
|
||||||
from math import ceil
|
from math import ceil
|
||||||
import pandas as pd
|
import pandas as pd
|
||||||
import smtplib
|
import smtplib
|
||||||
@ -18,7 +21,14 @@ import calendar
|
|||||||
from core.config import Settings
|
from core.config import Settings
|
||||||
from utils.dingding import Sample
|
from utils.dingding import Sample
|
||||||
|
|
||||||
|
# 构造一个sched.scheduler类,用于给推荐通知做定时任务
|
||||||
|
scheduler = sched.scheduler(time.time, time.sleep)
|
||||||
|
|
||||||
|
my_sender = '250213850@qq.com' # 发件人邮箱账号
|
||||||
|
my_pass = 'whrsugtgkstibjdj' # 发件人邮箱密码
|
||||||
|
subject = '入职通知' # 邮件的主题,也可以说是标题
|
||||||
|
mail_host = 'smtp.qq.com'
|
||||||
|
location_file = 'C:/Users/Administrator/Desktop/ddemo' # 默认读取转存的文件地址(上传至邮箱的文件)
|
||||||
def get_uid():
|
def get_uid():
|
||||||
return hex(int(time.time() * 10 ** 7) + random.randint(0, 10000))[2:]
|
return hex(int(time.time() * 10 ** 7) + random.randint(0, 10000))[2:]
|
||||||
|
|
||||||
@ -231,17 +241,43 @@ def send_str_mail(str_msg, my_user):
|
|||||||
:return: bool
|
:return: bool
|
||||||
"""
|
"""
|
||||||
msg = MIMEText(str_msg, 'plain', 'utf-8')
|
msg = MIMEText(str_msg, 'plain', 'utf-8')
|
||||||
msg['From'] = formataddr(["乐谷游戏人事", Settings.my_sender]) # 括号里的对应发件人邮箱昵称,发件人邮箱账号
|
msg['From'] = formataddr(["乐谷游戏人事", my_sender]) # 括号里的对应发件人邮箱昵称,发件人邮箱账号
|
||||||
msg['To'] = formataddr(["FK", my_user]) # 括号里的对应收件人邮箱昵称,收件人邮箱账号
|
msg['To'] = formataddr(["FK", my_user]) # 括号里的对应收件人邮箱昵称,收件人邮箱账号
|
||||||
msg['Subject'] = Settings.subject # 邮件的主题,也可以说是标题
|
msg['Subject'] = subject # 邮件的主题,也可以说是标题
|
||||||
|
|
||||||
server = smtplib.SMTP_SSL("smtp.qq.com", 465) # 发件人邮箱中的SMTP服务器,端口是25
|
server = smtplib.SMTP_SSL("smtp.qq.com", 465) # 发件人邮箱中的SMTP服务器,端口是25
|
||||||
server.login(Settings.my_sender, Settings.my_pass) # 括号中对应的是发件人邮箱账号,邮箱密码
|
server.login(my_sender, my_pass) # 括号中对应的是发件人邮箱账号,邮箱密码
|
||||||
# server.sendmail(my_sender, [my_user, ], msg.as_string()) # 括号中对应的是发件人邮箱账号,收件人邮箱账号,发送邮件
|
# server.sendmail(my_sender, [my_user, ], msg.as_string()) # 括号中对应的是发件人邮箱账号,收件人邮箱账号,发送邮件
|
||||||
server.sendmail(Settings.my_sender, [my_user, ], msg.as_string()) # 括号中对应的是发件人邮箱账号,收件人邮箱账号,发送邮件
|
server.sendmail(my_sender, [my_user, ], msg.as_string()) # 括号中对应的是发件人邮箱账号,收件人邮箱账号,发送邮件
|
||||||
server.quit() # 关闭连接
|
server.quit() # 关闭连接
|
||||||
|
|
||||||
|
|
||||||
|
def send_affix_mail(str_msg: str, send_to: list, file_name: list = None):
|
||||||
|
"""
|
||||||
|
发送邮件,包含文本或和附件
|
||||||
|
:param str_msg: 发送的邮件内容
|
||||||
|
:param send_to: 接收者的邮箱
|
||||||
|
:param file_name: 上传的附件
|
||||||
|
"""
|
||||||
|
msg = MIMEMultipart() # 创建一个带附件的实例
|
||||||
|
msg["Subject"] = "面试通知"
|
||||||
|
msg["From"] = my_sender
|
||||||
|
msg["To"] = ','.join(send_to)
|
||||||
|
# ---文字部分---
|
||||||
|
part = MIMEText(str_msg)
|
||||||
|
msg.attach(part)
|
||||||
|
# ---附件部分---
|
||||||
|
if file_name != None:
|
||||||
|
for i in file_name:
|
||||||
|
part = MIMEApplication(open(location_file + '/' + i, 'rb').read())
|
||||||
|
part.add_header('Content-Disposition', 'attachment', filename=i)
|
||||||
|
msg.attach(part)
|
||||||
|
smpt = smtplib.SMTP_SSL(mail_host, 465, 'utf-8')
|
||||||
|
smpt.login(my_sender, my_pass)
|
||||||
|
smpt.sendmail(my_sender, send_to, msg.as_string())
|
||||||
|
smpt.quit()
|
||||||
|
|
||||||
|
|
||||||
def get_week(date_str=None):
|
def get_week(date_str=None):
|
||||||
if date_str and isinstance(date_str, str):
|
if date_str and isinstance(date_str, str):
|
||||||
now_time = (p1.strptime(date_str + " 00:00:00", "%Y-%m-%d %H:%M:%S") + datetime.timedelta(days=1)).strftime(
|
now_time = (p1.strptime(date_str + " 00:00:00", "%Y-%m-%d %H:%M:%S") + datetime.timedelta(days=1)).strftime(
|
||||||
@ -426,7 +462,7 @@ def run_task(data):
|
|||||||
重启服务
|
重启服务
|
||||||
data为读取的json文件数据
|
data为读取的json文件数据
|
||||||
"""
|
"""
|
||||||
res = Settings.scheduler.queue
|
res = scheduler.queue
|
||||||
uid = [i.kwargs['uid'] for i in res] # 取所有的任务uid
|
uid = [i.kwargs['uid'] for i in res] # 取所有的任务uid
|
||||||
for k, v in data.items():
|
for k, v in data.items():
|
||||||
if k not in uid: # 在现有任务里面不在json文件里面,则启动json文件里面的一个任务
|
if k not in uid: # 在现有任务里面不在json文件里面,则启动json文件里面的一个任务
|
||||||
@ -434,14 +470,14 @@ def run_task(data):
|
|||||||
end_time = v['times'] - int(now)
|
end_time = v['times'] - int(now)
|
||||||
# 没有过时的才会重启任务
|
# 没有过时的才会重启任务
|
||||||
if end_time > 0:
|
if end_time > 0:
|
||||||
Settings.scheduler.enter(end_time, 1, task, kwargs=v)
|
scheduler.enter(end_time, 1, task, kwargs=v)
|
||||||
t = threading.Thread(target=Settings.scheduler.run)
|
t = threading.Thread(target=scheduler.run)
|
||||||
t.start()
|
t.start()
|
||||||
|
|
||||||
|
|
||||||
def judge(**kwarg):
|
def judge(**kwarg):
|
||||||
# 没有任务
|
# 没有任务
|
||||||
if Settings.scheduler.empty():
|
if scheduler.empty():
|
||||||
with open('task.json', 'r', encoding='utf-8') as f:
|
with open('task.json', 'r', encoding='utf-8') as f:
|
||||||
ff = f.read()
|
ff = f.read()
|
||||||
if ff == '':
|
if ff == '':
|
||||||
@ -450,48 +486,48 @@ def judge(**kwarg):
|
|||||||
data = json.loads(ff)
|
data = json.loads(ff)
|
||||||
if data == {}:
|
if data == {}:
|
||||||
# 创建一个任务
|
# 创建一个任务
|
||||||
Settings.scheduler.enter(3600, 1, task, kwargs=kwarg)
|
scheduler.enter(3600, 1, task, kwargs=kwarg)
|
||||||
data[kwarg['uid']] = kwarg
|
data[kwarg['uid']] = kwarg
|
||||||
jsontext = json.dumps(data)
|
jsontext = json.dumps(data)
|
||||||
else: # 重启所有服务
|
else: # 重启所有服务
|
||||||
run_task(data)
|
run_task(data)
|
||||||
# 再添加这次的服务
|
# 再添加这次的服务
|
||||||
Settings.scheduler.enter(3600, 1, task, kwargs=kwarg)
|
scheduler.enter(3600, 1, task, kwargs=kwarg)
|
||||||
data[kwarg['uid']] = kwarg
|
data[kwarg['uid']] = kwarg
|
||||||
jsontext = json.dumps(data)
|
jsontext = json.dumps(data)
|
||||||
write_task(jsontext)
|
write_task(jsontext)
|
||||||
# 开启线程
|
# 开启线程
|
||||||
t = threading.Thread(target=Settings.scheduler.run)
|
t = threading.Thread(target=scheduler.run)
|
||||||
t.start()
|
t.start()
|
||||||
else:
|
else:
|
||||||
# 查询创建了的任务
|
# 查询创建了的任务
|
||||||
res = Settings.scheduler.queue
|
res = scheduler.queue
|
||||||
uid = [i.kwargs['uid'] for i in res] # 在执行中的任务uid
|
uid = [i.kwargs['uid'] for i in res] # 在执行中的任务uid
|
||||||
if not kwarg['types']: # 换新的任务
|
if not kwarg['types']: # 换新的任务
|
||||||
if kwarg['uid'] in uid: # 如果新开的任务在执行的任务中
|
if kwarg['uid'] in uid: # 如果新开的任务在执行的任务中
|
||||||
for i in res:
|
for i in res:
|
||||||
# 如存在同样的求职者id,取消老任务
|
# 如存在同样的求职者id,取消老任务
|
||||||
if i.kwargs['uid'] == kwarg['uid']:
|
if i.kwargs['uid'] == kwarg['uid']:
|
||||||
Settings.scheduler.cancel(i)
|
scheduler.cancel(i)
|
||||||
with open('task.json', 'r', encoding='utf-8') as f: # 取消json任务记录
|
with open('task.json', 'r', encoding='utf-8') as f: # 取消json任务记录
|
||||||
data = json.load(f)
|
data = json.load(f)
|
||||||
for k, v in data.items():
|
for k, v in data.items():
|
||||||
if v['uid'] == kwarg['uid']:
|
if v['uid'] == kwarg['uid']:
|
||||||
data[kwarg['uid']] = kwarg
|
data[kwarg['uid']] = kwarg
|
||||||
Settings.scheduler.enter(3600, 1, task, kwargs=kwarg) # 新任务
|
scheduler.enter(3600, 1, task, kwargs=kwarg) # 新任务
|
||||||
data[kwarg['uid']] = kwarg
|
data[kwarg['uid']] = kwarg
|
||||||
else: # 不在
|
else: # 不在
|
||||||
with open('task.json', 'r', encoding='utf-8') as f: # 添加json任务记录
|
with open('task.json', 'r', encoding='utf-8') as f: # 添加json任务记录
|
||||||
data = json.load(f)
|
data = json.load(f)
|
||||||
data['uid'] = kwarg['uid']
|
data['uid'] = kwarg['uid']
|
||||||
Settings.scheduler.enter(3600, 1, task, kwargs=kwarg) # 新任务
|
scheduler.enter(3600, 1, task, kwargs=kwarg) # 新任务
|
||||||
jsontext = json.dumps(data)
|
jsontext = json.dumps(data)
|
||||||
write_task(jsontext)
|
write_task(jsontext)
|
||||||
else: # 删除任务
|
else: # 删除任务
|
||||||
for i in res:
|
for i in res:
|
||||||
# 如存在同样的求职者id,取消老任务
|
# 如存在同样的求职者id,取消老任务
|
||||||
if i.kwargs['uid'] == kwarg['uid']:
|
if i.kwargs['uid'] == kwarg['uid']:
|
||||||
Settings.scheduler.cancel(i)
|
scheduler.cancel(i)
|
||||||
break
|
break
|
||||||
with open('task.json', 'r', encoding='utf-8') as f: # 取消json任务记录
|
with open('task.json', 'r', encoding='utf-8') as f: # 取消json任务记录
|
||||||
data = json.load(f)
|
data = json.load(f)
|
||||||
|
Loading…
Reference in New Issue
Block a user