Send HTML file contents via python email script - python

Looking for a way to send the contents of a HTML file that is generated once a day using this script below. Running into road blocks getting it to work. I can sent HTML and see it, just not sure how to print out the contents of the file and send it.
File Format is export_MM-DD-YY.html
Id rather have it display the contents of the HTML in the email not the HTML file.
#!/usr/bin/env python3
import smtplib
import config
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
filename = 'name_of_file'
# Read a file and encode it into base64 format
fo = open(filename, "rb")
filecontent = fo.read()
encodedcontent = base64.b64encode(filecontent) # base64
filename = os.path.basename(filename)
# me == my email address
# you == recipient's email address
me = "From#example.com"
you = "TO#example.com"
subject = 'Test Subject v5'
# Create message container - the correct MIME type is multipart/alternative.
msg = MIMEMultipart('alternative')
msg['Subject'] = subject
msg['From'] = me
msg['To'] = you
# Create the body of the message (a plain-text and an HTML version).
text = "Hi!\nHow are you?\nHere is the link you wanted:\nhttps://www.python.org"
html = """\
**INSERT HTML FILE CONTENTS HERE...**
"""
# Record the MIME types of both parts - text/plain and text/html.
part1 = MIMEText(text, 'plain')
part2 = MIMEText(html, 'html')
# Attach parts into message container.
# According to RFC 2046, the last part of a multipart message, in this case
# the HTML message, is best and preferred.
msg.attach(part1)
msg.attach(part2)
# Send the message via local SMTP server.
server = smtplib.SMTP('smtp.gmail.com:587')
server.starttls()
server.login(config.EMAIL_ADDRESS, config.PASSWORD)
server.sendmail(me,you,msg.as_string())
server.quit()
So I think I got it working but im sure theres more code here than is needed (If anyone sees anything I can clean up?)
#!/usr/bin/env python3
import smtplib
import os
import config
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
raport_file = open('export.html','rb')
alert_msg = MIMEText(raport_file.read(),"html", "utf-8")
# me == my email address
# you == recipient's email address
me = "From#example.com"
you = "TO#example.com"
subject = 'Test Subject v5'
# Create message container - the correct MIME type is multipart/alternative.
msg = MIMEMultipart('alternative')
msg['Subject'] = subject
msg['From'] = me
msg['To'] = you
# Create the body of the message (a plain-text and an HTML version).
text = "Hi!\nHow are you?\nHere is the link you wanted:\nhttps://www.python.org"
html = """\
"""
# Record the MIME types of both parts - text/plain and text/html.
part1 = MIMEText(text, 'plain')
part2 = MIMEText(html, 'html')
# Attach parts into message container.
# According to RFC 2046, the last part of a multipart message, in this case
# the HTML message, is best and preferred.
msg.attach(part1)
msg.attach(part2)
# Send the message via local SMTP server.
server = smtplib.SMTP('smtp.gmail.com:587')
server.starttls()
server.login(config.EMAIL_ADDRESS, config.PASSWORD)
server.sendmail(me,you,alert_msg.as_string())
server.quit()

You're really close. Three changes:
Don't open the html file in binary mode. Read the file directly into the html string
report_file = open('export.html')
html = report_file.read()
remove the subsequent assignment to html var
html = """\
"""
send the msg object as constructed
server.sendmail(me, you, msg.as_string())
That worked for me. Also keep in mind that by default gmail settings may not allow your script to send mail. If so you'll need to update your settings to allow "insecure" (meaning non-Google) apps to send mail.

Related

Send email with plain text and html attachment

