如何在python的电子邮件正文中打印为多行字符串的变量

问题描述

我有这段代码

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

输出

Hello
This
Is
Great

我正尝试将其打印到电子邮件正文,如下所示,我将文本作为附件而不是正文发送。有人可以告诉我我是否在这里错过什么吗?

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

解决方法

使用yagmail时,它可以正常工作。

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

其中conf_yag存储您的凭据,emailto是收件人的电子邮件地址,而'somefile.txt'是文件附件。