How do I print a variable which is multiline string in the body of email in python

424 views Asked by At

I have this piece of code:

l = ["Jargon", "Hello", "This", "Is", "Great"]
result = "\n".join(l[1:])
print result

output:

Hello
This
Is
Great

And I am trying to print this to a body of an email as shown below, I am getting the text as an attachment rather than as-body. can anyone please tell me if I am missing something here?

msg = MIMEMultipart()
msg["From"] = emailfrom
msg["To"] = emailto
ctype, encoding = mimetypes.guess_type(fileToSend)
if ctype is None or encoding is not None:
    ctype = "application/octet-stream"   
maintype, subtype = ctype.split("/", 1)
fp = open(file.csv, 'r')
attachment = MIMEBase(maintype, subtype)
attachment.set_payload(fp.read())
fp.close()
encoders.encode_base64(attachment)
attachment.add_header("Content-Disposition", "attachment", fileame='file.csv')
msg.attach(attachment)
msg.attach(MIMEText(result, "plain"))
server = smtplib.SMTP("localhost")
server.sendmail(emailfrom, emailto, msg.as_string())
server.quit()
2

There are 2 answers

3
KM_83 On

When using yagmail, it works as intended.

import yagmail 

yag = yagmail.SMTP(
  user=conf_yag['user'],
  password=conf_yag['password'])

l = ["Jargon", "Hello", "This", "Is", "Great"]
result = "\n".join(l[1:])

yag.send(emailto, 'test from yagmail', result)


# including attachment
yag.send(emailto, 
         subject='test from yagmail', 
         contents=result,
         attachments='somefile.txt')

where conf_yag stores your credentials, emailto is the receiver email address, and 'somefile.txt' is the file attachment.

0
Merin Nakarmi On

In python, `\n' means a line break. In python email, '
' means a line break.

If you do

result = result.replace('\n','<br/>')

It should work.