|
| 1 | +import smtplib |
| 2 | +from email.mime.multipart import MIMEMultipart |
| 3 | +from email.mime.text import MIMEText |
| 4 | +from email.mime.base import MIMEBase |
| 5 | +from email import encoders |
| 6 | +import schedule |
| 7 | +import time |
| 8 | +from datetime import datetime |
| 9 | + |
| 10 | +def send_email(subject, body, to_emails, from_email, smtp_server, smtp_port, login, password, attachment_path=None): |
| 11 | + # Create a multipart message |
| 12 | + msg = MIMEMultipart() |
| 13 | + msg['From'] = from_email |
| 14 | + msg['To'] = ', '.join(to_emails) |
| 15 | + msg['Subject'] = subject |
| 16 | + |
| 17 | + # Attach the body with the msg instance |
| 18 | + msg.attach(MIMEText(body, 'plain')) |
| 19 | + |
| 20 | + # Attach any file if specified |
| 21 | + if attachment_path: |
| 22 | + attachment = open(attachment_path, "rb") |
| 23 | + part = MIMEBase('application', 'octet-stream') |
| 24 | + part.set_payload(attachment.read()) |
| 25 | + encoders.encode_base64(part) |
| 26 | + part.add_header('Content-Disposition', f"attachment; filename= {attachment_path}") |
| 27 | + msg.attach(part) |
| 28 | + |
| 29 | + # Create a secure SSL context and send the email |
| 30 | + with smtplib.SMTP_SSL(smtp_server, smtp_port) as server: |
| 31 | + server.login(login, password) |
| 32 | + text = msg.as_string() |
| 33 | + server.sendmail(from_email, to_emails, text) |
| 34 | + |
| 35 | +def daily_report(): |
| 36 | + # Define email parameters |
| 37 | + subject = "Daily Report - " + datetime.now().strftime("%Y-%m-%d") |
| 38 | + body = "Please find attached the daily report." |
| 39 | + |
| 40 | + |
| 41 | + smtp_server = "smtp.example.com" |
| 42 | + smtp_port = 465 |
| 43 | + |
| 44 | + password = "your-email-password" |
| 45 | + attachment_path = "path/to/your/report.csv" # Change this to the path of your report |
| 46 | + |
| 47 | + send_email(subject, body, to_emails, from_email, smtp_server, smtp_port, login, password, attachment_path) |
| 48 | + |
| 49 | +# Schedule the script to run daily at a specific time |
| 50 | +schedule.every().day.at("09:00").do(daily_report) # Change the time as needed |
| 51 | + |
| 52 | +if __name__ == "__main__": |
| 53 | + while True: |
| 54 | + schedule.run_pending() |
| 55 | + time.sleep(1) |
0 commit comments