Celeskry commited on
Commit
4041115
·
verified ·
1 Parent(s): 08cd7e6

Update app/gm_crate.py

Browse files
Files changed (1) hide show
  1. app/gm_crate.py +45 -31
app/gm_crate.py CHANGED
@@ -1,40 +1,54 @@
1
  import os
2
- import email.message
3
- import aiosmtplib
 
 
 
4
 
5
  class GmailLogic:
6
  def __init__(self):
7
- self.mail_user = os.getenv("GMAIL_USER")
8
- self.mail_pass = os.getenv("GMAIL_PASS")
 
 
 
9
 
10
- async def send_order_email(self, to_email: str, subject: str, customer_name: str, order_id: str, status: str):
11
- if not self.mail_user or not self.mail_pass:
12
- return {"ok": False, "error": "ENV GMAIL_USER/PASS missing"}
 
 
 
 
 
 
 
 
13
 
14
- msg = email.message.EmailMessage()
15
- msg["From"] = self.mail_user
16
- msg["To"] = to_email
17
- msg["Subject"] = subject
 
 
 
 
 
 
 
18
 
19
- content = f"""
20
- <div style="font-family: sans-serif; padding: 20px;">
21
- <h2>Thông báo đơn hàng</h2>
22
- <p>Chào <b>{customer_name}</b>, đơn hàng <b>#{order_id}</b>: <b>{status}</b>.</p>
23
- </div>
24
- """
25
- msg.add_alternative(content, subtype="html")
26
 
27
- try:
28
- # Thay đổi Port sang 587 và dùng STARTTLS
29
- await aiosmtplib.send(
30
- msg,
31
- hostname="smtp.gmail.com",
32
- port=587,
33
- start_tls=True, # Dùng STARTTLS thay vì TLS trực tiếp
34
- username=self.mail_user,
35
- password=self.mail_pass,
36
- timeout=15 # Thêm timeout để không bị treo server
37
- )
38
- return {"ok": True, "message": f"Sent to {to_email}"}
39
  except Exception as e:
40
- return {"ok": False, "error": f"Lỗi kết nối SMTP: {str(e)}"}
 
1
  import os
2
+ import base64
3
+ from email.message import EmailMessage
4
+ from google.oauth2.credentials import Credentials
5
+ from googleapiclient.discovery import build
6
+ from google.auth.transport.requests import Request
7
 
8
  class GmailLogic:
9
  def __init__(self):
10
+ # Bạn cần các biến này trong Secrets của Hugging Face
11
+ self.client_id = os.getenv("GMAIL_CLIENT_ID")
12
+ self.client_secret = os.getenv("GMAIL_CLIENT_SECRET")
13
+ self.refresh_token = os.getenv("GMAIL_REFRESH_TOKEN")
14
+ self.user_email = os.getenv("GMAIL_USER")
15
 
16
+ def get_service(self):
17
+ creds = Credentials(
18
+ None,
19
+ refresh_token=self.refresh_token,
20
+ token_uri="https://oauth2.googleapis.com/token",
21
+ client_id=self.client_id,
22
+ client_secret=self.client_secret,
23
+ )
24
+ # Tự động làm mới token nếu hết hạn
25
+ creds.refresh(Request())
26
+ return build('gmail', 'v1', credentials=creds)
27
 
28
+ async def send_order_email(self, to_email: str, subject: str, customer_name: str, order_id: str, status: str):
29
+ try:
30
+ service = self.get_service()
31
+
32
+ # Tạo email chuẩn
33
+ message = EmailMessage()
34
+ message.set_content(f"Chào {customer_name}, đơn hàng {order_id} của bạn: {status}")
35
+
36
+ # Nội dung HTML
37
+ html_content = f"<h2>Thông báo đơn hàng</h2><p>Chào <b>{customer_name}</b>, đơn hàng <b>#{order_id}</b> của bạn đã <b>{status}</b>.</p>"
38
+ message.add_alternative(html_content, subtype='html')
39
 
40
+ message['To'] = to_email
41
+ message['From'] = self.user_email
42
+ message['Subject'] = subject
 
 
 
 
43
 
44
+ # Mã hóa base64 đúng chuẩn Gmail API
45
+ raw_message = base64.urlsafe_b64encode(message.as_bytes()).decode()
46
+
47
+ create_message = {'raw': raw_message}
48
+
49
+ # Gửi qua HTTP POST (Cổng 443)
50
+ service.users().messages().send(userId="me", body=create_message).execute()
51
+
52
+ return {"ok": True, "message": "Gửi qua Gmail API thành công!"}
 
 
 
53
  except Exception as e:
54
+ return {"ok": False, "error": f"Gmail API Error: {str(e)}"}