Use Python to connect Database to export report file and send via Email

Tram Ho

During the working process, there are some requests to send daily, monthly and quarterly reports from Sales to System Operators.

Today I will write a tutorial on using Python to connect to the database to export the report file and send the report file via email. Here I use Mysql database, export file format is xls.

image.png

1. Prepare

  • Install mysql-connector library for mysql database connection: pip install mysql-connector-python
  • Install xlwt library for processing excel files: pip install xlwt
  • Install the smtplib library for emailing: pip install smtplib

2. Processing code

Create file report_python.py, file content as below.

Import library

Function to export xls file from MySQL database

Email sending function

Main function

3. Results I set crontab to run reports and send emails every day

image.png

In the following article, I will guide you to connect to Oracle Database.

 

Share the news now

Source : Viblo