-
Notifications
You must be signed in to change notification settings - Fork 42
/
core.py
92 lines (74 loc) · 2.21 KB
/
core.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
# !/usr/bin/env python
# coding=utf-8
import datetime
import os
import re
import smtplib
from email.header import Header
from email.mime.text import MIMEText
import requests
from bs4 import BeautifulSoup
from tenacity import retry, stop_after_attempt
from receivers import MAIL_RECEIVER
START_URL = "https://github.com/ruanyf/weekly"
HEADERS = {
"X-Requested-With": "XMLHttpRequest",
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 "
"(KHTML, like Gecko) Chrome/56.0.2924.87 Safari/537.36",
}
# 隐私数据存放在环境变量中
MAIL_HOST = os.environ.get("MAIL_HOST")
MAIL_USER = os.environ.get("MAIL_USER")
MAIL_PASS = os.environ.get("MAIL_PASS")
MAIL_SENDER = os.environ.get("MAIL_SENDER")
MAIL_ENCODING = "utf8"
def is_friday():
"""
判断是否周五
"""
return datetime.datetime.now().weekday() == 4
@retry(stop=stop_after_attempt(3))
def get_email_content():
"""
获取邮件内容
"""
resp = requests.get(START_URL, headers=HEADERS).text
result = re.findall(r'<a href=\"(.*?issue-\d*\.md)\">(.*?)</a>', resp)
url, num = result[0]
readme_url = "https://github.com" + url
readme_content = requests.get(readme_url, headers=HEADERS).text
bs = BeautifulSoup(readme_content, "lxml").find("article")
html = """
<html lang="en">
<head>
<meta charset="UTF-8">
</head>
<body>
<div>
<a href="{0}">阮一峰技术周刊{1} 📅</a></br></br>
{2}
<div>
</body>
</html>
"""
return html.format(readme_url, num, bs)
def send_email():
"""
发送邮件
"""
if not is_friday():
return
content = get_email_content()
message = MIMEText(content, "html", MAIL_ENCODING)
message["From"] = Header("weekly-bot", MAIL_ENCODING)
message["To"] = Header("Reader")
message["Subject"] = Header("weekly", MAIL_ENCODING)
try:
smtp_obj = smtplib.SMTP_SSL(MAIL_HOST)
smtp_obj.login(MAIL_USER, MAIL_PASS)
smtp_obj.sendmail(MAIL_SENDER, MAIL_RECEIVER, message.as_string())
smtp_obj.quit()
except Exception as e:
print(e)
if __name__ == "__main__":
send_email()