Beispiel #1
0
async def test_html_message_with_html(mail_config):
    persons = [{
        'name': 'Andrej'
    }, {
        'name': 'Mark'
    }, {
        'name': 'Thomas'
    }, {
        'name': 'Lucy',
    }, {
        'name': 'Robert'
    }, {
        'name': 'Dragomir'
    }]

    directory = os.getcwd()
    html = directory + "/files"

    msg = MessageSchema(subject="testing",
                        recipients=["*****@*****.**"],
                        html=persons)
    conf = ConnectionConfig(**mail_config)
    fm = FastMail(conf)
    await fm.send_message(message=msg, template_name="email.html")
    assert msg.html == '''
Beispiel #2
0
 def __init__(self):
     self.conf = ConnectionConfig(MAIL_USERNAME=settings.system_username,
                                  MAIL_PASSWORD=settings.system_mail_pw,
                                  MAIL_FROM=settings.system_mail,
                                  MAIL_PORT=settings.mail_server_port,
                                  MAIL_SERVER=settings.mail_server,
                                  MAIL_TLS=True,
                                  MAIL_SSL=False)
Beispiel #3
0
async def test_connection(mail_config):
    message = MessageSchema(subject="test subject",
                            recipients=["*****@*****.**"],
                            body="test",
                            subtype="plain")
    conf = ConnectionConfig(**mail_config)

    fm = FastMail(conf)

    await fm.send_message(message)
Beispiel #4
0
def send_email(background_tasks: BackgroundTasks, email, code,
               request: Request):
    """Sends an email with a defined template containing the passcode.

    Email is intialized at '/enter_recovery_email' endpoint as global.
    You have to fill in here your email and password from which you want
    to send the mail (GMAIL).

    Parameters
    ----------
    background_tasks : BackgroudTasks
        For sending the mail in the background.
    request : Request
        For using JinJaTemplates as a response.

    Returns
    -------
    template : Jinaja Template
        Returns the template "after_email_sent_response.html".
    """

    template = """
        <html>
        <body>
        <p>Hi !!!
        <br>Thanks for using Workeeper</p>
        <p> Your passcode is : %s </p>
        </body>
        </html>
        """ % (code)

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

    message = MessageSchema(
        subject="password recovery",
        recipients=[email],  # List of recipients, as many as you can pass  
        body=template,
        subtype="html")

    fm = FastMail(conf)

    #await fm.send_message(message)

    background_tasks.add_task(fm.send_message, message)

    return templates.TemplateResponse("after_email_sent_response.html",
                                      {"request": request})
Beispiel #5
0
    async def send_email(self,
                         subject: str,
                         email: str,
                         recipients,
                         test_email: bool = False):

        conf = await self.get_email_config()
        if not conf:
            return f"no email server configured"

        decoded = self.decode(conf[0]["password"])

        conf[0]["password"] = decoded[1]["password"]
        conf = conf[0]

        conf = ConnectionConfig(
            **{
                "MAIL_USERNAME": conf["username"],
                "MAIL_PASSWORD": conf["password"],
                "MAIL_FROM": conf["mail_from"],
                "MAIL_PORT": conf["port"],
                "MAIL_SERVER": conf["server"],
                "MAIL_FROM_NAME": conf["mail_from_name"],
                "MAIL_TLS": conf["mail_tls"],
                "MAIL_SSL": conf["mail_ssl"],
            })

        body = f"""<p>{email}</p>"""

        message = MessageSchema(
            subject=f"{subject}",
            recipients=recipients if isinstance(recipients, list) else
            [recipients],  # List of recipients, as many as you can pass
            body=body,
            subtype="html",
        )

        async def email_send():
            try:
                return await fm.send_message(message)
            except Exception as e:
                self.log.exception("Error sending email")
                return f"Error Sending Email - {repr(e)}"

        fm = FastMail(conf)
        if not test_email:
            asyncio.create_task(email_send())
        else:
            result = await email_send()
        return {"message": "email sent"}
Beispiel #6
0
class EmailSchema(BaseModel):
    emails: List[EmailStr]

    try:
        conf = ConnectionConfig(MAIL_USERNAME=MAIL_USERNAME,
                                MAIL_PASSWORD=MAIL_PASSWORD,
                                MAIL_FROM=MAIL_SENDER_ADDRESS,
                                MAIL_PORT=MAIL_PORT,
                                MAIL_SERVER=MAIL_SERVER,
                                MAIL_TLS=MAIL_TLS,
                                MAIL_SSL=MAIL_SSL,
                                USE_CREDENTIALS=True)
    except Exception as e:
        warnings.warn(f"Error while trying to config email schema:{e}")
Beispiel #7
0
async def connect_to_smtp():
    logging.info("FastMail: Start Connection...")
    smtp.client = FastMail(
        ConnectionConfig(
            MAIL_USERNAME=settings.MAIL_USERNAME,
            MAIL_PASSWORD=settings.MAIL_PASSWORD,
            MAIL_FROM=settings.MAIL_FROM,
            MAIL_PORT=settings.MAIL_PORT,
            MAIL_SERVER=settings.MAIL_SERVER,
            MAIL_TLS=settings.MAIL_TLS,
            MAIL_SSL=settings.MAIL_SSL,
            USE_CREDENTIALS=settings.MAIL_USE_CREDENTIALS,
        ))
    logging.info("FastMail: Connection Successful!")
Beispiel #8
0
async def test_html_message(mail_config):

    directory = os.getcwd()
    html = directory + "/files"

    msg = MessageSchema(subject="testing",
                        recipients=["*****@*****.**"],
                        body="html test")
    conf = ConnectionConfig(**mail_config)
    fm = FastMail(conf)

    await fm.send_message(message=msg, template_name="test.html")

    assert msg.subtype == "html"
Beispiel #9
0
def get_config():
    current_config = data.get_campaign_config_default()
    if not current_config:
        return False
    return ConnectionConfig(
        MAIL_USERNAME=current_config["MAIL_USERNAME"],
        MAIL_PASSWORD=current_config["MAIL_PASSWORD"],
        MAIL_FROM=current_config["MAIL_FROM"],
        MAIL_PORT=current_config["MAIL_PORT"],
        MAIL_SERVER=current_config["MAIL_SERVER"],
        MAIL_FROM_NAME=current_config["MAIL_FROM_NAME"],
        MAIL_TLS=current_config["MAIL_TLS"],
        MAIL_SSL=current_config["MAIL_SSL"],
        USE_CREDENTIALS=current_config["USE_CREDENTIALS"],
        TEMPLATE_FOLDER="./api/templates",
    )
Beispiel #10
0
async def test_send_msg(mail_config):
    msg = MessageSchema(subject="testing",
                        recipients=["*****@*****.**"],

                        body="html test")

    sender = f"{mail_config['MAIL_FROM_NAME']} <{mail_config['MAIL_FROM']}>"
    conf = ConnectionConfig(**mail_config)
    fm = FastMail(conf)
    fm.config.SUPPRESS_SEND = 1
    with fm.record_messages() as outbox:
        await fm.send_message(message=msg, template_name="test.html")

        assert len(outbox) == 1
        assert outbox[0]["subject"] == "testing"
        assert outbox[0]["from"] == sender
        assert outbox[0]["To"] == "*****@*****.**"
Beispiel #11
0
async def test_html_message_with_html(mail_config):
    persons = [
        {"name": "Andrej"},
        {"name": "Mark"},
        {"name": "Thomas"},
        {"name": "Lucy", },
        {"name": "Robert"},
        {"name": "Dragomir"}
    ]

    directory = os.getcwd()
    html = directory + "/files"

    msg = MessageSchema(subject="testing",
                        recipients=["*****@*****.**"],
                        html=persons)
    conf = ConnectionConfig(**mail_config)
    fm = FastMail(conf)
    await fm.send_message(message=msg, template_name="email.html")
    assert msg.html == """
Beispiel #12
0
class Settings(BaseSettings):
    app_name: str = "DACoT API"
    mongo_uri: str
    mail_user: str
    mail_pass: str
    mail_config: ConnectionConfig = None
    mail_extra_targets: List[str] = list()
    authjwt_secret_key: str
    apikey_users_file: str = '/app/fake_users.json'


settings = Settings()

if settings.mail_user and settings.mail_pass:
    settings.mail_config = ConnectionConfig(
        MAIL_USERNAME=settings.mail_user,
        MAIL_PASSWORD=settings.mail_pass,
        MAIL_PORT=587,
        MAIL_FROM='*****@*****.**',
        MAIL_SERVER='smtp.gmail.com',
        MAIL_TLS=True,
        MAIL_SSL=False,
        USE_CREDENTIALS=True,
        TEMPLATE_FOLDER='/app/email_templates/')


@lru_cache()
def get_settings():
    return settings
Beispiel #13
0
from fastapi import BackgroundTasks
from fastapi_mail import FastMail, MessageSchema, ConnectionConfig
from pydantic import EmailStr
from config import MailSettings

from os import path

_conf = ConnectionConfig(MAIL_USERNAME=MailSettings.MAIL_USERNAME,
                         MAIL_PASSWORD=MailSettings.MAIL_PASSWORD,
                         MAIL_SERVER=MailSettings.MAIL_SERVER,
                         MAIL_PORT=MailSettings.MAIL_PORT,
                         MAIL_TLS=MailSettings.MAIL_TLS,
                         MAIL_SSL=MailSettings.MAIL_SSL,
                         MAIL_FROM=MailSettings.MAIL_FROM,
                         MAIL_FROM_NAME=MailSettings.MAIL_NICENAME,
                         USE_CREDENTIALS=True,
                         TEMPLATE_FOLDER=path.join(path.dirname(__file__),
                                                   '..', 'templates', 'email'))


async def send_email_async(subject: str,
                           recipients: list[EmailStr],
                           template: str,
                           body: dict = {},
                           attachments: list[dict] = []):
    message = MessageSchema(subject=subject,
                            recipients=recipients,
                            template_body=body,
                            subtype='html',
                            attachments=attachments)
Beispiel #14
0
from fastapi_mail import FastMail, MessageSchema, ConnectionConfig
from mjml import mjml_to_html

from app.core import config, security

EMAIL_TEMPLATES = Path(__file__).parent.parent / "email_templates"
SRC_TEMPATE_LOC = EMAIL_TEMPLATES / "src"
BUILD_TEMPLATE_LOC = EMAIL_TEMPLATES / "build"

conf = ConnectionConfig(
    MAIL_USERNAME=config.SMTP_USER,
    MAIL_PASSWORD=config.SMTP_PASSWORD,
    MAIL_FROM=config.EMAILS_FROM_EMAIL,
    MAIL_PORT=1025,
    MAIL_SERVER="localhost",
    MAIL_FROM_NAME=config.EMAILS_FROM_NAME,
    MAIL_TLS=False,
    MAIL_SSL=False,
    USE_CREDENTIALS=False,
    VALIDATE_CERTS=False,
    TEMPLATE_FOLDER=BUILD_TEMPLATE_LOC,
)


def build_email_templates():
    for template_filename in os.listdir(SRC_TEMPATE_LOC):
        logging.info(f"Building email template {template_filename}...")
        template_name = template_filename.split(".")[0]
        with (SRC_TEMPATE_LOC / template_filename).open("rb") as fp:
            html_output = mjml_to_html(fp)
        with (BUILD_TEMPLATE_LOC / (template_name + ".html")).open("w+") as fp:
from jose import JWTError, jwt
from datetime import datetime, timedelta

from fastapi_mail import FastMail, MessageSchema, ConnectionConfig

#from modules.topic_classification import inference
import json
#Define secret key and algorithm
SECRET_KEY = "b8f93afd6ae4f16427e475cb090a23671e6e9f00dc5fbd603c1469355f575854"
ALGORITHM = "HS256"
ACCESS_TOKEN_EXPIRE_MINUTES = 1000

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

#Load model
"""def load_model():
    predictor = inference.Predictor()
    return predictor 
"""
#predictor = load_model()


def get_db():
    db = SessionLocal()
    try:
Beispiel #16
0
"""
Extracts the logic needed to craft a notification email.
"""

from fastapi_mail import ConnectionConfig
from backend.server.actions import job_actions, todo_actions
from datetime import datetime, timedelta
from jinja2 import Environment, FileSystemLoader
import os

# Move this to env file
email_config = ConnectionConfig(
    MAIL_USERNAME="******",
    MAIL_PASSWORD="******",
    MAIL_FROM="*****@*****.**",
    MAIL_PORT=587,
    MAIL_SERVER="smtp.gmail.com",
    MAIL_FROM_NAME="Jobful App",
    MAIL_TLS=True,
    MAIL_SSL=False,
)


# Receives a user object, returns a template to be sent
async def build_template(user):
    # Get data from DB
    incomplete_todos = []
    jobs = await job_actions.get_all_with_status(user.id, "0"
                                                 )  # "0" is all "Added" jobs

    for job in jobs:
        todos = await todo_actions.get_all(job,
Beispiel #17
0
config.parse_args()


class Body(BaseModel):
    username: str
    confirm_url: AnyHttpUrl


conf = ConnectionConfig(
    MAIL_USERNAME=os.getenv("MAIL_USERNAME") or config.CONFIG.mail_username,
    MAIL_PASSWORD=os.getenv("MAIL_PASSWORD") or config.CONFIG.mail_password,
    MAIL_FROM=os.getenv("MAIL_USERNAME") or config.CONFIG.mail_username
    or "*****@*****.**",
    MAIL_PORT=int(config.CONFIG.mail_port),
    MAIL_SERVER=config.CONFIG.mail_server,
    MAIL_FROM_NAME=config.CONFIG.mail_from,
    MAIL_TLS=True,
    MAIL_SSL=False,
    USE_CREDENTIALS=True,
    TEMPLATE_FOLDER="./api/mail",
)


async def user(to: EmailStr, body: Body):
    message = MessageSchema(subject="Confirm your email address",
                            recipients=[to],
                            body=body,
                            subtype="html")
    if (os.getenv("MAIL_USERNAME") and os.getenv("MAIL_PASSWORD")) or (
            config.CONFIG.mail_username and config.CONFIG.mail_password):
Beispiel #18
0
import os
from datetime import datetime
from typing import List, Union
from reykjalundur.common.config import email_console
from fastapi_mail import FastMail, MessageSchema, ConnectionConfig
from .models import EmailMessage, SocketResponse

conf = ConnectionConfig(
    MAIL_USERNAME=os.environ["MAIL_USER"],
    MAIL_PASSWORD=os.environ["MAIL_PASSWORD"],
    MAIL_FROM=os.environ["MAIL_FROM"],
    MAIL_PORT=587,
    MAIL_SERVER=os.environ["MAIL_SERVER"],
    MAIL_TLS=True,
    MAIL_SSL=False,
)


async def send_mail(message: EmailMessage) -> SocketResponse:

    data = MessageSchema(
        subject=message.subject,
        recipients=message.recipients.dict().get("email"),
        body=message.body,
        subtype="html",
    )

    fm = FastMail(conf)
    if not email_console:
        await fm.send_message(data)
    else:
Beispiel #19
0
from functools import lru_cache
from typing import List
import os

from fastapi_mail import FastMail, ConnectionConfig
from pydantic import EmailStr, BaseModel


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


conf = ConnectionConfig(
    MAIL_USERNAME=os.environ["MAIL_USERNAME"],
    MAIL_PASSWORD=os.environ["MAIL_PASSWORD"],
    MAIL_FROM=os.environ["MAIL_FROM"],
    MAIL_PORT=int(os.environ["MAIL_PORT"]),
    MAIL_SERVER=os.environ["MAIL_HOSTNAME"],
    MAIL_TLS=bool(os.environ["MAIL_TLS"]),
    MAIL_SSL=bool(os.environ["MAIL_SSL"]),
)

mailer = FastMail(conf)


@lru_cache()
def get_mailer():
    return mailer
Beispiel #20
0
@router.delete("/notes/{note_id}/",
               response_model=Note,
               status_code=status.HTTP_200_OK)
async def delete_note(note_id: int):
    query = notes.delete().where(notes.c.id == note_id)
    await database.execute(query)
    return {
        "message": "Note with id: {} deleted successfully!".format(note_id)
    }


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

template = """
<p>Your Account is registered Sucessfully </p>
"""


@router.post('/User', status_code=status.HTTP_200_OK)
async def User_Created(email: Email):
    if not email.email:
        raise HTTPException(status_code=status.HTTP_204_NO_CONTENT,
                            detail="User is not Created")
Beispiel #21
0
config.read("../conf/conf.ini")
PROD = eval(config['MODE']['PRODUCTION'])
INDEX = config['ES']['QUANTITIES']
mail = config['MAIL']
HOST = os.getenv('API_HOST', '0.0.0.0')
PORT = os.getenv('API_PORT', 5000)

uvicorn_logger = logging.getLogger('uvicorn')
f_logger.handlers = uvicorn_logger.handlers
f_logger.setLevel(uvicorn_logger.level)

MAIL = ConnectionConfig(MAIL_USERNAME=os.getenv('MAIL_USER', ''),
                        MAIL_PASSWORD=os.getenv('MAIL_KEY', ''),
                        MAIL_FROM="*****@*****.**",
                        MAIL_FROM_NAME="Science Checker",
                        MAIL_PORT=int(os.getenv('MAIL_PORT', 587)),
                        MAIL_SERVER=os.getenv('MAIL_SERVER', ''),
                        MAIL_TLS=True,
                        MAIL_SSL=False,
                        TEMPLATE_FOLDER=mail['TEMPLATE'])

CLASSIFIER = config['SQA']['CLASSIFIER']
PULLER = config['SQA'].get('PULLER')
EXTRACTOR = config['SQA'].get('EXTRACTOR', 'eqa')

LIST_TASK = list()
DATA_PATH = config['BASE'].get('PATH', '')

##################################################

sampler, classifier, puller = load_sqa(CLASSIFIER, PULLER, extractor=EXTRACTOR)

class Envs:
    MAIL_USERNAME = os.getenv('MAIL_USERNAME')
    MAIL_PASSWORD = os.getenv('MAIL_PASSWORD')
    MAIL_FROM = os.getenv('MAIL_FROM')
    MAIL_PORT = int(os.getenv('MAIL_PORT'))
    MAIL_SERVER = os.getenv('MAIL_SERVER')
    MAIL_FROM_NAME = os.getenv('MAIN_FROM_NAME')


conf = ConnectionConfig(MAIL_USERNAME=Envs.MAIL_USERNAME,
                        MAIL_PASSWORD=Envs.MAIL_PASSWORD,
                        MAIL_FROM=Envs.MAIL_FROM,
                        MAIL_PORT=Envs.MAIL_PORT,
                        MAIL_SERVER=Envs.MAIL_SERVER,
                        MAIL_FROM_NAME=Envs.MAIL_FROM_NAME,
                        MAIL_TLS=True,
                        MAIL_SSL=False,
                        USE_CREDENTIALS=True,
                        TEMPLATE_FOLDER='./templates/email')


async def send_email_async(subject: str, email_to: str, body: dict):
    message = MessageSchema(
        subject=subject,
        recipients=[email_to],
        body=body,
        subtype='html',
    )

    fm = FastMail(conf)
Beispiel #23
0
# settings
settings = Settings()

# client
client = AsyncIOMotorClient(settings.database_url,
                            uuidRepresentation='standard')

# database
db = client['rowmate']
db['templates'].create_index([('ngrams', TEXT)], name='templates_ngrams_index')
db['questions'].create_index([('ngrams', TEXT)], name='questions_ngrams_index')
db['events'].create_index([('ngrams', TEXT)], name='events_ngrams_index')

user_db = MongoDBUserDatabase(UserDB, db['users'])

jwt_auth = Authentication(secret=settings.jwt_secret,
                          lifetime_seconds_refresh=50000,
                          lifetime_seconds=3600)

api_user = APIUsers(user_db, [jwt_auth], User, UserCreate, UserUpdate, UserDB)

smtp_config = ConnectionConfig(MAIL_USERNAME=settings.smtp_username,
                               MAIL_PASSWORD=settings.smtp_password,
                               MAIL_SERVER=settings.smtp_server,
                               MAIL_PORT=settings.smtp_port,
                               MAIL_TLS=settings.smtp_tls,
                               MAIL_SSL=settings.smtp_ssl,
                               MAIL_FROM=settings.smtp_username)
# initialize
mail = FastMail(smtp_config)
Beispiel #24
0
from fastapi_mail import FastMail, MessageSchema, ConnectionConfig
from pydantic import EmailStr, BaseModel
from fastapi_mail.email_utils import DefaultChecker
from dotenv import load_dotenv

import os

load_dotenv()


conf = ConnectionConfig(
    MAIL_USERNAME=os.getenv("MAIL_USERNAME"),
    MAIL_PASSWORD=os.getenv("MAIL_PASSWORD"),
    MAIL_FROM=os.getenv("MAIL_FROM"),
    MAIL_PORT=int(os.getenv("MAIL_PORT")),
    MAIL_SERVER=os.getenv("MAIL_SERVER"),
    MAIL_FROM_NAME=os.getenv("MAIL_FROM_NAME"),
    MAIL_TLS=True if os.getenv("MAIL_TLS") == "True" else False,
    MAIL_SSL=True if os.getenv("MAIL_SSL") == "True" else False,
)


async def simple_send(emails, content, subject):

    message = MessageSchema(
        subject=subject,
        recipients=emails,
        body=content,
        subtype="html"
    )
Beispiel #25
0
from fastapi_mail import FastMail, MessageSchema, ConnectionConfig

import logging
import os

from models import NewUserInput, ResetPasswordInput, MailOutput

logging.config.fileConfig('logging.conf', disable_existing_loggers=False)
templates = Jinja2Templates(directory='templates')

app = FastAPI()
logger = logging.getLogger('email')
conf = ConnectionConfig(MAIL_USERNAME=os.environ.get('SMTP_USERNAME'),
                        MAIL_PASSWORD=os.environ.get('SMTP_PASSWORD'),
                        MAIL_FROM='*****@*****.**',
                        MAIL_PORT=os.environ.get('EMAIL_PORT', '2525'),
                        MAIL_SERVER=os.environ.get('SMTP_SERVER'),
                        MAIL_TLS=True,
                        MAIL_SSL=False,
                        USE_CREDENTIALS=True)
fm = FastMail(conf)

FRONT_URL = 'http://example.com'


@app.post('/new-user/', response_model=MailOutput)
async def new_user(data: NewUserInput):
    """ Send email welcoming a new user. """

    logger.info(f'new_user email input received: {data}')

    template = templates.get_template('new_user.html')
from typing import List
from database import app, client
from models import EmailSchema
from fastapi import APIRouter
from starlette.responses import JSONResponse
from fastapi_mail import FastMail, MessageSchema, ConnectionConfig

SURVEY_URL = 'https://www.google.com/'

conf = ConnectionConfig(MAIL_USERNAME="******",
                        MAIL_PASSWORD="******",
                        MAIL_FROM="*****@*****.**",
                        MAIL_PORT=587,
                        MAIL_SERVER="smtp.gmail.com",
                        MAIL_FROM_NAME="Project 28",
                        MAIL_TLS=True,
                        MAIL_SSL=False,
                        USE_CREDENTIALS=True,
                        VALIDATE_CERTS=True)

app = APIRouter()

html = f"""
Hello, this is Project 28.
We are pleased to invite you to join our survey. Below is the survey link.
{SURVEY_URL}
Thank you.
"""
db = client.email2
# Q1 Haven't put any data to database
Beispiel #27
0
from email.mime.text import MIMEText

from fastapi_mail import ConnectionConfig, MessageSchema, FastMail
from jinja2 import Environment, PackageLoader, select_autoescape

from app.settings import mail_setting, app_settings

conf = ConnectionConfig(MAIL_USERNAME=mail_setting.username,
                        MAIL_PASSWORD=mail_setting.password,
                        MAIL_FROM=mail_setting.from_email,
                        MAIL_PORT=mail_setting.port,
                        MAIL_SERVER=mail_setting.server,
                        MAIL_TLS=mail_setting.tls,
                        MAIL_SSL=mail_setting.ssl)


class MailHelper:
    async def send_welcome_email(self, registration_data, user_email):
        await self.send_email(
            subject='Inscripción a II Carrera Virtual Runners Cúcuta',
            html_template="",
            recipents=[user_email],
            template_name='welcome.html',
            template_data=registration_data,
        )

    async def send_reset_password_email(self, recovery_password_data: dict,
                                        user_email: str):
        await self.send_email(
            subject='Runners Cúcuta: Recupera tu contraseña',
            html_template="",
Beispiel #28
0
from fastapi_mail import FastMail, MessageSchema, ConnectionConfig

from schema.user_schema import UserSchema
from models.user import User
from mongoengine.errors import NotUniqueError
from os import getenv
from dotenv import load_dotenv

load_dotenv()

router = APIRouter()

conf = ConnectionConfig(MAIL_USERNAME=getenv("GMAIL"),
                        MAIL_PASSWORD=getenv("PASSWORD"),
                        MAIL_FROM=getenv("GMAIL"),
                        MAIL_PORT=587,
                        MAIL_SERVER="smtp.gmail.com",
                        MAIL_TLS=True,
                        MAIL_SSL=False)


@router.post('/api/register')
async def register_user(background_tasks: BackgroundTasks,
                        payload: UserSchema) -> JSONResponse:
    try:

        user = User(full_name=payload.full_name, email=payload.email)
        user.save()
        registeredUser = UserSchema(full_name=user.full_name, email=user.email)

    except NotUniqueError:
Beispiel #29
0
from fastapi import FastAPI, BackgroundTasks, UploadFile, File, Form
from starlette.responses import JSONResponse
from .templates import html, template, bulkmail
from .schema import EmailSchema, EmailStr
from starlette.requests import Request
from fastapi_mail import FastMail, MessageSchema, ConnectionConfig

conf = ConnectionConfig(MAIL_USERNAME="******",
                        MAIL_PASSWORD="******",
                        MAIL_PORT=587,
                        MAIL_SERVER="your mail server",
                        MAIL_TLS=True,
                        MAIL_SSL=False)

app = FastAPI()


#test email standart sending mail
@app.post("/email")
async def simple_send(email: EmailSchema) -> JSONResponse:

    message = MessageSchema(subject="Fastapi-Mail module",
                            recipients=email.dict().get("email"),
                            body=html,
                            subtype="html")

    fm = FastMail(conf)
    await fm.send_message(message)
    return JSONResponse(status_code=200,
                        content={"message": "email has been sent"})
Beispiel #30
0
JWT_HASH_ALGORITHM = "HS256"

JWT_ACCESS_TOKEN_EXPIRE_MINUTES = 60 * 2

SECRET_KEY = os.environ.get(
    "SECRET_KEY",
    "09d25e094faa6ca2556c818166b7a9563b93f7099f6f0f4caa6cf63b88e8d3e7")

ALLOWED_ORIGINS = json.loads(os.environ.get("ALLOWED_ORIGINS", "[]"))

_EMAIL_CONF = ConnectionConfig(
    MAIL_USERNAME=os.environ.get("EMAIL_USERNAME", ""),
    MAIL_PASSWORD=os.environ.get("EMAIL_PASSWORD", ""),
    MAIL_FROM=os.environ.get("EMAIL_FROM", "*****@*****.**"),
    MAIL_PORT=int(os.environ.get("EMAIL_PORT", 0)),
    MAIL_SERVER=os.environ.get("EMAIL_SERVER", ""),
    MAIL_TLS=os.environ.get("EMAIL_TLS", "false") != "false",
    MAIL_SSL=os.environ.get("EMAIL_SSL", "false") != "false",
    USE_CREDENTIALS=True,
    TEMPLATE_FOLDER="./app/emails")

FASTAPI_MAIL_INSTANCE = FastMail(_EMAIL_CONF)

TZ = "Asia/Calcutta"

assert isinstance(ALLOWED_ORIGINS, list)


def get_origin_settings():
    """Set CORS Settings According To DEBUG"""
    settings = {