From 6f1da0cbb259ef2108caab0b8896fd654c18d6ee Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E6=9D=8E=E4=BC=9F?= <250213850@qq.com> Date: Thu, 20 Oct 2022 17:24:33 +0800 Subject: [PATCH] =?UTF-8?q?1.=E5=A4=84=E7=90=86=E9=82=AE=E4=BB=B6=E7=9A=84?= =?UTF-8?q?=E5=8F=91=E9=80=81=EF=BC=8C=E6=96=B0=E5=A2=9E=E9=99=84=E4=BB=B6?= =?UTF-8?q?=E5=8A=9F=E8=83=BD?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- api/api_v1/endpoints/interview.py | 41 +++++++++++---- utils/dingding.py | 11 +++- utils/func.py | 84 ++++++++++++++++++++++--------- 3 files changed, 100 insertions(+), 36 deletions(-) diff --git a/api/api_v1/endpoints/interview.py b/api/api_v1/endpoints/interview.py index 78e1c42..04e96c9 100644 --- a/api/api_v1/endpoints/interview.py +++ b/api/api_v1/endpoints/interview.py @@ -4,12 +4,12 @@ import json import operator import os import re -from typing import Any +from typing import Any, List, Union from obs import ObsClient from copy import deepcopy import pandas as pd 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 motor.motor_asyncio import AsyncIOMotorDatabase @@ -22,7 +22,7 @@ from schemas import ExtendendOAuth from utils.dingding import * from utils.jianli import get_resume 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 from datetime import datetime from core.configuration import * @@ -1459,24 +1459,43 @@ async def get_str_mail( @router.post("/send_str_mail") async def send_mail( 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), current_user: schemas.UserDB = Depends(deps.get_current_user) ) -> schemas.Msg: """发送邮件""" try: - # 发送邮件 - send_str_mail(data_in.email_str, data_in.email) + if file == None: + # 发送邮件 + 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] - await crud.email_record.create(db, schemas.email_record(user_id=data_in.user_id, text=data_in.email_str, - times=now_time, name=data_in.name, state=1, + await crud.email_record.create(db, schemas.email_record(user_id=user_id, text=email_str, + times=now_time, name=name, state=1, read_status=0, type='email')) return schemas.Msg(code=200, msg='邮件发送成功', data='') - except Exception: + except Exception as e: + print(e) 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, - times=now_time, name=data_in.name, state=0, + await crud.email_record.create(db, schemas.email_record(user_id=user_id, text=email_str, + times=now_time, name=name, state=0, read_status=0, type='email')) return schemas.Msg(code=200, msg='邮件发送失败', data='') diff --git a/utils/dingding.py b/utils/dingding.py index e74efe7..1aa833a 100644 --- a/utils/dingding.py +++ b/utils/dingding.py @@ -1,5 +1,6 @@ # -*- coding: utf-8 -*- # This file is auto-generated, don't edit it. Thanks. +import datetime import json import pprint 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_openapi import models as open_api_models from core.config import Settings, Debug -from utils import get_msec + Settings = Settings() Mongo = Debug() @@ -27,6 +28,14 @@ password = Settings.REDIS_CONF.get('password') redisdb = redis.Redis(host=host, port=port, db=db) 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(): """ diff --git a/utils/func.py b/utils/func.py index 7b6cffc..479e5f1 100644 --- a/utils/func.py +++ b/utils/func.py @@ -3,9 +3,12 @@ import json import os import random +import sched import threading import time import datetime +from email.mime.application import MIMEApplication +from email.mime.multipart import MIMEMultipart from math import ceil import pandas as pd import smtplib @@ -18,7 +21,14 @@ import calendar from core.config import Settings 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(): 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 """ 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['Subject'] = Settings.subject # 邮件的主题,也可以说是标题 + msg['Subject'] = subject # 邮件的主题,也可以说是标题 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(Settings.my_sender, [my_user, ], msg.as_string()) # 括号中对应的是发件人邮箱账号,收件人邮箱账号,发送邮件 + server.sendmail(my_sender, [my_user, ], msg.as_string()) # 括号中对应的是发件人邮箱账号,收件人邮箱账号,发送邮件 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): 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( @@ -426,72 +462,72 @@ def run_task(data): 重启服务 data为读取的json文件数据 """ - res = Settings.scheduler.queue + res = scheduler.queue uid = [i.kwargs['uid'] for i in res] # 取所有的任务uid for k, v in data.items(): if k not in uid: # 在现有任务里面不在json文件里面,则启动json文件里面的一个任务 now = str(time.time()).split('.')[0] end_time = v['times'] - int(now) - #没有过时的才会重启任务 - if end_time >0: - Settings.scheduler.enter(end_time, 1, task, kwargs=v) - t = threading.Thread(target=Settings.scheduler.run) + # 没有过时的才会重启任务 + if end_time > 0: + scheduler.enter(end_time, 1, task, kwargs=v) + t = threading.Thread(target=scheduler.run) t.start() def judge(**kwarg): # 没有任务 - if Settings.scheduler.empty(): + if scheduler.empty(): with open('task.json', 'r', encoding='utf-8') as f: - ff=f.read() + ff = f.read() if ff == '': - data={} + data = {} else: data = json.loads(ff) if data == {}: # 创建一个任务 - Settings.scheduler.enter(3600, 1, task, kwargs=kwarg) + scheduler.enter(3600, 1, task, kwargs=kwarg) data[kwarg['uid']] = kwarg jsontext = json.dumps(data) else: # 重启所有服务 run_task(data) # 再添加这次的服务 - Settings.scheduler.enter(3600, 1, task, kwargs=kwarg) + scheduler.enter(3600, 1, task, kwargs=kwarg) data[kwarg['uid']] = kwarg jsontext = json.dumps(data) write_task(jsontext) # 开启线程 - t = threading.Thread(target=Settings.scheduler.run) + t = threading.Thread(target=scheduler.run) t.start() else: # 查询创建了的任务 - res = Settings.scheduler.queue - uid = [i.kwargs['uid'] for i in res]#在执行中的任务uid + res = scheduler.queue + uid = [i.kwargs['uid'] for i in res] # 在执行中的任务uid if not kwarg['types']: # 换新的任务 - if kwarg['uid'] in uid:#如果新开的任务在执行的任务中 + if kwarg['uid'] in uid: # 如果新开的任务在执行的任务中 for i in res: # 如存在同样的求职者id,取消老任务 if i.kwargs['uid'] == kwarg['uid']: - Settings.scheduler.cancel(i) + scheduler.cancel(i) with open('task.json', 'r', encoding='utf-8') as f: # 取消json任务记录 data = json.load(f) for k, v in data.items(): if v['uid'] == kwarg['uid']: - data[kwarg['uid']]=kwarg - Settings.scheduler.enter(3600, 1, task, kwargs=kwarg) # 新任务 + data[kwarg['uid']] = kwarg + scheduler.enter(3600, 1, task, kwargs=kwarg) # 新任务 data[kwarg['uid']] = kwarg - else:#不在 + else: # 不在 with open('task.json', 'r', encoding='utf-8') as f: # 添加json任务记录 data = json.load(f) data['uid'] = kwarg['uid'] - Settings.scheduler.enter(3600, 1, task, kwargs=kwarg) # 新任务 + scheduler.enter(3600, 1, task, kwargs=kwarg) # 新任务 jsontext = json.dumps(data) write_task(jsontext) else: # 删除任务 for i in res: # 如存在同样的求职者id,取消老任务 if i.kwargs['uid'] == kwarg['uid']: - Settings.scheduler.cancel(i) + scheduler.cancel(i) break with open('task.json', 'r', encoding='utf-8') as f: # 取消json任务记录 data = json.load(f)