简体   繁体   中英

How to change actual location to temporary, add headers and remove space in csv file on Python Email table from MySQL?

I have a python code that run a MySQL query and send a email with csv attachment. I need to make following three changes. Can anybody please help me with this?

  • I need to change the actual location to a temporary location (I tired, it gaves me an error then I chnage it to the real location)
  • I have no headers on my result csv file. How do I add header on result csv?
  • It puts a empty raw between each raw, how do I remove that too.

Code -

from email.mime.text import MIMEText
from email.mime.image import MIMEImage
from email.mime.base import MIMEBase
import mysql.connector
import csv


my_db = mysql.connector.connect(
    host="localhost",
    user="root",
    passwd="admin",
    database="simplymacstaging"
)

my_cursor = my_db.cursor()

my_cursor.execute("SELECT CONVERT(DateCreated, Date) 'Date', StoreName, ROUND(sum(TotalCost), 2) 'TotalCost' "
                  "FROM simplymacstaging.ajdustmenthistory  WHERE ReasonCode = 'Negligence - Service' AND  "
                  "CONVERT(DateCreated, Date) >= '2019-02-03' GROUP by StoreName, Date")


databases = my_cursor.fetchall()
fp = open('C:\#Emailproject/emailtest.csv', 'w')
attach_file = csv.writer(fp)
attach_file.writerows(databases)
fp.close()

# My email
fromaddr = "******************@gmail.com"
# EMAIL ADDRESS YOU SEND TO
toaddr = "**********@gmail.com"

msg = MIMEMultipart()

msg['From'] = fromaddr
msg['To'] = toaddr
msg['Subject'] = "Test Email Data"  # SUBJECT OF THE EMAIL

body = "Hello, Please see the attched report for  week. Thank you, ****"

msg.attach(MIMEText(body, 'plain'))

filename = "Test Email.csv"  # NAME OF THE FILE WITH ITS EXTENSION
attachment = open("C:\#Emailproject/emailtest.csv", "rb")  # PATH OF THE FILE

part = MIMEBase('application', 'octet-stream')
part.set_payload((attachment).read())
encoders.encode_base64(part)
part.add_header('Content-Disposition', "attachment; filename= %s" % filename)

msg.attach(part)

server = smtplib.SMTP('smtp.gmail.com', 587)
server.starttls()
server.login(fromaddr, "***********")  # YOUR PASSWORD
text = msg.as_string()
server.sendmail(fromaddr, toaddr, text)
server.quit()

sample result image -

在此输入图像描述

Thank you so much

to avoid the empty rows try this


fp = open('C:\#Emailproject/emailtest.csv', 'w', newline='')


to add the header row

attach_file.writerow(["date", "address", "col3"])
attach_file.writerows(databases)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM