PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Sunday, October 23, 2022

[FIXED] Why when I send an email via FastAPI-mail, the email I receive displays the same message twice?

 October 23, 2022     email, fastapi, html, python     No comments   

Issue

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"})


Solution

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"
)


Answered By - AndreFeijo
Answer Checked By - Marie Seifert (PHPFixing Admin)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing