File size: 2,048 Bytes
4bea261
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
45
46
47
48
49
50
51
52
53
54
55
56
57
import { txasupabase } from '../../../lib/txasupabase.js';

export async function POST({ request, cookies }) {
  const token = cookies.get('auth_token')?.value;
  let user = null;
  if (token) {
    try {
      user = JSON.parse(Buffer.from(token, 'base64').toString('utf-8'));
    } catch (e) {}
  }

  if (!user || user.role !== 'admin') {
    return new Response(
      JSON.stringify({ error: 'Từ chối truy cập! Yêu cầu quyền quản trị viên.' }), 
      { status: 403, headers: { 'Content-Type': 'application/json' } }
    );
  }

  try {
    const { toEmail, smtpOptions } = await request.json();

    if (!toEmail) {
      return new Response(
        JSON.stringify({ error: 'Vui lòng nhập địa chỉ email nhận test!' }), 
        { status: 400, headers: { 'Content-Type': 'application/json' } }
      );
    }

    // Gửi thư test bằng hàm sendMail sử dụng template test_email mới và cấu hình động chưa lưu
    const res = await txasupabase.sendMail({
      to: toEmail,
      subject: 'Thư điện tử thử nghiệm kết nối SMTP - TPHIMX',
      templateName: 'test_email',
      placeholders: {
        username: 'Quản Trị Viên',
        test_time: new Date().toLocaleString('vi-VN', { timeZone: 'Asia/Ho_Chi_Minh' }),
        smtp_host: smtpOptions.smtp_host || 'smtp.gmail.com',
        smtp_port: String(smtpOptions.smtp_port || 465),
        smtp_secure: smtpOptions.smtp_secure || 'SSL',
        smtp_user: smtpOptions.smtp_user || ''
      },
      smtpConfigOverride: smtpOptions
    });

    return new Response(JSON.stringify({ message: 'Gửi email test thành công! Hãy kiểm tra hòm thư của bạn.', data: res }), {
      status: 200,
      headers: { 'Content-Type': 'application/json' }
    });
  } catch (error) {
    console.error('[SMTP Test Error]:', error);
    return new Response(JSON.stringify({ error: 'Gửi thất bại! Lỗi chi tiết: ' + error.message }), {
      status: 500,
      headers: { 'Content-Type': 'application/json' }
    });
  }
}