OiO.lk Community platform!

Oio.lk is an excellent forum for developers, providing a wide range of resources, discussions, and support for those in the developer community. Join oio.lk today to connect with like-minded professionals, share insights, and stay updated on the latest trends and technologies in the development field.
  You need to log in or register to access the solved answers to this problem.
  • You have reached the maximum number of guest views allowed
  • Please register below to remove this limitation

Gmail shows Message clipped even after View Entire Message

  • Thread starter Thread starter HMS
  • Start date Start date
H

HMS

Guest
I am using smtplib to send a few automated reports over python. I am using MIMEText to attach the HTML format of those reports, but the isssue is, if the reports gets too long, Gmail as usual displays the "View Entire Message" link to display the full reports, however my message gets clipped even after clicking the View Entire Message link (opens the clipped report in the new window), it displays the same amount of report/data and adds "[Message clipped]" note at the bottom of the report in the new window too.

Kindly help me with what can be the walkaround for this problem.

Here is the code that I am using to get the custom html format:

Code:
import pandas as pd
import re
from bs4 import BeautifulSoup

class GenerateHTMLReport:
    def __init__(self, debug_logger):
        self.debug_logger = debug_logger

    def get_styled_html(self, origin_df, source_df, course_df, state_df, city_df):
        origin_html = origin_df.to_html(index=False)
        source_html = source_df.to_html(index=False)
        course_html   = course_df.to_html(index=False)
        state_html   = state_df.to_html(index=False)
        city_html   = city_df.to_html(index=False)

        soup_origin = BeautifulSoup(origin_html, 'html.parser')
        soup_source = BeautifulSoup(source_html, 'html.parser')
        soup_course = BeautifulSoup(course_html, 'html.parser')
        soup_state = BeautifulSoup(state_html, 'html.parser')
        soup_city = BeautifulSoup(city_html, 'html.parser')

        for table in soup_origin.find_all('table') + soup_source.find_all('table') + soup_course.find_all('table') + soup_state.find_all('table') + soup_city.find_all('table'):
            table['style'] = "border:1px solid black;border-collapse:collapse"

        for th in soup_origin.find_all('th') + soup_source.find_all('th') + soup_course.find_all('th') + soup_state.find_all('th') + soup_city.find_all('th'):
            th['style'] = "border:1px solid black;border-collapse:collapse;padding:2px;background-color:yellow;text-align:center"
            th['bgcolor'] = "yellow"
            th['align'] = "center"

        for table in soup_origin.find_all('table') + soup_source.find_all('table') + soup_course.find_all('table') + soup_state.find_all('table') + soup_city.find_all('table'):
            rows = table.find_all('tr')
            for row in rows:
                cells = row.find_all('td')
                if any(cell.text.strip() == 'Grand Total' for cell in cells):
                    for cell in cells:
                        cell['style'] = "border:1px solid black;border-collapse:collapse;padding:2px;background-color:#d7e4fb;text-align:center"
                        cell['bgcolor'] = "#d7e4fb"
                        cell['align'] = "center"
                else:
                    for cell in cells:
                        cell['style'] = "border:1px solid black;border-collapse:collapse;padding:2px;background-color:white;text-align:center"
                        cell['bgcolor'] = "white"
                        cell['align'] = "center"

        leave_line = """<div><br></div>"""
        full_html = str(soup_origin) + leave_line + str(soup_source) + leave_line + str(soup_course) + leave_line + str(soup_state) + leave_line + str(soup_city)
        return full_html

And here is what I am using to send the emails:

Code:
import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.application import MIMEApplication
from email.mime.text import MIMEText
import yaml
from pandas.io.formats.style import Styler
import pandas as pd
from reports_tohtml import GenerateHTMLReport

