Add main.py
This commit is contained in:
commit
eaab87febe
91
main.py
Normal file
91
main.py
Normal file
@ -0,0 +1,91 @@
|
||||
import mysql.connector
|
||||
from openpyxl import Workbook
|
||||
import smtplib
|
||||
from email.mime.multipart import MIMEMultipart
|
||||
from email.mime.base import MIMEBase
|
||||
from email.mime.text import MIMEText
|
||||
from email import encoders
|
||||
import os
|
||||
|
||||
|
||||
def perform_query(query, db_config):
|
||||
try:
|
||||
connection = mysql.connector.connect(**db_config)
|
||||
cursor = connection.cursor()
|
||||
cursor.execute(query)
|
||||
|
||||
results = cursor.fetchall()
|
||||
column_headers = [i[0] for i in cursor.description]
|
||||
return results, column_headers
|
||||
|
||||
except mysql.connector.Error as e:
|
||||
print(f"Error: {e}")
|
||||
finally:
|
||||
if connection.is_connected():
|
||||
cursor.close()
|
||||
connection.close()
|
||||
|
||||
|
||||
def write_to_excel(data, headers, file_name):
|
||||
workbook = Workbook()
|
||||
sheet = workbook.active
|
||||
sheet.append(headers)
|
||||
|
||||
for row in data:
|
||||
sheet.append(row)
|
||||
|
||||
workbook.save(file_name)
|
||||
print(f"Excel file saved as {file_name}")
|
||||
|
||||
|
||||
def send_email(subject, body, recipient_email, sender_email, sender_password, file_path):
|
||||
try:
|
||||
msg = MIMEMultipart()
|
||||
msg['From'] = sender_email
|
||||
msg['To'] = recipient_email
|
||||
msg['Subject'] = subject
|
||||
|
||||
msg.attach(MIMEText(body, 'plain'))
|
||||
|
||||
with open(file_path, 'rb') as attachment:
|
||||
part = MIMEBase('application', 'octet-stream')
|
||||
part.set_payload(attachment.read())
|
||||
encoders.encode_base64(part)
|
||||
part.add_header(
|
||||
'Content-Disposition',
|
||||
f'attachment; filename={os.path.basename(file_path)}'
|
||||
)
|
||||
msg.attach(part)
|
||||
|
||||
with smtplib.SMTP('smtp.eu.mailgun.org', 587) as server:
|
||||
server.starttls()
|
||||
server.login(smtp_user, smtp_password)
|
||||
server.send_message(msg)
|
||||
print("Email sent!")
|
||||
|
||||
except Exception as e:
|
||||
print(f"Error: {e}")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
db_config = {
|
||||
'host': '192.168.145.196',
|
||||
'user': 'sql_to_xlsx',
|
||||
'password': '2Uce5Uc5',
|
||||
'database': 'smsgw_control'
|
||||
}
|
||||
|
||||
sql_query = "SELECT mcc AS MCC, mnc AS MNC, route, price FROM smsgw_control.routingprices WHERE route = 'M1' AND clientid = '13283';"
|
||||
|
||||
results, headers = perform_query(sql_query, db_config)
|
||||
|
||||
excel_file_name = "pricelist.xlsx"
|
||||
write_to_excel(results, headers, excel_file_name)
|
||||
|
||||
email_subject = "Your subject"
|
||||
email_body = "Please find attached bla bla"
|
||||
recipient = "mark@42tele.com"
|
||||
sender = "zobbi@sender.com"
|
||||
|
||||
send_email(email_subject, email_body, recipient, sender, excel_file_name)
|
||||
|
||||
Loading…
Reference in New Issue
Block a user