-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmailer.py
More file actions
70 lines (61 loc) · 2.25 KB
/
mailer.py
File metadata and controls
70 lines (61 loc) · 2.25 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
import os
import ssl
import certifi
import aiosmtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from dotenv import load_dotenv
load_dotenv()
SMTP_SERVER = os.getenv("MAIL_SERVER")
_smtp_port = os.getenv("MAIL_PORT")
try:
SMTP_PORT = int(_smtp_port) if _smtp_port else 465
except ValueError:
SMTP_PORT = 465
SMTP_USER = os.getenv("MAIL_USERNAME")
SMTP_PASSWORD = os.getenv("MAIL_PASSWORD")
SMTP_SENDER = os.getenv("MAIL_DEFAULT_SENDER") or SMTP_USER
async def send_email(
to_email: list[str], subject: str, content: str, is_html: bool = False
) -> dict:
"""
异步发送邮件工具函数
:param to_email: 收件人邮箱列表
:param subject: 邮件主题
:param content: 邮件内容
:param is_html: 是否为HTML格式
:return: 发送结果字典
"""
if not all([SMTP_SERVER, SMTP_USER, SMTP_PASSWORD]):
print("Error: SMTP configuration missing")
return {"status": -1, "message": "SMTP config missing"}
if not to_email:
return {"status": -1, "message": "No recipients provided"}
# 构建邮件对象
message = MIMEMultipart()
message["From"] = SMTP_SENDER
message["To"] = ", ".join(
to_email
) # 邮件头中的To字段,展示给用户看,通常用逗号连接
message["Subject"] = subject
# 设置邮件正文
msg_type = "html" if is_html else "plain"
message.attach(MIMEText(content, msg_type, "utf-8"))
try:
# 创建 SSL 上下文,使用 certifi 提供的 CA 证书
context = ssl.create_default_context(cafile=certifi.where())
# 异步连接并发送
await aiosmtplib.send(
message,
recipients=to_email, # 显式指定收件人列表
hostname=SMTP_SERVER,
port=SMTP_PORT,
username=SMTP_USER,
password=SMTP_PASSWORD,
use_tls=True, # 如果端口是 465 通常需要 True,587 通常用 start_tls
tls_context=context, # 显式传入 SSL 上下文
)
return {"status": 200, "message": "Email sent successfully"}
except Exception as e:
print(f"Failed to send email: {str(e)}")
return {"status": -2, "message": f"Failed to send email: {str(e)}"}