使用python 3.3生成并保存.eml文件
问题内容:
我正在尝试使用标准电子邮件库生成电子邮件并将其另存为.eml文件。我一定不明白email.generator的工作方式,因为我不断收到错误’AttributeError:’str’对象没有属性’write’。
from email import generator
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
active_dir = 'c:\\'
class Gen_Emails(object):
def __init__(self):
self.EmailGen()
def EmailGen(self):
sender = 'sender'
recepiant = 'recipiant'
subject = 'subject'
msg = MIMEMultipart('alternative')
msg['Subject'] = subject
msg['From'] = sender
msg['To'] = recepiant
html = """\
<html>
<head></head>
<body>
<p> hello world </p>
</body>
</html>
"""
part = MIMEText(html, 'html')
msg.attach(part)
self.SaveToFile(msg)
def SaveToFile(self,msg):
out_file = active_dir
gen = generator.Generator(out_file)
gen.flatten(msg)
有任何想法吗?
问题答案:
您应该将打开的文件(以写入模式)传递给Generator()
。当前,您仅向它传递一个字符串,这就是为什么它在尝试调用.write()
该字符串时失败的原因。
所以做这样的事情:
import os
cwd = os.getcwd()
outfile_name = os.path.join(cwd, 'message.eml')
class Gen_Emails(object):
# ...
def SaveToFile(self,msg):
with open(outfile_name, 'w') as outfile:
gen = generator.Generator(outfile)
gen.flatten(msg)
注意 :以写入模式with open(outfile_name, 'w') as outfile
在路径outfile_name
下打开文件,并将文件指针分配给打开的文件outfile
。退出with
块后,上下文管理器还负责为您关闭文件。
os.path.join()
将以跨平台的方式连接路径,这就是为什么与手工连接路径相比,您应该更喜欢它的原因。
os.getcwd()
将返回您当前的工作目录。如果要将文件保存在其他位置,请相应地将其更改。