简体   繁体   中英

how to copy the contents of an excel sheet and paste it in the body of an email.(Not as an attachment) using Python

I'm writing a python script to send email. Right now it is sending an excel file as an attachment, but instead I want to send the email with the body having the contents of the excel file. Like copying the contents of the excel file with color, formatting etc. and then pasting it in the body of an email.

import win32com.client
from openpyxl import load_workbook 
import pandas as pd 
o = win32com.client.Dispatch("Outlook.Application") 
Msg = o.CreateItem(0)

Msg.To = "abc@gmail.com"

Msg.CC = "xyz@gmail.com" 
Msg.BodyFormat = 2 
Msg.HTMLBody = """
<html>
<body>
   <p>Hello All,<br>
       <br>
       Test HTML mail body from Python
    </p>
  </body>
</html>"""
Msg.Subject = "Automation Test" 
attachment1 = "D:\Demo.xlsx" 
Msg.Attachments.Add(attachment1) 
Msg.Send()

This code is working fine but I could not figure out how to add the contents of the excel directly in to the body of an email.

You should be able to convert the excel file to an HTML table and then include it into your email message, something like this (won't work if you copy and paste because I haven't defined the convert_to_html() function):

wb = load_workbook(filename = 'D:\Demo.xlsx')
html_table = convert_to_html(wb)

Msg.HTMLBody = """
<html>
<body>
   <p>Hello All,<br>
       <br>
       Test HTML mail body from Python
    </p>""" + html_table + """
  </body>
</html>"""

Here 's some code of someone using python to convert an excel file to an HTML table. I haven't inspected it closely, but it seems like you should be able to use it to make a convert_to_html() function or otherwise adapt it for your purposes.

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