Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python email (with txt and html)

I'm trying to send and email with html and txt. But I need the contents of the .txt file into the email html body. And so far I can only get the txt file to work or the html, but not both. Any ideas?

import smtplib

from email.MIMEMultipart import MIMEMultipart
from email.MIMEText import MIMEText

sender = "[email protected]"
receiver = "[email protected]"

msg = MIMEMultipart('alternative')
msg['Subject'] = "update"
msg['From'] = sender
msg['To'] = receiver

f1 = (open("email_data.txt"))
text = MIMEText(f1.read(),'plain') 

html = """\
<html>
  <head></head>
  Header
  <body>
    <p>Something<br>
       Update<br>
       Need the contents of the text file to open here
    </p>
  </body>
</html>
"""


#part1 = MIMEText(text, 'plain')
part2 = MIMEText(html, 'html')

msg.attach(text)
msg.attach(part2)


server = smtplib.SMTP('smtp.gmail.com', 587)

server.starttls()
server.ehlo()
server.login("sender", "password")
server.sendmail(sender, receiver, msg.as_string())
print 'Email sent'
server.quit()
like image 985
Carol M Avatar asked Apr 25 '26 04:04

Carol M


1 Answers

Great case for yagmail.

import yagmail
yag = yagmail.SMTP('username','password')

html = '<h1>some header text</h1><p>{}</p>'.format(f1.read())

yag.send('[email protected]', 'subject', html)

Done.

Best to read the yagmail documentation at the link above to see what magic is actually happening.

like image 108
PascalVKooten Avatar answered Apr 28 '26 11:04

PascalVKooten



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!