Python : Sending html format email through SMTP

Viewed 1650

I have a code which sends the emails perfectly, but now I need to make some updates and send the email as html format. I tried researching, but they didn't worked for me. How can I change the format to html? For now I'm receiving this code as a string, not html.

    server = smtplib.SMTP('smtp.gmail.com', 587)
    server.ehlo()
    server.starttls()
    server.ehlo()
    server.login(f'{login_email}', f'{login_email_pass}')
    Subject = f'{program_name} : Launch verification'
    server.add_header('Content-Type','text/html')
    Body2 = """\
    <!DOCTYPE html>
    <html>
    <body>

    <h1 style="color:black;text-align:center;font-family:verdana">SERVER 51SV15J LAUNCH</h1>
    <p style="color:black;text-align:center;font-family:courier;font-size:120%">Code for confirmation is - <b>51256fd.</b></p>

    </body>
    </html>
"""
    Body = f'{service} just have been started.\nServer Details:\nServer IPV4 : {Ipv4_Address}\nServer IPV6 : {Ipv6_Address}\nServer Region : {Ip_region}\nServer Internet Providers : {Ip_org}\nServer SessionID : {SessionID}\n\n* To verify it, please enter the code : {Code}' 
    msg = f"Subject : {Subject}\n\n{Body2}"
    server.sendmail(
        f'{login_email}',
         f'{test_email}',
        msg
    )
1 Answers

I am not sure how to use it doing smtp.ehlo() but alternatively it can be done as under:-


import os
import smtplib
from email.message import EmailMessage #new

EMAIL = f'{login_email}
PASSWORD = f'{login_email_pass}'

message = EmailMessage()
message['Subject'] = f'{program_name} : Launch verification'
message['From'] = EMAIL
message['To'] = EMAIL
message.set_content('This email is sent using python.')
message.add_alternative("""\
<!DOCTYPE html>
    <html>
    <body>

    <h1 style="color:black;text-align:center;font-family:verdana">SERVER 51SV15J LAUNCH</h1>
    <p style="color:black;text-align:center;font-family:courier;font-size:120%">Code for confirmation is - <b>51256fd.</b></p>

    </body>
    </html>
""", subtype = 'html')

with smtplib.SMTP_SSL('smtp.gmail.com', 465) as smtp:
    smtp.login(EMAIL, PASSWORD)
    smtp.send_message(message)

I hope this well help. I haven't tried it but used the code from hereand edited it to meet your case.

Related