1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
|
from fastapi import FastAPI
from starlette.responses import JSONResponse
from fastapi_mail import FastMail, MessageSchema, ConnectionConfig, MessageType
from pydantic import EmailStr, BaseModel
from typing import List, Dict, Any
class EmailSchema(BaseModel):
email: List[EmailStr]
body: Dict[str, Any]
conf = ConnectionConfig(
MAIL_USERNAME = "YourUsername",
MAIL_PASSWORD = "strong_password",
MAIL_FROM = "your@email.com",
MAIL_PORT = 587,
MAIL_SERVER = "your mail server",
MAIL_FROM_NAME="Desired Name",
MAIL_STARTTLS = True,
MAIL_SSL_TLS = False,
USE_CREDENTIALS = True,
VALIDATE_CERTS = True
TEMPLATE_FOLDER = Path(__file__).parent / 'templates',
)
app = FastAPI()
@app.post("/email")
async def simple_send(email: EmailSchema) -> JSONResponse:
html = """<p>Hi this test mail, thanks for using Fastapi-mail</p> """
message = MessageSchema(
subject="Fastapi-Mail module",
recipients=email.dict().get("email"),
body=html,
subtype=MessageType.html)
fm = FastMail(conf)
await fm.send_message(message)
return JSONResponse(status_code=200, content={"message": "email has been sent"})
@app.post("/email/template")
async def send_with_template(email: EmailSchema) -> JSONResponse:
message = MessageSchema(
subject="Fastapi-Mail module",
recipients=email.dict().get("email"),
template_body=email.dict().get("body"),
subtype=MessageType.html,
)
fm = FastMail(conf)
await fm.send_message(message, template_name="email_template.html")
return JSONResponse(status_code=200, content={"message": "email has been sent"})
|