美文网首页
Python渲染模板发送邮件

Python渲染模板发送邮件

作者: _张大云 | 来源:发表于2021-09-27 17:13 被阅读0次

    方式一

    from typing import List
    
    import yagmail
    from jinja2 import Template
    
    def send_email(
            email_to: List[str],
            title: str,
            html: str,
    ) -> None:
        yag = yagmail.SMTP(
            host=""smtp.163.com"", user="test@163.com",
            password="PASSWORD"
        )
        response = yag.send(to=email_to, subject=title, contents=html)
        print(f"邮件发送结果: {email_to} {response}")
    
    
    def send_test_email(email_to: List[str]) -> None:
        project_name = settings.PROJECT_NAME
        subject = f"{project_name} - A important email"
        
        with open("test_email.html") as f:
            tm = Template(f.read())
    
        msg = tm.render({"project_name": project_name, "email": email_to})
    
        send_email(
            email_to=email_to,
            title=subject,
            html=msg
        )
    
    
    if __name__ == '__main__':
        send_test_email(['cloud74521941@163.com', 'cloud_0805@163.com'])
    

    方式二

    import emails
    from emails.template import JinjaTemplate
    
    def send_email(
            email_to: str,
            subject_template: str = "",
            html_template: str = "",
            environment: Dict[str, Any] = dict({}),
    ) -> None:
        assert settings.EMAILS_ENABLED, "no provided configuration for email variables"
        message = emails.Message(
            subject=JinjaTemplate(subject_template),
            html=JinjaTemplate(html_template),
            mail_from=(settings.EMAILS_FROM_NAME, settings.EMAILS_FROM_EMAIL),
        )
        smtp_options = {"host": settings.SMTP_HOST, "port": settings.SMTP_PORT}
        if settings.SMTP_TLS:
            smtp_options["tls"] = True
        if settings.SMTP_USER:
            smtp_options["user"] = settings.SMTP_USER
        if settings.SMTP_PASSWORD:
            smtp_options["password"] = settings.SMTP_PASSWORD
    
        response = message.send(to=email_to, render=environment,
                                smtp=smtp_options)
        logger.info(f"邮件发送结果: {email_to} {response}")
    
    
    def send_test_email(email_to: str) -> None:
        project_name = settings.PROJECT_NAME
        subject = f"{project_name} - A important email"
        with open(Path(settings.EMAIL_TEMPLATES_DIR) / "test_email.html") as f:
            template_str = f.read()
        send_email(
            email_to=email_to,
            subject_template=subject,
            html_template=template_str,
            environment={"project_name": project_name, "email": email_to}
        )
    

    相关文章

      网友评论

          本文标题:Python渲染模板发送邮件

          本文链接:https://www.haomeiwen.com/subject/lmqknltx.html