habulaj commited on
Commit
fb14018
·
verified ·
1 Parent(s): 31f4ac1

Update routes/emails.py

Browse files
Files changed (1) hide show
  1. routes/emails.py +44 -13
routes/emails.py CHANGED
@@ -1,6 +1,7 @@
1
  import base64
2
  import aiohttp
3
- from fastapi import APIRouter, HTTPException, Query
 
4
  from google.auth.transport.requests import Request
5
  from google.oauth2.credentials import Credentials
6
  from email.mime.text import MIMEText
@@ -16,6 +17,11 @@ SENDER_NAME = "Ameddes"
16
 
17
  SCOPES = ['https://www.googleapis.com/auth/gmail.send']
18
 
 
 
 
 
 
19
  def get_access_token():
20
  creds = Credentials(
21
  None,
@@ -28,16 +34,46 @@ def get_access_token():
28
  creds.refresh(Request())
29
  return creds.token
30
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
31
  async def send_email_gmail(to_email: str, subject: str, body_html: str):
32
  access_token = get_access_token()
33
 
34
- # Cria o objeto MIMEText com charset utf-8 para o corpo HTML
35
  msg = MIMEText(body_html, 'html', 'utf-8')
36
  msg['To'] = to_email
37
  msg['From'] = formataddr((SENDER_NAME, EMAIL_ADDRESS))
38
  msg['Subject'] = subject
39
 
40
- # Codifica a mensagem em base64 urlsafe para a API Gmail
41
  raw_message = base64.urlsafe_b64encode(msg.as_bytes()).decode()
42
 
43
  url = "https://gmail.googleapis.com/gmail/v1/users/me/messages/send"
@@ -45,9 +81,7 @@ async def send_email_gmail(to_email: str, subject: str, body_html: str):
45
  "Authorization": f"Bearer {access_token}",
46
  "Content-Type": "application/json"
47
  }
48
- payload = {
49
- "raw": raw_message
50
- }
51
 
52
  async with aiohttp.ClientSession() as session:
53
  async with session.post(url, headers=headers, json=payload) as resp:
@@ -55,11 +89,8 @@ async def send_email_gmail(to_email: str, subject: str, body_html: str):
55
  if resp.status != 200:
56
  raise HTTPException(status_code=resp.status, detail=f"Gmail API error: {response_text}")
57
 
58
- @router.get("/send-email")
59
- async def send_email_route(
60
- to: str = Query(...),
61
- subject: str = Query(...),
62
- content: str = Query(...)
63
- ):
64
- await send_email_gmail(to, subject, content)
65
  return {"detail": "Email enviado com sucesso!"}
 
1
  import base64
2
  import aiohttp
3
+ from fastapi import APIRouter, HTTPException
4
+ from pydantic import BaseModel
5
  from google.auth.transport.requests import Request
6
  from google.oauth2.credentials import Credentials
7
  from email.mime.text import MIMEText
 
17
 
18
  SCOPES = ['https://www.googleapis.com/auth/gmail.send']
19
 
20
+ class EmailRequest(BaseModel):
21
+ to: str
22
+ subject: str
23
+ type: str # Tipo do email para definir conteúdo
24
+
25
  def get_access_token():
26
  creds = Credentials(
27
  None,
 
34
  creds.refresh(Request())
35
  return creds.token
36
 
37
+ def generate_email_html(email_type: str, to: str) -> str:
38
+ # Defina aqui os templates HTML para cada tipo de email
39
+ if email_type == "welcome":
40
+ return f"""
41
+ <html>
42
+ <body>
43
+ <h1>Bem-vindo ao Streamify!</h1>
44
+ <p>Olá {to}, estamos muito felizes em ter você conosco.</p>
45
+ <p>Aproveite a experiência completa!</p>
46
+ </body>
47
+ </html>
48
+ """
49
+ elif email_type == "goodbye":
50
+ return f"""
51
+ <html>
52
+ <body>
53
+ <h1>Sentiremos sua falta!</h1>
54
+ <p>Olá {to}, sentimos muito que você esteja saindo.</p>
55
+ <p>Se quiser voltar, estaremos aqui!</p>
56
+ </body>
57
+ </html>
58
+ """
59
+ # Template padrão
60
+ return f"""
61
+ <html>
62
+ <body>
63
+ <h1>Olá!</h1>
64
+ <p>Este é um email automático do Streamify.</p>
65
+ </body>
66
+ </html>
67
+ """
68
+
69
  async def send_email_gmail(to_email: str, subject: str, body_html: str):
70
  access_token = get_access_token()
71
 
 
72
  msg = MIMEText(body_html, 'html', 'utf-8')
73
  msg['To'] = to_email
74
  msg['From'] = formataddr((SENDER_NAME, EMAIL_ADDRESS))
75
  msg['Subject'] = subject
76
 
 
77
  raw_message = base64.urlsafe_b64encode(msg.as_bytes()).decode()
78
 
79
  url = "https://gmail.googleapis.com/gmail/v1/users/me/messages/send"
 
81
  "Authorization": f"Bearer {access_token}",
82
  "Content-Type": "application/json"
83
  }
84
+ payload = {"raw": raw_message}
 
 
85
 
86
  async with aiohttp.ClientSession() as session:
87
  async with session.post(url, headers=headers, json=payload) as resp:
 
89
  if resp.status != 200:
90
  raise HTTPException(status_code=resp.status, detail=f"Gmail API error: {response_text}")
91
 
92
+ @router.post("/send-email")
93
+ async def send_email_route(email_req: EmailRequest):
94
+ html_content = generate_email_html(email_req.type, email_req.to)
95
+ await send_email_gmail(email_req.to, email_req.subject, html_content)
 
 
 
96
  return {"detail": "Email enviado com sucesso!"}