I'm trying to send email that contain both plain text in the body and html attachment. I've succeeded in adding the attachment but can't figure out how to add the plain text to the body. Any help is appreciated.
Here is the code:
from email.mime.multipart import MIMEMultipart
from email.mime.base import MIMEBase
from email.mime.text import MIMEText
import smtplib, ssl
from email import encoders
def sendmail():
subject = 'Subject here'
body = "Shard Count: 248" #Need to add this to body in plain text
senders_email = 'title#domain.com'
receiver_email = 'security#domain.com'
#Create a multipart message and set headers
message = MIMEMultipart('alternative')
message['From'] = senders_email
message['To'] = receiver_email
message['Subject'] = subject
message.attach(MIMEText(html_file, 'html'))
filename = 'logs.html'
# Open file in binary mode
with open(filename, 'rb') as attachment:
# Add file as application/octet-stream
part = MIMEBase('application','octet-stream')
part.set_payload(attachment.read())
# Encodes file in ASCII characters to send via email
encoders.encode_base64(part)
# Add header as key/value pair to attachment part
part.add_header(
'Content-Disposition',
f"attachment; filename= {filename}",
)
# Add attachment to message and convert message to string
message.attach(part)
text = message.as_string()
# Log into server using secure connection
context = ssl.create_default_context()
with smtplib.SMTP("smtp.domain.com", 25) as server:
# server.starttls(context=context)
# server.login(senders_email, password)
server.sendmail(senders_email,receiver_email,text)
print("Email sent!")
sendmail()
Your program looks fine for sending email with html body and an attachment. For sending plain text body, you will need to make a minor modification. I have tested your code with html body and plain text body. I am attaching both the versions of the code below.
The code with html body and an attachment is given below. I have tested this code at my end.
from email.mime.multipart import MIMEMultipart
from email.mime.base import MIMEBase
from email.mime.text import MIMEText
import smtplib, ssl
from email import encoders
html_body = '''
<html>
<body>
<h1>Sample email header</h1>
<p>Sample body</p>
</body>
</html>
'''
def sendmail():
subject = 'Subject here'
body = "Shard Count: 248" # Need to add this to body in plain text
senders_email = 'amal#example.com'
receiver_email = 'amalgjose#example.com'
# Create a multipart message and set headers
message = MIMEMultipart('alternative')
message['From'] = senders_email
message['To'] = receiver_email
message['Subject'] = subject
# The message body gets set here. Here we can add html body or text body.
# Syntax - message.attach(MIMEText(content, 'content-type'))
message.attach(MIMEText(html_body, 'html'))
# Name of the file to be attached
filename = 'attachment.pdf'
# Open file in binary mode
with open(filename, 'rb') as attachment:
# Add file as application/octet-stream
part = MIMEBase('application', 'octet-stream')
part.set_payload(attachment.read())
# Encodes file in ASCII characters to send via email
encoders.encode_base64(part)
# Add header as key/value pair to attachment part
part.add_header(
'Content-Disposition',
f"attachment; filename= {filename}",
)
# Add attachment to message and convert message to string
message.attach(part)
text = message.as_string()
# Log into server using secure connection
context = ssl.create_default_context()
with smtplib.SMTP("smtp.examplemail.com", 25) as server:
server.starttls(context=context)
server.login(senders_email, 'password')
server.sendmail(senders_email, receiver_email, text)
print("Email sent!")
sendmail()
If you want to send an email with plain text and an attachment, you just need a very minor change in the code. Make the following modification in the code.
text_body = "Hello, this is my text data in email"
message.attach(MIMEText(text_body))
The updated code which sends emails with plain text body and attachment is given below.
from email.mime.multipart import MIMEMultipart
from email.mime.base import MIMEBase
from email.mime.text import MIMEText
import smtplib, ssl
from email import encoders
text_body = '''
Hello, this is the sample text body. This program sends email with text body and an attachment.
I hope this helps
'''
def sendmail():
subject = 'Subject here'
body = "Shard Count: 248" # Need to add this to body in plain text
senders_email = 'amal#example.com'
receiver_email = 'amalgjose#example.com'
# Create a multipart message and set headers
message = MIMEMultipart('alternative')
message['From'] = senders_email
message['To'] = receiver_email
message['Subject'] = subject
# The message body gets set here. Here we can add html body or text body.
# Syntax - message.attach(MIMEText(content, 'content-type'))
message.attach(MIMEText(text_body))
# Name of the file to be attached
filename = 'attachment.pdf'
# Open file in binary mode
with open(filename, 'rb') as attachment:
# Add file as application/octet-stream
part = MIMEBase('application', 'octet-stream')
part.set_payload(attachment.read())
# Encodes file in ASCII characters to send via email
encoders.encode_base64(part)
# Add header as key/value pair to attachment part
part.add_header(
'Content-Disposition',
f"attachment; filename= {filename}",
)
# Add attachment to message and convert message to string
message.attach(part)
text = message.as_string()
# Log into server using secure connection
context = ssl.create_default_context()
with smtplib.SMTP("smtp.examplemail.com", 25) as server:
server.starttls(context=context)
server.login(senders_email, 'password')
server.sendmail(senders_email, receiver_email, text)
print("Email sent!")
sendmail()

