Hello all,
I’ve searched here and found no solutions yet. I am trying to embed a plotly graph in an email. All of my email shows up except the actual plot. Does anyone have a solution for this?
Here is my code as is:
def send_email(sender: str, recipient: List[str], subject: str, attachment1: Optional[str],
html_body: Optional[str]) -> None:
try:
message = MIMEMultipart('alternative')
message["From"] = sender
message['To'] = ", ".join(recipient)
message["Subject"] = subject
if html_body:
part1 = MIMEText(html_body, "html")
message.attach(part1)
if attachment1:
with open(attachment1, "rb") as attachment_file:
part2 = MIMEBase("application", "octet-stream")
part2.set_payload(attachment_file.read())
encoders.encode_base64(part2)
part2.add_header("Content-Disposition", f"attachment; filename= {os.path.basename(attachment1)}")
message.attach(part2)
msg = message.as_string()
with smtplib.SMTP(link, 25) as server:
server.sendmail(sender, recipient, msg)
except UnicodeEncodeError as u:
raise Exception(f'Could not encode Message Body\n{u}')
except Exception as e:
raise Exception(f'Something else went wrong sending the email.\n{e}')
graph_html = pio.to_html(fig=fig, full_html=False, include_plotlyjs=True)
html_text = f"""
<!doctype html>
<html class="no-js" lang="">
<head>
<meta charset="utf-8">
<title></title>
<meta name="description" content="">
<meta name="viewport" content="width=device-width, initial-scale=1">
</head>
<body>
<!-- Add your site or application content here -->
<p>
<span style='font-family: "Times New Roman", Times, serif; font-size: 16px;'>
Hello,
</span>
</p>
<p>
<span style='font-family: "Times New Roman", Times, serif; font-size: 16px;'>
A summary of the Water Chemistry Alarm data for the previous 90 days is below. Attached to this
email is a spreadsheet with more details.
</span>
</p>
<script src="js/vendor/modernizr-3.11.2.min.js"></script>
<script src="js/plugins.js"></script>
<script src="js/main.js"></script>
{graph_html}
<p>
<span style='font-family: "Times New Roman", Times, serif; font-size: 16px;'><br></span>
</p>
<p style='margin-right:0in;margin-left:0in;font-size:15px;font-family:"Calibri",sans-serif;margin:0in;'>
<span style='font-size: 16px; font-family: "Times New Roman", Times, serif; color: red; background: yellow;'>
This email was autonomously generated. Do not reply to this email, as this inbox is not monitored.
</span>
</p>
<p>
<span style='font-size: 16px; font-family: "Times New Roman", Times, serif;'>
Please report any bugs and send your feedback to
</span>
</p>
</body>
</html>
"""
send_email(sender=sender,
recipient=contact,
subject=f'Water Chemistry Alarms from Past 90 Days',
html_body=html_text,
attachment1=excel_file_path
)