feat: use Mailer template

This commit is contained in:
Ting-Jun Wang 2024-07-30 16:03:14 +08:00
parent 77b51204af
commit 5b4982acf1
Signed by: snsd0805
GPG Key ID: 48D331A3D6160354
2 changed files with 39 additions and 12 deletions

27
mailer.py Normal file
View File

@ -0,0 +1,27 @@
import smtplib
from email.mime.text import MIMEText
class Mailer():
def __init__(self, google_owner, google_code):
self.google_owner = google_owner
self.google_code = google_code
def send(self, sender, receiver, subject, msg):
msg = MIMEText(msg, 'html')
msg['Subject'] = subject
msg['From'] = sender
msg['To'] = receiver
smtp = smtplib.SMTP('smtp.gmail.com', 587)
smtp.ehlo()
smtp.starttls()
smtp.login(self.google_owner, self.google_code)
status = smtp.send_message(msg)
smtp.quit()
if status == {}:
return True
else:
return False

24
main.py
View File

@ -5,11 +5,14 @@ import time
from bs4 import BeautifulSoup
from email.mime.text import MIMEText
import os
from mailer import Mailer
DEBUG_MODE = False
URL = 'https://www.cmlab.csie.ntu.edu.tw/status-gpu/'
GPU_LIMIT = 2
GOOGLE_OWNER = "snsd0805@cmlab.csie.ntu.edu.tw"
GOOGLE_CODE = os.environ['GOOGLE_CODE']
MAIL_CD_HOUR = 12
MAIL_MESSAGE = '''
@ -39,6 +42,8 @@ Email: unix_manager@cmlab.csie.ntu.edu.tw<br>
</pre>
'''
mailer = Mailer(GOOGLE_OWNER, GOOGLE_CODE)
def get_server_gpu_status() -> list:
'''
It will get html from CMLab webpage.
@ -188,30 +193,25 @@ def mail_notify(violators: list) -> None:
username = violator['username']
if check_send(send_log, username):
week_count = 1 if username not in send_log else send_log[username]['week_count']+1
# update log
send_log[username] = time.time()
send_log[username] = {
'time': time.time(),
'week_count': week_count
}
with open('send_log.json', 'w') as fp:
json.dump(send_log, fp)
usage_msg = get_usage_msg(violator['usage'])
print(f' {username} {usage_msg}')
msg = MAIL_MESSAGE.format(username, usage_msg)
msg = MIMEText(msg, 'html') # 郵件內文
msg['Subject'] = f'[網管通知] 提醒您已經超過 CMLab GPU 使用限制!({username})'
msg['From'] = 'unix_manager@cmlab.csie.ntu.edu.tw'
msg['To'] = f'{username}@cmlab.csie.ntu.edu.tw' if not DEBUG_MODE else 'snsd0805@cmlab.csie.ntu.edu.tw'
# msg['Cc'] = 'unix_manager@cmlab.csie.ntu.edu.tw' if not DEBUG_MODE else 'snsd0805@cmlab.csie.ntu.edu.tw'
smtp = smtplib.SMTP('smtp.gmail.com', 587)
smtp.ehlo()
smtp.starttls()
smtp.login('snsd0805@cmlab.csie.ntu.edu.tw', GOOGLE_CODE)
status = mailer.send('unix_manager@cmlab.csie.ntu.edu.tw', f'{username}@cmlab.csie.ntu.edu.tw' if not DEBUG_MODE else 'snsd0805@cmlab.csie.ntu.edu.tw', \
f'[網管通知] 提醒您已經超過 CMLab GPU 使用限制!({username})', msg)
status = smtp.send_message(msg)
if status == {}:
print(f' {username}, 郵件傳送成功!')
else:
print(f' {username}, 郵件傳送失敗...')
smtp.quit()
if __name__ == '__main__':