83 lines
4.7 KiB
Python
83 lines
4.7 KiB
Python
"""Per-recipient SMTP delivery; no global settings changes or automatic retries."""
|
|
import re
|
|
import smtplib
|
|
import ssl
|
|
from email.message import EmailMessage
|
|
from email.utils import formatdate
|
|
from uuid import UUID
|
|
|
|
from fastapi import HTTPException
|
|
|
|
|
|
def mailbox(value):
|
|
return (isinstance(value, str) and len(value) <= 254 and '..' not in value and '.@' not in value
|
|
and re.fullmatch(r'[A-Za-z0-9_+][A-Za-z0-9._%+\-]{0,63}@[A-Za-z0-9](?:[A-Za-z0-9.\-]*[A-Za-z0-9])?\.[A-Za-z]{2,63}', value))
|
|
|
|
|
|
def dispatch_email(payload: dict) -> dict:
|
|
host, port, security = payload.get('host'), payload.get('port'), payload.get('security')
|
|
username, password, sender = payload.get('username'), payload.get('password'), payload.get('sender')
|
|
operation = payload.get('operation')
|
|
if (not isinstance(host, str) or '..' in host or not re.fullmatch(r'[A-Za-z0-9](?:[A-Za-z0-9.\-]{0,251}[A-Za-z0-9])?', host)
|
|
or type(port) is not int or not 1 <= port <= 65535 or security not in {'ssl', 'starttls'}
|
|
or not isinstance(username, str) or not 1 <= len(username) <= 254 or re.search(r'[\x00-\x20\x7f]', username)
|
|
or not isinstance(password, str) or not 1 <= len(password) <= 512 or re.search(r'[\r\n\x00]', password)
|
|
or not mailbox(sender) or operation not in {'check', 'send'}):
|
|
raise HTTPException(400, '邮件服务器参数无效')
|
|
message = None
|
|
if operation == 'send':
|
|
target, subject, text = payload.get('receive_id'), payload.get('subject'), payload.get('text')
|
|
if (not mailbox(target) or not isinstance(subject, str) or not 1 <= len(subject) <= 300
|
|
or re.search(r'[\r\n\x00]', subject) or not isinstance(text, str) or not text.strip()
|
|
or len(text.encode('utf-8')) > 200000):
|
|
raise HTTPException(400, '邮件接收人或内容无效')
|
|
try:
|
|
request_id = str(UUID(payload.get('uuid', '')))
|
|
except (ValueError, TypeError, AttributeError):
|
|
raise HTTPException(400, '邮件请求编号无效') from None
|
|
message = EmailMessage()
|
|
message['From'], message['To'], message['Subject'] = sender, target, subject
|
|
message['Date'] = formatdate(localtime=False)
|
|
message['Message-ID'] = f'<{request_id}@{sender.split("@")[1]}>'
|
|
message.set_content(text, charset='utf-8')
|
|
|
|
client, sending = None, False
|
|
try:
|
|
context = ssl.create_default_context()
|
|
if security == 'ssl':
|
|
client = smtplib.SMTP_SSL(host, port, timeout=12, context=context)
|
|
else:
|
|
client = smtplib.SMTP(host, port, timeout=12)
|
|
client.ehlo()
|
|
client.starttls(context=context)
|
|
client.ehlo()
|
|
client.login(username, password)
|
|
if message is None:
|
|
return {'ok': True}
|
|
sending = True
|
|
refused = client.send_message(message, from_addr=sender, to_addrs=[target])
|
|
if refused:
|
|
return {'ok': False, 'status': 'failed', 'message': '邮件服务器拒收该地址,请核对接收邮箱。'}
|
|
# SMTP acceptance is not proof of final delivery or reading.
|
|
return {'ok': True, 'status': 'submitted', 'message_id': request_id}
|
|
except smtplib.SMTPAuthenticationError:
|
|
return {'ok': False, 'status': 'failed', 'message': '发件账号认证失败,请检查 SMTP 是否开启及邮箱授权码。'}
|
|
except ssl.SSLError:
|
|
return {'ok': False, 'status': 'unknown' if sending else 'failed', 'message': '邮件加密连接未完成,请检查服务器、端口和证书配置。'}
|
|
except (smtplib.SMTPRecipientsRefused, smtplib.SMTPSenderRefused, smtplib.SMTPDataError):
|
|
return {'ok': False, 'status': 'failed', 'message': '邮件服务器拒绝发送,请核对发件地址、接收地址及发送限制。'}
|
|
except smtplib.SMTPNotSupportedError:
|
|
return {'ok': False, 'status': 'failed', 'message': '邮件服务器不支持所选加密或认证方式,请检查 SMTP 配置。'}
|
|
except UnicodeError:
|
|
return {'ok': False, 'status': 'unknown' if sending else 'failed', 'message': '邮件账号或内容编码未被接受,请检查账号和授权码格式。'}
|
|
except (OSError, smtplib.SMTPException):
|
|
return {'ok': False, 'status': 'unknown' if sending else 'failed', 'message':
|
|
'邮件提交结果待确认,请先核对收件箱;本条邮件不会自动重发。' if sending else '邮件服务器连接失败,请检查地址、端口和网络。'}
|
|
finally:
|
|
if client is not None:
|
|
# A QUIT/close failure cannot negate an already accepted DATA response.
|
|
try:
|
|
client.close()
|
|
except OSError:
|
|
pass
|