Here's a simple example script:
import smtplibfrom email.mime.text import MIMETextfrom email.mime.multipart import MIMEMultipartimport scheduleimport timedef send_email(subject, body, to_email, smtp_server, smtp_port, smtp_username, smtp_password):# Create a MIME objectmsg = MIMEMultipart()msg['From'] = smtp_usernamemsg['To'] = to_emailmsg['Subject'] = subject# Attach the body of the emailmsg.attach(MIMEText(body, 'plain'))# Establish a connection to the SMTP serverwith smtplib.SMTP(smtp_server, smtp_port) as server:# Log in to the SMTP server if authentication is requiredserver.login(smtp_username, smtp_password)# Send the emailserver.sendmail(smtp_username, to_email, msg.as_string())def daily_report():# Customize these variables with your own valuessubject = "Daily Report"body = "This is your daily report email."to_email = "recipient@example.com"smtp_server = "smtp.example.com"smtp_port = 587 # Adjust the port according to your SMTP server configurationsmtp_username = "your_username"smtp_password = "your_password"# Send the emailsend_email(subject, body, to_email, smtp_server, smtp_port, smtp_username, smtp_password)# Schedule the job to run daily at a specific time (adjust as needed)schedule.every().day.at("08:00").do(daily_report)while True:# Run pending scheduled jobsschedule.run_pending()time.sleep(1)
Here's how you can set it up:
Install Required Libraries:
Make sure you have the smtplib, schedule, and email libraries installed. You can install them using:
pip install secure-smtplibpip install schedule
Configure Email and Schedule:
Replace the placeholder values in the daily_report function with your actual email content and SMTP server details.
Adjust the schedule in the schedule.every().day.at("08:00").do(daily_report) line to your desired daily sending time.
Run the Script:
Save the script with a .py extension (e.g., email_report_script.py) and run it using:
python email_report_script.py
The script will keep running and send the daily email at the specified time.
Note: Make sure to use an application-specific password or enable "less secure apps" in your Google account settings if you are using Gmail. Always be cautious about storing sensitive information like passwords in your code, and consider using environment variables or a configuration file for better security.

0 Comments