首页 > 解决方案 > 如何在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()

标签: pythonemail-attachmentsmime-message

解决方案


使用时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'是文件附件。


推荐阅读