send HTML content in email using Python? I can send simple texts or i can send HTMl content, but not both at the same time. I used SMTP built in lib in Python
text ='Hi,\n Just for testing"
with open('samplefile.html') as fp: body = fp.read(
)
part1 = MIMEText(text,'plain') part2 = MIMEText(body,'html)
msg.attach(part1) msg.attach(part2)
Email is sent but only text file is showing in the content and html send as attachement file. If i remove part1 and only send HTMl file , then I am able to see in the email content.
But not able to see both text and HTML in the body content at once.
CodePudding user response:
Try below python code:
Note : I am reading all the arguments from email.ini file (username, Pswd, smtp server details..etc)
def email(self, formatting):
config = ConfigParser()
config.read("email.ini")
msg = MIMEMultipart()
msg['To'] = 'abc.test@gmail'
msg['Subject'] = 'INFO: HTML WITH TEXT'
if formatting == 1:
html =open("Table.htm","r")
msg.attach(MIMEText(html.read(), 'html'))
else:
body = MIMEText(body)
msg.attach(body)
part = MIMEBase('application', 'octet-stream')
server = smtplib.SMTP(config.get('smtp','host'))
server.starttls()
server.login(config.get('smtp','user'),config.get('smtp','password'))
text = msg.as_string()
server.sendmail(config.get('email','fromaddr'), msg["To"].split(",") ,text)
server.quit()
print("sending email to " config.get('email','toaddr'))
def main():
email = sendEmail()
email.email(1)
if __name__ == "__main__": main()
CodePudding user response:
You can use the smtplib library in Python to send emails with both HTML and plain text as the body. The MIMEMultipart class from the email library can be used to create a message with multiple parts, one for the HTML version and one for the plain text version. Here is an example of how you can send an email with both HTML and plain text using the smtplib and email libraries:
import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
# Create the message
msg = MIMEMultipart('alternative')
msg['Subject'] = 'Test Email'
msg['From'] = '[email protected]'
msg['To'] = '[email protected]'
# Create the plain text version
plain_text = 'This is the plain text version of the email.'
part1 = MIMEText(plain_text, 'plain')
msg.attach(part1)
# Create the HTML version
html_text = '<p>This is the <b>HTML</b> version of the email.</p>'
part2 = MIMEText(html_text, 'html')
msg.attach(part2)
# Send the email
s = smtplib.SMTP('smtp.example.com')
s.sendmail(msg['From'], msg['To'], msg.as_string())
s.quit()
Note that you need to replace the smtp.example.com with the actual address of your email server. Also, you need to set the credentials for the email account you want to use for sending the email.