How to send email in fastapi with template

Question:

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>

When i try to send email without using template_name its sending with body values xyz(plain)

I need to send in this template format if i use template name i am getting below error . Help me to find solutions thanks

typeerror: ‘posixpath’ object is not iterable python

Asked By: putta

||

Answers:

well, you are passing your HTML file as text so that’s why you won’t receive the email as a template. you can use the jinja2 library to render your template and send it correctly.
you create an environment variable

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
)

then you use MessageSchema and you send it as you did!
hope my answer helps you

Answered By: notrayen
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
    )
Answered By: putta