简体   繁体   中英

Parse email message as HTML while sending email smtplib

I am sending bulk emails with the help of pandas library, There is a problem which I am facing, I want to parse the body text as HTML as there are some HTML tags which I want to use. Following is the code for the same.

    message = """\
Dear Student,
    Following are your login details,
            Email     {0}
            Password  {1}
    You may log in via URL mail.sample.com
    Do not copy/paste the password.

Regards,
Admin
        """.format(student_email,student_password)
    full_email = ("From: {0} <{1}>\n"
                  "To: {2}\n"
                  "Subject: {3}\n\n"
                  "{4}"
                  .format(self_name, self_email, email, subject, message))

I couldn't find any other code with having the same library which I am using currently and if possible I would like to use only these libraries ie pandas and smtplib .

Apologies if the redundant question

TL;DR I want to parse text to HTML while sending the email

The problem is if I append tags in message variable it will literally show tags instead of parsing. For ex:

 <b>Email : </b>sample@sample.com

You probably want to use the built-in email package, rather than constructing the email by hand. That will let you set the content-type to text/html :

from email.message import EmailMessage

msg = EmailMessage()
msg.set_content(html_message, subtype="html")
msg['Subject'] = subject
msg['From'] = '{0} <{1}>'.format(self_name, self.email)
msg['To'] = email

So after a couple of days of brainstorming, I hacked a way to do this, I had to use a couple of more libs. but that did that the job. Initially, I was not flexible to do so but had to.

Along with pandas and smtplib below are the libraries I have used.

from email.mime.text import MIMEText
from jinja2 import Environment

Here a tradeoff was done, I completely removed the full_email variable, instead of it, the following was done.

message = """\
<p>Dear Student,<p>
<span>Following are your login details,</span><br/><br/>
&nbsp;&nbsp;&nbsp;&nbsp;<b>Email</b>      {0} <br/>
&nbsp;&nbsp;&nbsp;&nbsp;<b>Password</b>  {1} </br><br/>
&nbsp;&nbsp;&nbsp;&nbsp;You may login via URL sample.mail.com<br/>
&nbsp;&nbsp;&nbsp;&nbsp;Do not copy/paste the password.<br/>
<br/><br/>

Regards,<br/>
        """.format(student_email,student_password)
    msg = MIMEText(
        Environment().from_string(message).render(
            title='Hello World!'
        ), "html"
    )
    msg['Subject'] = subject
    msg['From'] = from
    msg['To'] = email

and in order to send it.

server.sendmail(email,[email],msg.as_string())

Thanks to this answer, I was able to achieve it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM