File size: 1,615 Bytes
e813d54
73a7679
e813d54
73a7679
8504a87
e813d54
 
73a7679
 
 
 
 
 
 
 
 
 
 
 
 
8504a87
73a7679
 
 
8504a87
73a7679
 
43a61d0
73a7679
8504a87
73a7679
8504a87
 
73a7679
531d9ae
43a61d0
8504a87
531d9ae
43a61d0
531d9ae
 
e813d54
73a7679
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
import base64
import os
from email.mime.text import MIMEText
from google.auth.transport.requests import Request
from google.oauth2.credentials import Credentials
from googleapiclient.discovery import build

# Client ID / secret à stocker dans les secrets HF (cf. variables d’environnement du Space)
CLIENT_ID = os.getenv("GMAIL_CLIENT_ID")
CLIENT_SECRET = os.getenv("GMAIL_CLIENT_SECRET")

def authenticate_gmail(sender_email, refresh_token):
    creds_data = {
        "token": "",
        "refresh_token": refresh_token,
        "token_uri": "https://oauth2.googleapis.com/token",
        "client_id": CLIENT_ID,
        "client_secret": CLIENT_SECRET,
        "scopes": ["https://www.googleapis.com/auth/gmail.send"]
    }

    creds = Credentials.from_authorized_user_info(info=creds_data)
    if not creds.valid and creds.expired and creds.refresh_token:
        creds.refresh(Request())

    service = build("gmail", "v1", credentials=creds)
    return service

def send_email(sender_email, to_email, subject, body, refresh_token):
    try:
        service = authenticate_gmail(sender_email, refresh_token)
        message = MIMEText(body)
        message["to"] = to_email
        message["from"] = sender_email
        message["subject"] = subject

        raw_message = base64.urlsafe_b64encode(message.as_bytes()).decode()
        send_body = {"raw": raw_message}

        sent = service.users().messages().send(userId="me", body=send_body).execute()
        return True, f"✅ Email envoyé à {to_email} (ID: {sent['id']})"
    except Exception as e:
        return False, f"❌ Erreur d'envoi : {e}"