将 \n 添加到电子邮件时获取字符串

Getting \n in a string when adding it to email

尝试添加我之前使用此代码从 excel 创建的字符串

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))

然后输入这个代码

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...')

但是当我收到信息时,我得到的值类似于 CNG41383874\n CNG41383875\n 而不是:

CNG41383874

CNG41383875

您的问题在这里:

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

body 设置为一个 tuple 字符串,而不是一个长字符串,当它被格式化为 email_text 变量时,它会放入 str tuple 的形式,它是其组件的 repr(带换行符的 strrepr 将显示转义符,而不是原始换行符)。要使其工作,请将字符串连接成一个字符串:

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

这会将正常的 str 格式直接格式化为 email_text,而不是多个 repr,从而防止出现此问题。