Search code examples
pythonsmtplib

Getting \n in a string when adding it to email


Trying to add a string that I created before from excel using this code

data = interface.df
data1 = data.drop_duplicates(subset=["Ref/Lic Nr"], keep="first")
cr = pd.DataFrame(data1,columns= ['Carrier'])
rf = pd.DataFrame(data1,columns= ['Ref/Lic Nr'])
amtg = data1.loc[data1.Carrier=='AMTG', 'Ref/Lic Nr']
amtg1=(amtg.to_string(index=False, header=False))

And then in entering it to this code

import smtplib
import carriers
gmail_user = 'asgsgasgasg@gmail.com'
gmail_password = 'wqrqwgqwgqwb'

sent_from = gmail_user
if len(carriers.amtg) > 0:   
    to = ['afasgaswrl@gmail.com']
    subject = 'updates'
    body = " Good morning, Can we get updates for: ", carriers.amtg1
else:
     pass

email_text = """\
From: %s
To: %s
Subject: %s

%s
""" % (sent_from, ", ".join(to), subject, body)

try:
    server = smtplib.SMTP_SSL('smtp.gmail.com', 465)
    server.ehlo()
    server.login(gmail_user, gmail_password)
    server.sendmail(sent_from, to, email_text)
    server.close()

    print ('Email sent!')
except:
    print ('Something went wrong...')

But when I receive the info I get values like CNG41383874\n CNG41383875\n instead of:

CNG41383874

CNG41383875

Email that i receive


Solution

  • Your problem is here:

    body = " Good morning, Can we get updates for: ", carriers.amtg1
    

    That sets the body to a tuple of strings, not one long string, and when it's formatted into the email_text variable, it puts in the str form of the tuple, which is the repr of its components (and the repr of a str with newlines will display the escape, not the raw newline character). To make it work, concatenate the strings into a single string:

    body = " Good morning, Can we get updates for: " + carriers.amtg1
    

    This will format the normal str form into email_text directly, not multiple reprs, preventing this issue.