【问题标题】:Send html email using flask in Python在 Python 中使用烧瓶发送 html 电子邮件
【发布时间】:2017-06-27 10:42:20
【问题描述】:

我想使用 Python 和 Flask 将 HTML 网页作为邮件正文发送。我尝试使用 MIME 模块,但不知何故我无法发送邮件。如果有人对此有任何专业知识,请您帮助我。

如果你也能提供一些代码就好了。

【问题讨论】:

标签: python html email flask webpage


【解决方案1】:

flask-mail 是一个很好的工具,我用它来渲染模板以将 HTML 渲染为我的邮件正文。

from flask_mail import Message
from flask import render_template
MAIL_USERNAME = os.environ.get('MAIL_USERNAME')
MAIL_PASSWORD = os.environ.get('MAIL_PASSWORD')
    
def send_mail_flask(to,subject,template,**kwargs):
    msg = Message(subject=subject,sender='email@ofTheSender.com', recipients=to)
    msg.body = render_template('template.txt', **kwargs)
    msg.html = render_template('template.html', **kwargs)
    mail.send(msg)

模板是您希望包含在邮件中的 HTML 文件,您也可以使用 msg.body 添加文本版本!

您可能需要根据您使用的 SMTP 服务添加更多的环境变量。

【讨论】:

  • 为 msg.html 点赞
  • 问题是烧瓶邮件已经死了:-(
【解决方案2】:

尝试使用 FlaskMail https://pythonhosted.org/flask-mail/

msg = Message(
    recipients=[''],
    sender='xx@zz.yy',
    reply_to='aa@bb.cc',
    subject=mail.subject
  )
msg.html = mail.body
mail.send(msg)

这里,mail 是从“mails”目录导入的文件, body 是一个 HTML 标记。

【讨论】:

    【解决方案3】:

    在一个单独的 python 文件 (emails.py) 上,我创建了一个电子邮件类,其中包含要根据用户的操作发送给用户的所有电子邮件(作为类方法),如下所示:

    class Email:
    
        def accountCreation():
            body = "<html> <body> <p> {} </p> <br> <br>  <p> Lorem Ipsum is simply dummy text of the printing and typesetting industry.</p> </body> </html>"
            return body
    

    然后在我使用 flask_mail 库的另一个文件 (app.py) 上:

    from flask_mail import Mail, Message
    import emails
    
    mailer = emails.Email()
    
    try:
        email = "johndoe@mail.com"
        body = mailer.accountCreation()
        msg = Message('Hello',recipients=[email])
                                    
        msg.html =  body 
        mail.send(msg)
    except Exception as e:
        print(e)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2014-09-14
      • 2010-10-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多