-
-
Notifications
You must be signed in to change notification settings - Fork 4.9k
Expand file tree
/
Copy pathconstruct_email.py
More file actions
195 lines (177 loc) · 6.53 KB
/
construct_email.py
File metadata and controls
195 lines (177 loc) · 6.53 KB
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
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
from paper import ArxivPaper
import math
from tqdm import tqdm
from email.header import Header
from email.mime.text import MIMEText
from email.utils import parseaddr, formataddr
import smtplib
import datetime
import time
from loguru import logger
from typing import List
framework = """
<!DOCTYPE HTML>
<html>
<head>
<style>
.star-wrapper {
font-size: 1.3em; /* 调整星星大小 */
line-height: 1; /* 确保垂直对齐 */
display: inline-flex;
align-items: center; /* 保持对齐 */
}
.half-star {
display: inline-block;
width: 0.5em; /* 半颗星的宽度 */
overflow: hidden;
white-space: nowrap;
vertical-align: middle;
}
.full-star {
vertical-align: middle;
}
</style>
</head>
<body>
<div>
__CONTENT__
</div>
<br><br>
<div>
To unsubscribe, remove your email in your Github Action setting.
</div>
</body>
</html>
"""
def get_empty_html():
block_template = """
<table border="0" cellpadding="0" cellspacing="0" width="100%" style="font-family: Arial, sans-serif; border: 1px solid #ddd; border-radius: 8px; padding: 16px; background-color: #f9f9f9;">
<tr>
<td style="font-size: 20px; font-weight: bold; color: #333;">
No Papers Today. Take a Rest!
</td>
</tr>
</table>
"""
return block_template
def get_block_html(title:str, authors:str, rate:str,arxiv_id:str, abstract:str, pdf_url:str, code_url:str=None, affiliations:str=None):
code = f'<a href="{code_url}" style="display: inline-block; text-decoration: none; font-size: 14px; font-weight: bold; color: #fff; background-color: #5bc0de; padding: 8px 16px; border-radius: 4px; margin-left: 8px;">Code</a>' if code_url else ''
block_template = """
<table border="0" cellpadding="0" cellspacing="0" width="100%" style="font-family: Arial, sans-serif; border: 1px solid #ddd; border-radius: 8px; padding: 16px; background-color: #f9f9f9;">
<tr>
<td style="font-size: 20px; font-weight: bold; color: #333;">
{title}
</td>
</tr>
<tr>
<td style="font-size: 14px; color: #666; padding: 8px 0;">
{authors}
<br>
<i>{affiliations}</i>
</td>
</tr>
<tr>
<td style="font-size: 14px; color: #333; padding: 8px 0;">
<strong>Relevance:</strong> {rate}
</td>
</tr>
<tr>
<td style="font-size: 14px; color: #333; padding: 8px 0;">
<strong>arXiv ID:</strong> <a href="https://arxiv.org/abs/{arxiv_id}" target="_blank">{arxiv_id}</a>
</td>
</tr>
<tr>
<td style="font-size: 14px; color: #333; padding: 8px 0;">
<strong>TLDR:</strong> {abstract}
</td>
</tr>
<tr>
<td style="padding: 8px 0;">
<a href="{pdf_url}" style="display: inline-block; text-decoration: none; font-size: 14px; font-weight: bold; color: #fff; background-color: #d9534f; padding: 8px 16px; border-radius: 4px;">PDF</a>
{code}
</td>
</tr>
</table>
"""
return block_template.format(title=title, authors=authors,rate=rate,arxiv_id=arxiv_id, abstract=abstract, pdf_url=pdf_url, code=code, affiliations=affiliations)
def get_stars(score:float):
full_star = '<span class="full-star">⭐</span>'
half_star = '<span class="half-star">⭐</span>'
low = 6
high = 8
if score <= low:
return ''
elif score >= high:
return full_star * 5
else:
interval = (high-low) / 10
star_num = math.ceil((score-low) / interval)
full_star_num = int(star_num/2)
half_star_num = star_num - full_star_num * 2
return '<div class="star-wrapper">'+full_star * full_star_num + half_star * half_star_num + '</div>'
def render_email(papers:list[ArxivPaper]):
parts = []
if len(papers) == 0 :
return framework.replace('__CONTENT__', get_empty_html())
for p in tqdm(papers,desc='Rendering Email'):
rate = get_stars(p.score)
author_list = [a.name for a in p.authors]
num_authors = len(author_list)
if num_authors <= 5:
authors = ', '.join(author_list)
else:
authors = ', '.join(author_list[:3] + ['...'] + author_list[-2:])
if p.affiliations is not None:
affiliations = p.affiliations[:5]
affiliations = ', '.join(affiliations)
if len(p.affiliations) > 5:
affiliations += ', ...'
else:
affiliations = 'Unknown Affiliation'
parts.append(get_block_html(p.title, authors,rate,p.arxiv_id ,p.tldr, p.pdf_url, p.code_url, affiliations))
time.sleep(10)
content = '<br>' + '</br><br>'.join(parts) + '</br>'
return framework.replace('__CONTENT__', content)
def send_email(sender:str, receiver:str, password:str,smtp_server:str,smtp_port:int, html:str,):
def _format_addr(s):
name, addr = parseaddr(s)
return formataddr((Header(name, 'utf-8').encode(), addr))
def _split_receivers(receiver_str: str) -> List[str]:
"""
"a@example.com, b@example.com; c@example.com"
"""
if not receiver_str:
return []
# support , ; <space>
return [r.strip() for r in receiver_str.replace(';', ',').split(',') if r.strip()]
receivers = _split_receivers(receiver)
if not receivers:
logger.warning("No valid receiver email addresses provided.")
return
msg = MIMEText(html, 'html', 'utf-8')
msg['From'] = _format_addr(f'Github Action <{sender}>')
today = datetime.datetime.now().strftime('%Y/%m/%d')
msg['Subject'] = Header(f'Daily arXiv {today}', 'utf-8').encode()
msg['To'] = ', '.join(_format_addr(f'You <{r}>') for r in receivers)
# ---------- SMTP ----------
try:
if smtp_port == 465: # QQ、Outlook
server = smtplib.SMTP_SSL(smtp_server, smtp_port, timeout=15)
logger.debug("Using SMTP_SSL (port 465).")
else: # 587、25
server = smtplib.SMTP(smtp_server, smtp_port, timeout=15)
server.starttls()
logger.debug("Using SMTP + STARTTLS.")
except Exception as e:
logger.error(f"Failed to establish SMTP connection: {e}")
raise
# ---------- login & send ----------
try:
server.login(sender, password)
server.sendmail(sender, receivers, msg.as_string())
logger.info(f"Email sent successfully to: {', '.join(receivers)}")
except Exception as e:
logger.error(f"SMTP login/send failed: {e}")
raise
finally:
server.quit()