-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathfetch_emails.php
More file actions
77 lines (65 loc) · 2.58 KB
/
fetch_emails.php
File metadata and controls
77 lines (65 loc) · 2.58 KB
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
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
<?php
// Script to fetch emails from Gmail mailbox via IMAP and insert into contact_messages table
// Configuration
$hostname = '{imap.gmail.com:993/imap/ssl}INBOX';
$username = 'booker_library_staff@gmail.com'; // Your Gmail address
$password = 'jbai gevm jtgl ucvx'; // Your Gmail app password
// Connect to mailbox
$inbox = imap_open($hostname, $username, $password) or die('Cannot connect to Gmail: ' . imap_last_error());
// Search for all unseen emails
$emails = imap_search($inbox, 'UNSEEN');
if ($emails) {
include 'connection.php';
foreach ($emails as $email_number) {
// Fetch email overview and body
$overview = imap_fetch_overview($inbox, $email_number, 0)[0];
$structure = imap_fetchstructure($inbox, $email_number);
$message = '';
if (!isset($structure->parts)) {
$message = imap_body($inbox, $email_number);
} else {
// multipart message
foreach ($structure->parts as $part_number => $part) {
if ($part->type == 0) { // text
$message .= imap_fetchbody($inbox, $email_number, $part_number + 1);
}
}
}
// Decode message if base64 or quoted-printable
if ($part->encoding == 3) {
$message = base64_decode($message);
} elseif ($part->encoding == 4) {
$message = quoted_printable_decode($message);
}
// Extract sender email and name
$from = $overview->from;
$from_address = '';
$from_name = '';
if (preg_match('/(.*)<(.+)>/', $from, $matches)) {
$from_name = trim($matches[1], "\" ");
$from_address = $matches[2];
} else {
$from_address = $from;
$from_name = $from;
}
// Prepare data for insertion
$name = $from_name ?: 'Unknown';
$email = $from_address;
$phone = ''; // No phone info from email
$staff_email = $username;
$subject = $overview->subject ?? '';
$date = date('Y-m-d H:i:s', strtotime($overview->date));
// Insert into contact_messages table
$stmt = $db->prepare("INSERT INTO contact_messages (name, email, phone, message, staff_email, submitted_at) VALUES (?, ?, ?, ?, ?, ?)");
if ($stmt) {
$stmt->bind_param("ssssss", $name, $email, $phone, $message, $staff_email, $date);
$stmt->execute();
$stmt->close();
}
// Mark email as seen
imap_setflag_full($inbox, $email_number, "\\Seen");
}
}
imap_close($inbox);
echo "Email fetch completed.\n";
?>