Sending email with rich text and embedded image using Python

I am learning how to use Python for automating emails, and am facing issues in creating a "clean" email.
Problem: I have a Google doc which has a certain text, followed by an image, followed by some text. I wish to use this as the content of an email, which I wish to send using Python
Approach: Based on what I read on SO and blogs, I used MIMEMultipart and broke my original doc into 3 parts: text, image, text and I downloaded the html versions for both the text files. Thereafter, I used the following code:
import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from email.mime.image import MIMEImage
from string import Template
me = "myemail#gmail.com"
you = "youremail#gmail.com"
msg = MIMEMultipart()
msg['From'] = me
msg['To'] = you
msg['Subject'] = 'This is a test'
html1 = open('test_doc_part1.html')
part1 = MIMEText(html1.read(), 'html')
msg.attach(part1)
html1.close()
image_text = MIMEText('<img src="cid:image1">', 'html')
msg.attach(image_text)
fp = open('test_image.jpg', 'rb')
image = MIMEImage(fp.read())
fp.close()
image.add_header('Content-ID', '<image1>') # Define the image's ID as referenced in the HTML body above
msg.attach(image)
html2 = open('test_doc_part2.html')
part2 = MIMEText(html2.read(), 'html')
msg.attach(part2)
html2.close()
server = smtplib.SMTP('smtp.gmail.com', 587)
server.starttls()
server.login(me, "password")
text = msg.as_string()
# Do text substitutions here
server.sendmail(from_addr= me, to_addrs= you, msg=text)
server.quit()
Issue: Depending on the text sources, the text of my email is either hidden under the image, or all/some of it is underlined/garbled. I'm using gmail and viewing this email in Google Chrome. The original content of the received email can be viewed here. Can someone point out where I'm incorrect?

Use EMailMessage to to send email with embedded image and multipart text & html read from file

