Python Email sending HTML as plain text

Viewed 2582

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 <support@example.xyz>"
       msg["To"] = "{} <{}>".format("Test Human","<test.human@somewhere.xyz>")                
       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 <support@example.xyz","{} <{}>".format(Test Human,test.human@somewhere.xyz),msg.as_string())
       server.quit()

I am using Python3.9 on Ubuntu 18.04. Thanks All!

2 Answers

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'] = 'my_contact@mail.com'
        msg['Cc'] = ''
        msg['Bcc'] = ''
        smtp.send_message(msg)
     except:
        print("Something went wrong!!!")
print("DONE!")

From Real Python

from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText

# Create the plain-text and HTML version of your message
text = """\
Hi,
How are you?
Real Python has many great tutorials:
www.realpython.com"""
html = """\
<html>
  <body>
    <p>Hi,<br>
       How are you?<br>
       <a href="http://www.realpython.com">Real Python</a> 
       has many great tutorials.
    </p>
  </body>
</html>
"""

# Turn these into plain/html MIMEText objects
part1 = MIMEText(text, "plain")
part2 = MIMEText(html, "html")

# Add HTML/plain-text parts to MIMEMultipart message
# The email client will try to render the last part first
message.attach(part1)
message.attach(part2)

Looks like you can to use the MIMEText function with the html args. If you are able to import those libraries

Related