3

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 = "sender@gmail.com"
receiver = "receiver@gmail.com"

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()
Martin Tournoij
  • 26,737
  • 24
  • 105
  • 146
Carol M
  • 141
  • 1
  • 3
  • 12

2 Answers2

2

Great case for yagmail.

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

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

yag.send('toaddr@gmail.com', 'subject', html)

Done.

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

PascalVKooten
  • 20,643
  • 17
  • 103
  • 160
0

I think you're looking for string formatting, the most basic use case is

"""the text i want to insert is the following {} """.format(text)
maxymoo
  • 35,286
  • 11
  • 92
  • 119
  • The text I want to insert is a big file that changes every time I run the script that has the email as the final output, so I'll always have different text in there. – Carol M Feb 10 '16 at 23:25