I want to send a multi-part email (text and html) using the Python 3 EMailMessage class, which also has an embedded image. I have been able to get it working when using the MIME classes, but not with the EMailMessage class. The HTML mail shows up but there is no embedded image, with it being added as an attachment instead. Example code is shown below (there are also lines commented out from my various attempts):
# Send an HTML email with an embedded image and a plain text message for
# email clients that don't want to display the HTML.
#Import smtplib for the actual sending function
import smtplib, ssl, mimetypes, imghdr
# Import the email modules we'll need
from email.message import EmailMessage
from email.headerregistry import Address
from email.mime.image import MIMEImage
from email.utils import make_msgid
STR_FROM_DISPLAY_NAME = "From Display Name"
TEXTFILE = "example.txt"
HTMLFILE = "example.html"
IMGFILE = "logo.png"
STR_FROM = "from#example.com"
STR_TO = "to#example.com"
STR_SUBJECT = f"The contents of {TEXTFILE}"
msg = EmailMessage()
msg["Subject"] = STR_SUBJECT
# STR_FROM == the sender's email address
# STR_TO == the recipient's email address
msg["From"] = STR_FROM
msg["To"] = STR_TO
msg.preamble = 'You will not see this in a MIME-aware mail reader.\n'
# Open the plain text file whose name is in TEXTFILE for reading.
with open(TEXTFILE) as fp:
# Create a text/plain message
msg.set_content(fp.read())
# Add the html version. This converts the message into a multipart/alternative
# container, with the original text message as the first part and the new html
# message as the second part.
image_cid = make_msgid()[1:-1] # strip <>
with open(HTMLFILE) as fp:
msg.add_alternative(fp.read(), subtype="html")
#.format(cid=cid), subtype="html")
#maintype, subtype = mimetypes.guess_type(IMGFILE)[0].split('/', 1)
# Now add the related image to the html part.
#attachments={"image1": IMGFILE}
#for png_cid in attachments:
from email.mime.image import MIMEImage
with open(IMGFILE, "rb") as fp:
image_type = imghdr.what(fp.name)
print("image_type = ", image_type)
msgImage = MIMEImage(fp.read())
# Define the image's ID as referenced above
msgImage.add_header("Content-ID", "<image_cid>")
msgImage.add_header('X-Attachment-Id', IMGFILE)
msgImage.add_header("Content-Disposition", f"inline; filename={IMGFILE}")
# msg.attach(msgImage)
# Make the EmailMessage's payload `mixed`
#msg.get_payload()[1].make_mixed() # getting the second part because it is the HTML alternative
#msg.get_payload()[1].attach(msgImage)
msg.get_payload()[1].add_related(msgImage, "image", image_type, fp.name, cid=image_cid) #.format(cid=cid))
# logo = MIMEImage(img.read())
# logo.add_header("Content-ID", f"cid")
# logo.add_header('X-Attachment-Id', IMGFILE)
# logo['Content-Disposition'] = f"inline; filename=" IMGFILE
# msg.attach(logo)
# Make the EmailMessage's payload `mixed`
# msg.get_payload()[1].make_mixed() # getting the second part because it is the HTML alternative
# msg.get_payload()[1].attach(logo)
port = 465 # For starttls
smtp_server = "smtp.mail.server.com"
password = "Password"
# Create secure connection with server and send email
context = ssl.create_default_context()
# Send the message via our own SMTP server.
with smtplib.SMTP_SSL(smtp_server, port, context=context) as server:
server.login(STR_FROM, password)
server.send_message(msg)
Below is the line from the HTML file where I specify the image:
<img class="image_fix" src="cid:{image_cid}" alt="Logo" title="Logo" width="637" height="213" />
There are lots of examples where the HTML is specified in the python code, but I haven't been able to find any where the HTML is loaded from a file where an image is embedded.
I also want to attach a word .docx file to the email, and I have sort of managed this with MIME classes, but the attachment did not show the size when viewed in the e-mail client. I used the line:
MIMEBase("application", "octet-stream").
with it encoded as base64. I think that there is a "word"/"docx" MIME type, but again not sure how to do it.
Any ideas ?

How to allow the user to choose HTML to be sent as an E-mail in python

