You cannot select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
56 lines
2.0 KiB
Python
56 lines
2.0 KiB
Python
|
1 day ago
|
import base64
|
||
|
|
from email.mime.text import MIMEText
|
||
|
|
|
||
|
|
from fastapi import APIRouter, Depends, HTTPException
|
||
|
|
from pydantic import BaseModel, EmailStr
|
||
|
|
from sqlmodel import Session, select
|
||
|
|
|
||
|
|
from app.core.db import get_session
|
||
|
|
from app.models import GoogleAccount, AuditLog
|
||
|
|
from app.google.client import get_service
|
||
|
|
|
||
|
|
router = APIRouter()
|
||
|
|
|
||
|
|
class SendEmailIn(BaseModel):
|
||
|
|
to: EmailStr
|
||
|
|
subject: str
|
||
|
|
body: str
|
||
|
|
|
||
|
|
def get_account(session: Session, email: str) -> GoogleAccount:
|
||
|
|
acc = session.exec(select(GoogleAccount).where(GoogleAccount.email == email)).first()
|
||
|
|
if not acc:
|
||
|
|
raise HTTPException(status_code=404, detail="Cuenta no autorizada. Primero usa /auth/google/start.")
|
||
|
|
return acc
|
||
|
|
|
||
|
|
@router.get("/profile")
|
||
|
|
def gmail_profile(account_email: str, session: Session = Depends(get_session)):
|
||
|
|
acc = get_account(session, account_email)
|
||
|
|
gmail = get_service("gmail", "v1", acc.token_json)
|
||
|
|
try:
|
||
|
|
profile = gmail.users().getProfile(userId="me").execute()
|
||
|
|
session.add(AuditLog(account_email=account_email, action="gmail_profile", detail="ok"))
|
||
|
|
session.commit()
|
||
|
|
return profile
|
||
|
|
except Exception as e:
|
||
|
|
raise HTTPException(status_code=400, detail=str(e))
|
||
|
|
|
||
|
|
@router.post("/send")
|
||
|
|
def gmail_send(payload: SendEmailIn, account_email: str, session: Session = Depends(get_session)):
|
||
|
|
acc = get_account(session, account_email)
|
||
|
|
gmail = get_service("gmail", "v1", acc.token_json)
|
||
|
|
|
||
|
|
message = MIMEText(payload.body, "plain", "utf-8")
|
||
|
|
message["to"] = payload.to
|
||
|
|
message["subject"] = payload.subject
|
||
|
|
|
||
|
|
raw = base64.urlsafe_b64encode(message.as_bytes()).decode("utf-8")
|
||
|
|
body = {"raw": raw}
|
||
|
|
|
||
|
|
try:
|
||
|
|
sent = gmail.users().messages().send(userId="me", body=body).execute()
|
||
|
|
session.add(AuditLog(account_email=account_email, action="gmail_send", detail=f"to={payload.to}"))
|
||
|
|
session.commit()
|
||
|
|
return {"status": "sent", "id": sent.get("id")}
|
||
|
|
except Exception as e:
|
||
|
|
raise HTTPException(status_code=400, detail=str(e))
|