我有一段代码:
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'
是文件附件。