Now I'm working in a project that going to allow the user to send HTML files an E-mails . The problem here is : I made a script that going to allow him to send the HTML files as an E-mail but the HTML file must be wirtten inside the code it self , here is the question : How can I let him to chose pre-made HTML to be sent instead of integrating it into the code , and here is my current code
import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
# me == my email address
# you == recipient's email address
me = "Sender mail"
you = "reciver mail"
# Create message container - the correct MIME type is multipart/alternative.
msg = MIMEMultipart('alternative')
msg['Subject'] = "HR report"
msg['From'] = me
msg['To'] = you
# Create the body of the message (a plain-text and an HTML version).
text = "Hi!\nHow are you?\nHere is the link you wanted:\nhttp://www.python.org"
html = """\
<html>
<head></head>
<body>
<p>Hi!<br>
How are you?<br>
Here is the link you wanted.
</p>
</body>
</html>
"""
# Record the MIME types of both parts - text/plain and text/html.
part1 = MIMEText(text, 'plain')
part2 = MIMEText(html, 'html')
# Attach parts into message container.
# According to RFC 2046, the last part of a multipart message, in this case
# the HTML message, is best and preferred.
msg.attach(part1)
msg.attach(part2)
# Send the message via local SMTP server.
mail = smtplib.SMTP('smtp.gmail.com', 587)
mail.ehlo()
mail.starttls()
mail.login(me, 'the Password ')
mail.sendmail(me, you, msg.as_string())
mail.quit()

embed HTML table in email via python [duplicate]

