first commit
This commit is contained in:
56
app/email_sender.py
Normal file
56
app/email_sender.py
Normal file
@@ -0,0 +1,56 @@
|
||||
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
|
||||
|
||||
|
||||
# ============================================================================
|
||||
Reference in New Issue
Block a user