|
| 1 | +# Before class definition, ensure there are two blank lines |
1 | 2 | import smtplib
|
| 3 | +from email.mime.multipart import MIMEMultipart |
| 4 | +from email.mime.text import MIMEText |
2 | 5 |
|
3 |
| -def send_email(subject, body, to_email): |
4 |
| - sender_email = "your_email@example.com" |
5 |
| - sender_password = "your_password" |
6 | 6 |
|
7 |
| - message = f"Subject: {subject}\n\n{body}" |
| 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 |
8 | 13 |
|
9 |
| - server = smtplib.SMTP('smtp.gmail.com', 587) |
10 |
| - server.starttls() |
11 |
| - server.login(sender_email, sender_password) |
12 |
| - server.sendmail(sender_email, to_email, message) |
13 |
| - server.quit() |
| 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 |
14 | 21 |
|
15 |
| -send_email("Test Alert", "This is an automated email", "recipient@example.com") |
| 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, 'your_email@gmail.com', 'your_password') |
| 47 | + email_alert.send_email('Test Subject', 'This is a test email', ['recipient@example.com']) |
0 commit comments