I have the following script that is supposed to send an email; however, the email is being sent as a plain text rather than HTML. Am I missing a piece of code?
import smtplib, ssl, mimetypes
from email.message import EmailMessage
from email.utils import make_msgid
def send_email():
server = connect_server()
if server:
html = """\
<html>
<body>
<div style="width:60%;background-color:#193048;border:4px solid #3c71aa;padding:5px 10px">
Putting My Email Text Here!
</div>
</body>
</html>
"""
msg = EmailMessage()
msg["Subject"] = "Subject"
msg["From"] = "Support <[email protected]>"
msg["To"] = "{} <{}>".format("Test Human","<[email protected]>")
msg.set_content('Plain Text Here!')
msg_image = make_msgid(domain="example.xyz")
msg.add_alternative(html.format(msg_image=msg_image[1:-1],subtype="html"))
with open("./resources/email-logo.png","rb") as fp:
maintype,subtype = mimetypes.guess_type(fp.name)[0].split('/')
msg.get_payload()[1]add_related(fp.read(),maintype=maintype,subtype=subtype,cid=msg_image)
server.sendmail("Support <[email protected]","{} <{}>".format(Test Human,[email protected]),msg.as_string())
server.quit()
I am using Python3.9 on Ubuntu 18.04. Thanks All!
I usually use the smtplib
In addition to set your text as a simple text, you need to set the html content too!
import smtplib
from email.message import EmailMessage
html = """<!DOCTYPE html>
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Your HTML Title</title>
<body>
<h1>The best html email content!!!</h1>
</body>
</html>
"""
with smtplib.SMTP_SSL('smtp.gmail.com', 465) as smtp:
smtp.login('my_email', 'my_password')
try:
msg = EmailMessage()
msg.set_content('simple text would go here - This is a fallback for html content')
msg.add_alternative(html, subtype='html')
msg['Subject'] = 'Subject of your email would go here!'
msg['From'] = 'my_email'
msg['To'] = '[email protected]'
msg['Cc'] = ''
msg['Bcc'] = ''
smtp.send_message(msg)
except:
print("Something went wrong!!!")
print("DONE!")
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With