class Emailer:

    def __init__(self, debug_logger) -> None:
        self.debug_logger = debug_logger
        self.html_rep = GenerateHTMLReport(self.debug_logger)
        
    def sorting_emailer(self, originwise_report, sourcewise_report, coursewise_report, statewise_report, citywise_report ,college_name, college_id, end_date, subject_college_name, subject_college_id) -> None:

        try:
            self.originwise_report = originwise_report
            self.sourcewise_report = sourcewise_report
            self.coursewise_report = coursewise_report
            self.statewise_report = statewise_report
            self.citywise_report = citywise_report
            
            # print(f" self.originwise_report ==> \n{self.originwise_report}")
            # print(f"self.sourcewise_report ==> \n{self.sourcewise_report}")

            self.college_name = college_name
            self.college_id = college_id
            self.end_date = end_date
            self.subject_college_name = subject_college_name
            self.subject_college_id = subject_college_id
            # self.subject = f'({college_id}) | {college_name} | NPF Daily Leads Report'
            self.subject = f'({self.subject_college_id}) | {self.subject_college_name} | NPF Daily Leads Report'

            self.body = f'Hi, PFA the {self.college_name} Daily Report till {self.end_date}.'

        except Exception as e:
            self.debug_logger.error(f'Error in sorting_data_emailer: {e}')

    def emailer(self, sender_email, receiver_email, athentication_file):        
        
        # with open('/home/npf_daily_report/pwd.yml', 'r') as file: #for hari sharma email
        # with open('/home/npf_daily_report/pwd_ops.yml', 'r') as file: #for central operations email
        with open(athentication_file, 'r') as file:

            content = file.read()

        creds = yaml.load(content, yaml.FullLoader)
        user = creds['user']
        password = creds['password']

        smtp_server = 'smtp.gmail.com'
        smtp_port = 587
        smtp_username = user
        smtp_password = password

        # Create a multipart message object
        msg = MIMEMultipart()

        # Set email headers
        msg['From'] = sender_email
        msg['To'] = receiver_email
        msg['Subject'] = self.subject
        receiver_emails_li = [email.strip() for email  in receiver_email.split(',')]

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

        html = self.html_rep.get_styled_html(self.originwise_report, self.sourcewise_report, self.coursewise_report, self.statewise_report, self.citywise_report)
        msg.attach(MIMEText(html, 'html'))

        # Attach the CSV file
        # attachment = MIMEApplication(file.read(), _subtype="csv")
        # attachment.add_header('Content-Disposition', 'attachment', filename='Ganga Group of Institutions.csv')
        # msg.attach(attachment)

        try:
            #Connect to the SMTP server
            server = smtplib.SMTP(smtp_server, smtp_port)
            server.starttls()
            
            #Log in to your email account
            server.login(smtp_username, smtp_password)
            
            #Send the email
            server.sendmail(sender_email, receiver_emails_li, msg.as_string())
            
            #Close the SMTP server connection
            server.quit()
            
            print('Email sent successfully.')
        except Exception as e:
            print('Email Error: ', str(e))
<p>I am using <code>smtplib</code> to send a few automated reports over python. I am using <code>MIMEText</code> to attach the HTML format of those reports, but the isssue is, if the reports gets too long, Gmail as usual displays the "<em>View Entire Message</em>" link to display the full reports, however my message gets clipped even after clicking the <em>View Entire Message</em> link (opens the clipped report in the new window), it displays the same amount of report/data and adds "<em>[Message clipped]</em>" note at the bottom of the report in the new window too.</p>
<p>Kindly help me with what can be the walkaround for this problem.</p>
<p>Here is the code that I am using to get the custom html format:</p>
<pre><code>import pandas as pd
import re
from bs4 import BeautifulSoup

class GenerateHTMLReport:
def __init__(self, debug_logger):
self.debug_logger = debug_logger

def get_styled_html(self, origin_df, source_df, course_df, state_df, city_df):
origin_html = origin_df.to_html(index=False)
source_html = source_df.to_html(index=False)
course_html = course_df.to_html(index=False)
state_html = state_df.to_html(index=False)
city_html = city_df.to_html(index=False)

soup_origin = BeautifulSoup(origin_html, 'html.parser')
soup_source = BeautifulSoup(source_html, 'html.parser')
soup_course = BeautifulSoup(course_html, 'html.parser')
soup_state = BeautifulSoup(state_html, 'html.parser')
soup_city = BeautifulSoup(city_html, 'html.parser')

for table in soup_origin.find_all('table') + soup_source.find_all('table') + soup_course.find_all('table') + soup_state.find_all('table') + soup_city.find_all('table'):
table['style'] = "border:1px solid black;border-collapse:collapse"

for th in soup_origin.find_all('th') + soup_source.find_all('th') + soup_course.find_all('th') + soup_state.find_all('th') + soup_city.find_all('th'):
th['style'] = "border:1px solid black;border-collapse:collapse;padding:2px;background-color:yellow;text-align:center"
th['bgcolor'] = "yellow"
th['align'] = "center"

