如何使用模板在fastapi中发送电子邮件


conf = ConnectionConfig(
USERNAME=config.mail_username,
PASSWORD=config.mail_pasword,
FROM=config.mail_from,
PORT=config.mail_port,
SERVER=config.mail_server,
USE_CREDENTIALS=True,
VALIDATE_CERTS=True,
TEMPLATE_FOLDER='./templates'
)
async def send_email(email_to: EmailSchema, body:EmailSchema) -> JSONResponse:
message = MessageSchema(
subject="fastapi",
recipients=[email_to],
body=body,
subtype="html"
)
fm = FastMail(conf)

await fm.send_message(message,template_name='email.html')
data="xyz"
@app.get("/email")
async def endpoint_send_email(
): 
await send_email(
email_to=email_to,
body=data
)

email.html
<!DOCTYPE html>
<html>
<head>
<title>email</title>
</head>
<body>
<h4>Hi Team</h4>
<p>get the data of date {{date}}</p><br />
{{body.data}}
<br /><br />
<h4>thanks,</h4>
<h4>Team</h4>
</body>
</html>

当我试图发送电子邮件而不使用template_namexyz(普通)

我需要在这个模板格式发送,如果我使用模板名称,我得到下面的错误。帮助我找到解决方案,谢谢

typeerror: 'posixpath' object is not iterable python

好吧,你正在传递你的HTML文件作为文本,所以这就是为什么你不会收到电子邮件作为模板。您可以使用jinja2库呈现模板并正确地发送它。创建一个环境变量

env = Environment(
loader=PackageLoader('app', 'templates'),#where you are getting the templates from
autoescape=select_autoescape(['html', 'xml']))
template = env.get_template(template_name)
html = template.render(
name=email,
code=code,
subject=subject
)

则使用MessageSchema并按原样发送!希望我的回答对你有所帮助

env = Environment(
loader=FileSystemLoader(searchpath="./templates"),
autoescape=select_autoescape(['html', 'xml'])
)
async def sendMail(url,email_to: EmailSchema):
conf = ConnectionConfig(
USERNAME=config.mail_username,
PASSWORD=config.mail_pasword,
FROM=config.mail_from,
PORT=config.mail_port,
SERVER=config.mail_server,
USE_CREDENTIALS=True,
VALIDATE_CERTS=True,
)
template = env.get_template('email.html')
html = template.render(
url=url,
)
message = MessageSchema(
subject="fastapi",
recipients=[email_to],
body=body,
subtype="html"
)
fm = FastMail(conf)
await fm.send_message(message)
data="xyz"
@app.get("/email")
async def endpoint_send_email(
): 
await send_email(
email_to=email_to,
url=data
)

相关内容

  • 没有找到相关文章

最新更新