Search code examples
pythonsmtplib

Displaying contents of list in body of email with Python and smtplib


I would like to loop through a list and display each item on a separate line in my email.

The code works fine if I set body = "Just a string"

mylist = [first line,second line,third line,fourth line]

fromaddr = "EMAIL"
toaddr = "EMAIL"
msg = MIMEMultipart()
msg['From'] = fromaddr
msg['To'] = toaddr
msg['Subject'] = "EMAIL SUBJECT"

body = mylist
msg.attach(MIMEText(body, 'plain'))

server = smtplib.SMTP('smtp.gmail.com', 587)
server.ehlo()
server.starttls()
server.ehlo()
server.login("EMAIL", "PASSWORD")
text = msg.as_string()
server.sendmail(fromaddr, toaddr, text)

I tried just making body = to mylist just to see how it looked currently but I get the following error: _text.encode('us-ascii')
AttributeError: 'list' object has no attribute 'encode'

What I would like ultimately is the body of the email to look this (when I receive the email):

first line
second line
third line
fourth line


Solution

  • Thanks to Michael Butscher for the push in the right direction.

    This does the job.

    body = "\r\n".join(mylist)