for table in soup_origin.find_all('table') + soup_source.find_all('table') + soup_course.find_all('table') + soup_state.find_all('table') + soup_city.find_all('table'):
rows = table.find_all('tr')
for row in rows:
cells = row.find_all('td')
if any(cell.text.strip() == 'Grand Total' for cell in cells):
for cell in cells:
cell['style'] = "border:1px solid black;border-collapse:collapse;padding:2px;background-color:#d7e4fb;text-align:center"
cell['bgcolor'] = "#d7e4fb"
cell['align'] = "center"
else:
for cell in cells:
cell['style'] = "border:1px solid black;border-collapse:collapse;padding:2px;background-color:white;text-align:center"
cell['bgcolor'] = "white"
cell['align'] = "center"

leave_line = """<div><br></div>"""
full_html = str(soup_origin) + leave_line + str(soup_source) + leave_line + str(soup_course) + leave_line + str(soup_state) + leave_line + str(soup_city)
return full_html
</code></pre>
<p>And here is what I am using to send the emails:</p>
<pre><code>import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.application import MIMEApplication
from email.mime.text import MIMEText
import yaml
from pandas.io.formats.style import Styler
import pandas as pd
from reports_tohtml import GenerateHTMLReport

class Emailer:

def __init__(self, debug_logger) -> None:
self.debug_logger = debug_logger
self.html_rep = GenerateHTMLReport(self.debug_logger)

def sorting_emailer(self, originwise_report, sourcewise_report, coursewise_report, statewise_report, citywise_report ,college_name, college_id, end_date, subject_college_name, subject_college_id) -> None:

try:
self.originwise_report = originwise_report
self.sourcewise_report = sourcewise_report
self.coursewise_report = coursewise_report
self.statewise_report = statewise_report
self.citywise_report = citywise_report

# print(f" self.originwise_report ==> \n{self.originwise_report}")
# print(f"self.sourcewise_report ==> \n{self.sourcewise_report}")

self.college_name = college_name
self.college_id = college_id
self.end_date = end_date
self.subject_college_name = subject_college_name
self.subject_college_id = subject_college_id
# self.subject = f'({college_id}) | {college_name} | NPF Daily Leads Report'
self.subject = f'({self.subject_college_id}) | {self.subject_college_name} | NPF Daily Leads Report'

self.body = f'Hi, PFA the {self.college_name} Daily Report till {self.end_date}.'

except Exception as e:
self.debug_logger.error(f'Error in sorting_data_emailer: {e}')

def emailer(self, sender_email, receiver_email, athentication_file):

# with open('/home/npf_daily_report/pwd.yml', 'r') as file: #for hari sharma email
# with open('/home/npf_daily_report/pwd_ops.yml', 'r') as file: #for central operations email
with open(athentication_file, 'r') as file:

content = file.read()

creds = yaml.load(content, yaml.FullLoader)
user = creds['user']
password = creds['password']

smtp_server = 'smtp.gmail.com'
smtp_port = 587
smtp_username = user
smtp_password = password

# Create a multipart message object
msg = MIMEMultipart()

# Set email headers
msg['From'] = sender_email
msg['To'] = receiver_email
msg['Subject'] = self.subject
receiver_emails_li = [email.strip() for email in receiver_email.split(',')]

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

html = self.html_rep.get_styled_html(self.originwise_report, self.sourcewise_report, self.coursewise_report, self.statewise_report, self.citywise_report)
msg.attach(MIMEText(html, 'html'))

# Attach the CSV file
# attachment = MIMEApplication(file.read(), _subtype="csv")
# attachment.add_header('Content-Disposition', 'attachment', filename='Ganga Group of Institutions.csv')
# msg.attach(attachment)

try:
#Connect to the SMTP server
server = smtplib.SMTP(smtp_server, smtp_port)
server.starttls()

#Log in to your email account
server.login(smtp_username, smtp_password)

#Send the email
server.sendmail(sender_email, receiver_emails_li, msg.as_string())

#Close the SMTP server connection
server.quit()

print('Email sent successfully.')
except Exception as e:
print('Email Error: ', str(e))
</code></pre>
 

Latest posts

S
Replies
0
Views
1
Safwan Aipuram
S
Top