How to send HTML content in email using Python? I can send simple texts.
From Python v2.7.14 documentation - 18.1.11. email: Examples:
Here’s an example of how to create an HTML message with an alternative plain text version:
#! /usr/bin/python
import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
# me == my email address
# you == recipient's email address
me = "my#email.com"
you = "your#email.com"
# Create message container - the correct MIME type is multipart/alternative.
msg = MIMEMultipart('alternative')
msg['Subject'] = "Link"
msg['From'] = me
msg['To'] = you
# Create the body of the message (a plain-text and an HTML version).
text = "Hi!\nHow are you?\nHere is the link you wanted:\nhttp://www.python.org"
html = """\
<html>
<head></head>
<body>
<p>Hi!<br>
How are you?<br>
Here is the link you wanted.
</p>
</body>
</html>
"""
# Record the MIME types of both parts - text/plain and text/html.
part1 = MIMEText(text, 'plain')
part2 = MIMEText(html, 'html')
# Attach parts into message container.
# According to RFC 2046, the last part of a multipart message, in this case
# the HTML message, is best and preferred.
msg.attach(part1)
msg.attach(part2)
# Send the message via local SMTP server.
s = smtplib.SMTP('localhost')
# sendmail function takes 3 arguments: sender's address, recipient's address
# and message to send - here it is sent as one string.
s.sendmail(me, you, msg.as_string())
s.quit()
Here is a Gmail implementation of the accepted answer:
import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
# me == my email address
# you == recipient's email address
me = "my#email.com"
you = "your#email.com"
# Create message container - the correct MIME type is multipart/alternative.
msg = MIMEMultipart('alternative')
msg['Subject'] = "Link"
msg['From'] = me
msg['To'] = you
# Create the body of the message (a plain-text and an HTML version).
text = "Hi!\nHow are you?\nHere is the link you wanted:\nhttp://www.python.org"
html = """\
<html>
<head></head>
<body>
<p>Hi!<br>
How are you?<br>
Here is the link you wanted.
</p>
</body>
</html>
"""
# Record the MIME types of both parts - text/plain and text/html.
part1 = MIMEText(text, 'plain')
part2 = MIMEText(html, 'html')
# Attach parts into message container.
# According to RFC 2046, the last part of a multipart message, in this case
# the HTML message, is best and preferred.
msg.attach(part1)
msg.attach(part2)
# Send the message via local SMTP server.
mail = smtplib.SMTP('smtp.gmail.com', 587)
mail.ehlo()
mail.starttls()
mail.login('userName', 'password')
mail.sendmail(me, you, msg.as_string())
mail.quit()
You might try using my mailer module.
from mailer import Mailer
from mailer import Message
message = Message(From="me#example.com",
To="you#example.com")
message.Subject = "An HTML Email"
message.Html = """<p>Hi!<br>
How are you?<br>
Here is the link you wanted.</p>"""
sender = Mailer('smtp.example.com')
sender.send(message)
Here is a simple way to send an HTML email, just by specifying the Content-Type header as 'text/html':
import email.message
import smtplib
msg = email.message.Message()
msg['Subject'] = 'foo'
msg['From'] = 'sender#test.com'
msg['To'] = 'recipient#test.com'
msg.add_header('Content-Type','text/html')
msg.set_payload('Body of <b>message</b>')
# Send the message via local SMTP server.
s = smtplib.SMTP('localhost')
s.starttls()
s.login(email_login,
email_passwd)
s.sendmail(msg['From'], [msg['To']], msg.as_string())
s.quit()
for python3, improve #taltman 's answer:
use email.message.EmailMessage instead of email.message.Message to construct email.
use email.set_content func, assign subtype='html' argument. instead of low level func set_payload and add header manually.
use SMTP.send_message func instead of SMTP.sendmail func to send email.
use with block to auto close connection.
from email.message import EmailMessage
from smtplib import SMTP
# construct email
email = EmailMessage()
email['Subject'] = 'foo'
email['From'] = 'sender#test.com'
email['To'] = 'recipient#test.com'
email.set_content('<font color="red">red color text</font>', subtype='html')
# Send the message via local SMTP server.
with smtplib.SMTP('localhost') as s:
s.login('foo_user', 'bar_password')
s.send_message(email)
Here's sample code. This is inspired from code found on the Python Cookbook site (can't find the exact link)
def createhtmlmail (html, text, subject, fromEmail):
"""Create a mime-message that will render HTML in popular
MUAs, text in better ones"""
import MimeWriter
import mimetools
import cStringIO
out = cStringIO.StringIO() # output buffer for our message
htmlin = cStringIO.StringIO(html)
txtin = cStringIO.StringIO(text)
writer = MimeWriter.MimeWriter(out)
#
# set up some basic headers... we put subject here
# because smtplib.sendmail expects it to be in the
# message body
#
writer.addheader("From", fromEmail)
writer.addheader("Subject", subject)
writer.addheader("MIME-Version", "1.0")
#
# start the multipart section of the message
# multipart/alternative seems to work better
# on some MUAs than multipart/mixed
#
writer.startmultipartbody("alternative")
writer.flushheaders()
#
# the plain text section
#
subpart = writer.nextpart()
subpart.addheader("Content-Transfer-Encoding", "quoted-printable")
pout = subpart.startbody("text/plain", [("charset", 'us-ascii')])
mimetools.encode(txtin, pout, 'quoted-printable')
txtin.close()
#
# start the html subpart of the message
#
subpart = writer.nextpart()
subpart.addheader("Content-Transfer-Encoding", "quoted-printable")
#
# returns us a file-ish object we can write to
#
pout = subpart.startbody("text/html", [("charset", 'us-ascii')])
mimetools.encode(htmlin, pout, 'quoted-printable')
htmlin.close()
#
# Now that we're done, close our writer and
# return the message body
#
writer.lastpart()
msg = out.getvalue()
out.close()
print msg
return msg
if __name__=="__main__":
import smtplib
html = 'html version'
text = 'TEST VERSION'
subject = "BACKUP REPORT"
message = createhtmlmail(html, text, subject, 'From Host <sender#host.com>')
server = smtplib.SMTP("smtp_server_address","smtp_port")
server.login('username', 'password')
server.sendmail('sender#host.com', 'target#otherhost.com', message)
server.quit()
Actually, yagmail took a bit different approach.
It will by default send HTML, with automatic fallback for incapable email-readers. It is not the 17th century anymore.
Of course, it can be overridden, but here goes:
import yagmail
yag = yagmail.SMTP("me#example.com", "mypassword")
html_msg = """<p>Hi!<br>
How are you?<br>
Here is the link you wanted.</p>"""
yag.send("to#example.com", "the subject", html_msg)
For installation instructions and many more great features, have a look at the github.
Here's a working example to send plain text and HTML emails from Python using smtplib along with the CC and BCC options.
https://varunver.wordpress.com/2017/01/26/python-smtplib-send-plaintext-and-html-emails/
#!/usr/bin/env python
import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
def send_mail(params, type_):
email_subject = params['email_subject']
email_from = "from_email#domain.com"
email_to = params['email_to']
email_cc = params.get('email_cc')
email_bcc = params.get('email_bcc')
email_body = params['email_body']
msg = MIMEMultipart('alternative')
msg['To'] = email_to
msg['CC'] = email_cc
msg['Subject'] = email_subject
mt_html = MIMEText(email_body, type_)
msg.attach(mt_html)
server = smtplib.SMTP('YOUR_MAIL_SERVER.DOMAIN.COM')
server.set_debuglevel(1)
toaddrs = [email_to] + [email_cc] + [email_bcc]
server.sendmail(email_from, toaddrs, msg.as_string())
server.quit()
# Calling the mailer functions
params = {
'email_to': 'to_email#domain.com',
'email_cc': 'cc_email#domain.com',
'email_bcc': 'bcc_email#domain.com',
'email_subject': 'Test message from python library',
'email_body': '<h1>Hello World</h1>'
}
for t in ['plain', 'html']:
send_mail(params, t)
Here is my answer for AWS using boto3
subject = "Hello"
html = "<b>Hello Consumer</b>"
client = boto3.client('ses', region_name='us-east-1', aws_access_key_id="your_key",
aws_secret_access_key="your_secret")
client.send_email(
Source='ACME <do-not-reply#acme.com>',
Destination={'ToAddresses': [email]},
Message={
'Subject': {'Data': subject},
'Body': {
'Html': {'Data': html}
}
}
Simplest solution for sending email from Organizational account in Office 365:
from O365 import Message
html_template = """
<html>
<head>
<title></title>
</head>
<body>
{}
</body>
</html>
"""
final_html_data = html_template.format(df.to_html(index=False))
o365_auth = ('sender_username#company_email.com','Password')
m = Message(auth=o365_auth)
m.setRecipients('receiver_username#company_email.com')
m.setSubject('Weekly report')
m.setBodyHTML(final_html_data)
m.sendMessage()
here df is a dataframe converted to html Table, which is being injected to html_template
I may be late in providing an answer here, but the Question asked a way to send HTML emails. Using a dedicated module like "email" is okay, but we can achieve the same results without using any new module. It all boils down to the Gmail Protocol.
Below is my simple sample code for sending HTML mail only by using "smtplib" and nothing else.
```
import smtplib
FROM = "....#gmail.com"
TO = "another....#gmail.com"
SUBJECT= "Subject"
PWD = "thesecretkey"
TEXT="""
<h1>Hello</h1>
""" #Your Message (Even Supports HTML Directly)
message = f"Subject: {SUBJECT}\nFrom: {FROM}\nTo: {TO}\nContent-Type: text/html\n\n{TEXT}" #This is where the stuff happens
try:
server=smtplib.SMTP("smtp.gmail.com",587)
server.ehlo()
server.starttls()
server.login(FROM,PWD)
server.sendmail(FROM,TO,message)
server.close()
print("Successfully sent the mail.")
except Exception as e:
print("Failed to send the mail..", e)
```
In case you want something simpler:
from redmail import EmailSender
email = EmailSender(host="smtp.myhost.com", port=1)
email.send(
subject="Example email",
sender="me#example.com",
receivers=["you#example.com"],
html="<h1>Hi, this is HTML body</h1>"
)
Pip install Red Mail from PyPI:
pip install redmail
Red Mail has most likely all you need from sending emails and it has a lot of features including:
Attachments
Templating (with Jinja)
Embedded images
Prettified tables
Send as cc or bcc
Gmail preconfigured
Documentation: https://red-mail.readthedocs.io/en/latest/index.html
Source code: https://github.com/Miksus/red-mail

Categories

Resources