Home > Software design >  Why when I send an email via FastAPI-mail, the email I receive displays the same message twice?
Why when I send an email via FastAPI-mail, the email I receive displays the same message twice?

Time:10-12

I am trying to send an email using FastAPI-mail, and even though I am successfully sending it, when I open the email in Gmail or Outlook, the content (message) appears twice.

I am looking at the code but I don't think I am attaching the message twice (also note that the top message always shows the tags, while the second doesn't (see below image).

Any help will be appreciated!

enter image description here

main.py

from fastapi import FastAPI
from fastapi_mail import FastMail, MessageSchema, ConnectionConfig
from starlette.requests import Request
from starlette.responses import JSONResponse
from pydantic import EmailStr, BaseModel
from typing import List
app = FastAPI()


class EmailSchema(BaseModel):
   email: List[EmailStr]


conf = ConnectionConfig(
   MAIL_USERNAME='myGmailAddress',
   MAIL_PASSWORD="myPassword",
   MAIL_FROM='myGmailAddress',
   MAIL_PORT=587,
   MAIL_SERVER="smtp.gmail.com",
   MAIL_TLS=True,
   MAIL_SSL=False
)


@app.post("/send_mail")
async def send_mail(email: EmailSchema):

    template = """
        <html>
        <body>
        

<p>Hi !!!
        <br>Thanks for using <b>fastapi mail</b>!!!</p>


        </body>
        </html>
        """

    message = MessageSchema(
        subject="Fastapi-Mail module",
        recipients=email.dict().get("email"), # List of recipients, as many as you can pass
        body=template,
        subtype="html"
        )

    template = """
<p>Hi !!!
<br>Thanks for using <b>fastapi mail</b>!!!
</p>"""

    '''
    template = """
<p>Hi !!!
<br>Thanks for using <b>fastapi mail</b>!!!
</p>"""
    '''

    fm = FastMail(conf)
    await fm.send_message(message)

    return JSONResponse(status_code=200, content={"message": "email has been sent"})

CodePudding user response:

Instead of body, use the html property.

message = MessageSchema(
    subject="Fastapi-Mail module",
    recipients=email.dict().get("email"), # List of recipients, as many as you can pass
    html=template, # <<<<<<<<< here
    subtype="html"
)

CodePudding user response:

Use the template without <html> and <body>:

    template = """
<p>Hi !!!
<br>Thanks for using <b>fastapi mail</b>!!!
</p>"""
  • Related