Send an email – smtplib

Send a report via smtp mail server. Set up a routine report email using task scheduler in the server.

You may need to set .bat file to run the code if Task scheduler fails to run python code.

.bat file

@echo off
cls

python.exe "C:\send.py"

exit

.py file

from email.mime.multipart import MIMEMultipart
from email.mime.application import MIMEApplication
from email.mime.text import MIMEText
import smtplib

EMAIL_FROM = "your_email"
EMAIL_TO = "email you to send"
SMTP_SERVER = "mail server"
SMTP_PORT = "mail server port"

msg = MIMEMultipart()
msg['Subject'] = ''
msg['From'] = EMAIL_FROM
msg['To'] = EMAIL_TO
    
    # Add body to email
msg.attach(MIMEText('This is email body', 'plain'))
    
    # attach file
msg.attach(MIMEApplication(file.read(), Name = 'attachment.csv'))


smtp_obj = smtplib.SMTP(SMTP_SERVER, SMTP_PORT)
smtp_obj.sendmail(msg['From'], msg['To'], msg.as_string())
smtp_obj.quit()