可能最好的方法是use a templating engine从HTML文件加载并生成字符串形式的HTML。例如,如果您使用webapp2 jinja2 extras包,您可以按照以下方式执行操作:from webapp2_extras import jinja2 as webapp_extras_jinja2
# ...
def get_message_html():
jinja2 = webapp_extras_jinja2.get_jinja2()
return jinja2.render_template('relative/path/to/template.html')
# ...
def send_email():
# ...
message.html = get_message_html()
# ...
请注意,要使其正常工作,您需要将jinja2添加到应用程序yaml如:
^{pr2}$
。。。你还需要包括一个合适的webapp2_额外服务2'到应用程序配置。例如:config = {
'webapp2_extras.jinja2': {
'template_path': 'path/containing/my/templates',
'environment_args': {
# Keep generated HTML short
'trim_blocks': True,
'extensions': [
# Support auto-escaping for security
'jinja2.ext.autoescape',
# Handy but might not be needed for you
'jinja2.ext.with_'
# ... other extensions? ...
],
# Auto-escape by default for security
'autoescape': True
},
# .. other configuration options for jinja2 ...
},
# ... other configuration for the app ...
},
# ...
app = webapp2.WSGIApplication(routes, is_debug_enabled, config)
虽然您可以自己轻松地打开HTML文件,但是使用jinja2这样的模板引擎的好处是,它将鼓励您以更理智的方式编写和重用HTML(而简单地加载HTML文件可能最终导致您手动应用替换)。另外,只是一个快速的安全提示:如果您在电子邮件中包含的任何数据来自不受信任的源(如用户或其他用户),请确保正确验证并检查内容是否正常(同时在模板引擎中启用自动转义)。在
显然,您可以选择jinja2之外的模板,但是我特别选择了这个模板作为我的答案,因为它在appengine中得到了很好的支持和文档记录。在