|
| 1 | +# Before class definition, ensure there are two blank lines |
| 2 | +import smtplib |
| 3 | +from email.mime.multipart import MIMEMultipart |
| 4 | +from email.mime.text import MIMEText |
| 5 | + |
| 6 | + |
| 7 | +class EmailAlert: |
| 8 | + def __init__(self, smtp_server, smtp_port, email_user, email_password): |
| 9 | + self.smtp_server = smtp_server |
| 10 | + self.smtp_port = smtp_port |
| 11 | + self.email_user = email_user |
| 12 | + self.email_password = email_password |
| 13 | + |
| 14 | + def send_email(self, subject, body, recipients): |
| 15 | + try: |
| 16 | + # Create the email message |
| 17 | + msg = MIMEMultipart() |
| 18 | + msg['From'] = self.email_user |
| 19 | + msg['To'] = ", ".join(recipients) |
| 20 | + msg['Subject'] = subject |
| 21 | + |
| 22 | + msg.attach(MIMEText(body, 'plain')) |
| 23 | + |
| 24 | + # Set up the server |
| 25 | + server = smtplib.SMTP(self.smtp_server, self.smtp_port) |
| 26 | + server.starttls() |
| 27 | + |
| 28 | + # Login to the email server |
| 29 | + server.login(self.email_user, self.email_password) |
| 30 | + |
| 31 | + # Send the email |
| 32 | + server.sendmail(self.email_user, recipients, msg.as_string()) |
| 33 | + |
| 34 | + # Log success |
| 35 | + print(f"Email sent successfully to {recipients}") |
| 36 | + |
| 37 | + except Exception as e: |
| 38 | + # Log failure |
| 39 | + print(f"Failed to send email. Error: {str(e)}") |
| 40 | + finally: |
| 41 | + server.quit() |
| 42 | + |
| 43 | + |
| 44 | +# After the class definition, ensure two blank lines |
| 45 | +if __name__ == "__main__": |
| 46 | + email_alert = EmailAlert( 'smtp.gmail.com', 587, '[email protected]', 'your_password') |
| 47 | + email_alert. send_email( 'Test Subject', 'This is a test email', [ '[email protected]']) |
0 commit comments