可能最好的方法是在
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添加到app.yaml的libraries部分,如下所示:
libraries:
- name: webapp2
version: 2.5.2
- name: jinja2
version: 2.6
…而且您还需要在应用配置中包含适当的“webapp2_extras.jinja2”.例如:
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之外的模板,但我特意选择了一个用于我的答案,因为它得到了很好的支持并且有很好的文档记录用于App Engine.