Files
syncio/app/email_sender.py
2026-04-16 17:57:58 +09:00

57 lines
2.3 KiB
Python
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

import os
import smtplib
from email.mime.application import MIMEApplication
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from typing import List
from .config import Config
class EmailSender:
"""Класс для отправки email уведомлений"""
def __init__(self, config: Config):
self.config = config
def send_email(self, subject: str, body: str, attachments: List[str] = None):
"""Отправка email с вложениями"""
if not all([self.config.EMAIL_HOST, self.config.EMAIL_USER,
self.config.EMAIL_PASSWORD, self.config.EMAIL_FROM]):
print("Настройки email не заполнены. Отправка email пропущена.")
return False
try:
# Создаем сообщение
msg = MIMEMultipart()
msg['From'] = self.config.EMAIL_FROM
msg['To'] = ', '.join(self.config.EMAIL_TO)
msg['Subject'] = subject
# Добавляем текст сообщения
msg.attach(MIMEText(body, 'plain', 'utf-8'))
# Добавляем вложения
if attachments:
for attachment_path in attachments:
if os.path.exists(attachment_path):
with open(attachment_path, 'rb') as f:
part = MIMEApplication(f.read(), Name=os.path.basename(attachment_path))
part['Content-Disposition'] = f'attachment; filename="{os.path.basename(attachment_path)}"'
msg.attach(part)
# Подключаемся к SMTP серверу
with smtplib.SMTP_SSL(self.config.EMAIL_HOST, self.config.EMAIL_PORT) as server:
server.login(self.config.EMAIL_USER, self.config.EMAIL_PASSWORD)
server.send_message(msg)
print(f"Email успешно отправлен на {', '.join(self.config.EMAIL_TO)}")
return True
except Exception as e:
print(f"Ошибка при отправке email: {e}")
return False
# ============================================================================