# email_service.py import smtplib from email.mime.multipart import MIMEMultipart from email.mime.text import MIMEText from email.mime.application import MIMEApplication import ssl class EmailService: def __init__(self, smtp_server, smtp_port, from_email, password): """ Initializes the EmailService with SMTP server details and sender's email credentials. :param smtp_server: SMTP server address :param smtp_port: SMTP server port :param from_email: Sender's email address :param password: Sender's email password """ self.smtp_server = smtp_server self.smtp_port = smtp_port self.from_email = from_email self.password = password def send_email(self, to_email, subject, body, html_body=None, attachments=None): """ Sends an email to the specified recipient with optional HTML body and attachments. :param to_email: Recipient's email address :param subject: Email subject :param body: Plain text email body :param html_body: HTML email body (optional) :param attachments: List of file paths to attach (optional) """ msg = MIMEMultipart() msg['From'] = self.from_email msg['To'] = to_email msg['Subject'] = subject msg.attach(MIMEText(body, 'plain')) if html_body: msg.attach(MIMEText(html_body, 'html')) if attachments: for attachment in attachments: try: with open(attachment, 'rb') as f: part = MIMEApplication(f.read(), Name=attachment.split('/')[-1]) part['Content-Disposition'] = f'attachment; filename="{attachment.split("/")[-1]}"' msg.attach(part) except Exception as e: print(f"Error attaching file {attachment}: {str(e)}") try: context = ssl.create_default_context() server = smtplib.SMTP(self.smtp_server, self.smtp_port) server.starttls(context=context) server.login(self.from_email, self.password) text = msg.as_string() server.sendmail(self.from_email, to_email, text) server.quit() print("Email sent successfully!") except Exception as e: print("Error sending email:", str(e)) # Example usage if __name__ == "__main__": email_service = EmailService( smtp_server="smtp.example.com", smtp_port=587, from_email="your_email@example.com", password="your_password" ) email_service.send_email( to_email="recipient@example.com", subject="Test Email with HTML and Attachments", body="This is a test email with plain text body.", html_body="

This is an HTML body

With some content.

", attachments=["/path/to/attachment1.pdf", "/path/to/attachment2.txt"] )