Skip to content

Commit

Permalink
Merge pull request #1 from lapig-ufg/email
Browse files Browse the repository at this point in the history
Email
  • Loading branch information
jairomr authored Oct 1, 2024
2 parents ea16c8f + b037249 commit 43af5b9
Show file tree
Hide file tree
Showing 11 changed files with 381 additions and 46 deletions.
44 changes: 43 additions & 1 deletion app/models/payload.py
Original file line number Diff line number Diff line change
Expand Up @@ -23,4 +23,46 @@ class ResultPayload(BaseModel):
request_user: UserInfo
class PayloadSaveGeojson(BaseModel):
user: User
geojson: LapigFeatureCollectionModel
geojson: LapigFeatureCollectionModel
model_config = {
"user": {
"name": "Jairo Matos da Rocha",
"email": "devjairomr@gmail.com"
},
"geojson": {
"type": "FeatureCollection",
"features": [
{
"type": "Feature",
"properties": {},
"geometry": {
"coordinates": [
[
[
-49.271489630116974,
-16.600834057263143
],
[
-49.271489630116974,
-16.613595063494913
],
[
-49.25488564150811,
-16.613595063494913
],
[
-49.25488564150811,
-16.600834057263143
],
[
-49.271489630116974,
-16.600834057263143
]
]
],
"type": "Polygon"
}
}
]
}
}
4 changes: 4 additions & 0 deletions docker-compose.yml
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,10 @@ services:
- CLIENT_ID=${CLIENT_ID}
- CLIENT_SECRET=${CLIENT_SECRET}
- REALM=${REALM}
- SERVER_EMAIL=${SERVER_EMAIL}
- EMAIL_PORT=${EMAIL_PORT}
- EMAIL_SENDER=${EMAIL_SENDER}
- EMAIL_PASSWORD={EMAIL_PASSWORD}
container_name: jobsgee
privileged: true
ports:
Expand Down
7 changes: 4 additions & 3 deletions pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -5,9 +5,10 @@ description = "Add your description here"
readme = "README.md"
requires-python = ">=3.12"
dependencies = [
"beautifulsoup4>=4.12.3",
"celery>=5.4.0",
"dynaconf>=3.2.6",
"earthengine-api>=1.1.1",
"earthengine-api>=1.1.2",
"fastapi-keycloak-middleware>=1.1.0",
"fastapi>=0.115.0",
"flower>=2.0.1",
Expand All @@ -21,8 +22,8 @@ dependencies = [
"pydantic[email]>=2.9.2",
"pyjwt>=2.9.0",
"pymongo>=4.9.1",
"python-keycloak>=4.4.0",
"python-multipart>=0.0.11",
"python-keycloak>=4.5.0",
"python-multipart>=0.0.12",
"redis>=5.1.0",
"unidecode>=1.3.8",
"uvicorn>=0.31.0",
Expand Down
58 changes: 58 additions & 0 deletions send_email.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,58 @@
import os
import email, smtplib, ssl
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart


from workers.models.email import SendEmail
from workers.render import template
from workers.utils.emial import html_to_text


def send_email(payload: SendEmail):
try:
sender_email = os.environ.get('EMAIL_SENDER')
password = os.environ.get('EMAIL_PASSWORD')
receiver_email = payload['receiver_email']


message = MIMEMultipart("alternative")
message["Subject"] = payload['subject']
message["From"] = sender_email
message["To"] = receiver_email

to_render = payload['message']
html = template.get_template(to_render['template']).render(to_render['content'])

message.attach(MIMEText(html_to_text(html), "plain"))
message.attach(MIMEText(html, "html"))

# Create secure connection with server and send email
context = ssl.create_default_context()
with smtplib.SMTP_SSL(os.environ.get('SERVER_EMAIL'), os.environ.get("EMAIL_PORT",465), context=context) as server:

server.login(sender_email, password)
server.sendmail(
sender_email, receiver_email, message.as_string()
)
except Exception as e:
raise Exception(f"Error sending email: {e} {sender_email} {password} {receiver_email}")
return {"status": "Email sent successfully"}


if __name__ == '__main__':
payload_send_mail ={
"receiver_email": "devjairomr@gmail.com",
"subject": "CONCLUÍDA - Requisição de Análise de Geometria (Área)",
"message":{
"template":"base.html",
"content":{
"title": "CONCLUÍDA - Requisição de Análise de Geometria (Área)",
"hello": f"Olá, Jairo Matos da Rocja",
"body": "Conforme solicitação, a análise de dados da área submetida está completa. Você consegue acessar os resultados no link abaixo:",
"url":"https://atlasdaspastagens.ufg.br/map/123-456-789-000",
"regards":f"Atenciosamente",
"team":"Equipe do Atlas das Pastagens do Brasil"
}
}}
send_email(payload_send_mail)
23 changes: 23 additions & 0 deletions uv.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

27 changes: 25 additions & 2 deletions worker.py
Original file line number Diff line number Diff line change
@@ -1,10 +1,13 @@
import os

from celery import Celery
from workers.send_email import send_email
from workers.gee import task_index_pasture
from app.models.payload import ResultPayload
from celery.utils.log import get_task_logger

from workers.models.email import SendEmail


logger = get_task_logger(__name__)

Expand All @@ -17,6 +20,26 @@

@celery.task(name="gee_get_index_pasture",bind=True)
def gee_get_index_pasture(self, payload: ResultPayload):
return task_index_pasture(self.request.id, payload)
result = task_index_pasture(self.request.id, payload)
payload_send_mail ={
"receiver_email": payload['user']['email'],
"subject": "CONCLUÍDA - Requisição de Análise de Geometria (Área)",
"message":{
"template":"base.html",
"content":{
"title": "CONCLUÍDA - Requisição de Análise de Geometria (Área)",
"hello": f"Olá, {payload['user']['name']}",
"body": "Conforme solicitação, a análise de dados da área submetida está completa. Você consegue acessar os resultados no link abaixo:",
"url":"https://atlasdaspastagens.ufg.br/map/{self.request.id}",
"regards":f"Atenciosamente",
"team":"Equipe do Atlas das Pastagens do Brasil"
}
}}
task_send_email.delay(payload_send_mail)
return result



@celery.task(name="Send Email")
def task_send_email(payload: SendEmail):
logger.info(f"Sending email: ")
return send_email(payload)
36 changes: 0 additions & 36 deletions workers/email.py

This file was deleted.

7 changes: 7 additions & 0 deletions workers/gee.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import os
from workers.utils.gee2chat import get_chat_pasture, get_chat_pasture_vigor
from app.models.payload import ResultPayload
from celery.utils.log import get_task_logger
Expand Down Expand Up @@ -190,4 +191,10 @@ def pasute_vigor_reduce(img):

# Insere o documento na coleção
resultado = colecao.insert_one(result)






return result
15 changes: 13 additions & 2 deletions workers/models/email.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,18 @@
from pydantic import BaseModel, EmailStr
from typing import Optional

class EmailResponse(BaseModel):
title: str
hello : Optional[str]
body: str
url: Optional[str]
regards: Optional[str]
team: str


class MessageHTML(BaseModel):
template_name: str
content: dict
template: str
content: EmailResponse

class SendEmail(BaseModel):
receiver_email: EmailStr
Expand Down
14 changes: 12 additions & 2 deletions workers/render.py
Original file line number Diff line number Diff line change
@@ -1,11 +1,21 @@
from pathlib import Path
from jinja2 import Environment, FileSystemLoader

from glob import glob
# Diretório do script atual
current_directory = Path(__file__).resolve().parent

# Diretório dos templates
templates_directory = current_directory / 'templates'

# Configurando o Jinja2 para carregar templates do diretório
template = Environment(loader=FileSystemLoader(str(templates_directory)))
template = Environment(loader=FileSystemLoader(str(templates_directory)))

if __name__ == '__main__':
# Testando o template
template_vars = {
'title': 'Hello, World!',
'body': 'This is a simple Jinja2 template.',
'team': 'Team!'
}
template_content = template.get_template('base.html').render(template_vars)
print(template_content)
Loading

0 comments on commit 43af5b9

Please sign in to comment.