[英]Does anyone know how I can read emails in PHP and then write them to a database?
I'm doing an internship right now and I'm supposed to implement the question from above.我现在正在实习,我应该从上面实施问题。 On google I find nothing that fits.
在谷歌上我找不到合适的东西。 I need help that emails are read (with the help of Imap), then written into a database (mysql).
我需要帮助读取电子邮件(在 Imap 的帮助下),然后写入数据库 (mysql)。 Unfortunately I have no idea how to do this, so I turn to you.
不幸的是,我不知道该怎么做,所以我求助于你。 Thanks in advance.
提前致谢。
I don't know how this works, I have no idea where to start.我不知道这是如何工作的,我不知道从哪里开始。 I am glad about help!
我很高兴能得到帮助!
This was an Attempt:这是一次尝试:
<?php
// POP3-Server
$host="xxx";
$port=" 993";
// User-Daten
$user="xxx";
$passwort="xxx";
// Verbinden zur Mailbox
$mailbox=imap_open("{".$host."/imap: 993}INBOX",$user,$passwort);
// Überprüfen ob Verbindung erfolgreich
if ($mailbox)
{
// Posteingang überprüfen
$check=imap_check($mailbox);
// Anzahl vorhandener Emails im Postfach
$count_msg=$check->Nmsgs;
// Anzahl neuer Emails im Postfach
$count_new_msg=$check->Recent;
// Emails auslesen
for ($i=1; $i<=imap_num_msg($mailbox);
$i++)
{
// Header erfassen
$mail_header=imap_header($mailbox, $i);
// Datum erfassen
$mail_date=$mail_header->Date;
// Mail-ID erfassen
$mail_id=$mail_header->message_id;
// Empfänger erfassen
$mail_to=$mail_header->toaddress;
// Absendername erfassen
$mail_from_name=$mail_header->from [0]->personal;
// Absender-eMail-Adresse erfassen
$mail_from_address=$mail_header->from [0]->mailbox."@".$mail_header->from [0]->host;
// Kopieempfänger erfassen
$mail_copy_to=$mail_header->cc[0] ->mailbox."@".$mail_header->cc[0] ->host;
// Antwortempfänger erfassen
$mail_answer_to=$mail_header->reply_to;
// Betreff erfassen
$mail_subject=$mail_header->subject;
// Nachricht erfassen
$mail_body = imap_body($mailbox,$i);
// Daten in db speichern
include ("config.inc.php");
$eintrag = "INSERT INTO bsi_statistik (komponente, anzahlmeldungen, datumletztemeldung, mailsin30tagen) VALUES ('$komponente', '$mail_from_address', '$mail_subject', '$mail_date', '$mail_body')";
$eintragen = mysql_query($eintrag);
echo "e-Mail Nr.".$i."<br>";
// Ausgabe in HTML
echo '<b>Versendet am:</b> ';
echo $mail_date."<br>";
echo '<b>Eindeutige eMail-ID: </b>';
echo $mail_id."<br>";
echo '<b>Empfänger: </b>';
echo $mail_to."<br>";
echo '<b>"Name des Absenders: </b>';
echo $komponente."<br>";
echo '<b>"eMail des Absenders: </b>';
echo $mail_from_address."<br>";
// echo $mail_from_address."<br>";
echo '<b>Betreff: </b>';
echo $mail_subject."<br><br>";
echo '<b>Nachricht: </b>';
echo $mail_body."<br><br>";
// E-Mail löschen löschen
imap_delete($mailbox, $i);
}
imap_expunge($mailbox);
imap_close($mailbox);
}
?>
Updated with example from additional information provided by OP使用 OP 提供的附加信息中的示例进行了更新
The easiest way to achieve this would be to do the following.实现此目的的最简单方法是执行以下操作。 This example uses the following database schema:
此示例使用以下数据库架构:
create table incoming_emails
(
id int auto_increment,
date_sent datetime null,
headers json null,
`from` varchar(191) null,
subject text null,
content longtext null,
constraint incoming_emails_pk
primary key (id)
);
Use Composer to import a new library, laminas/mail
:使用 Composer 导入新库
laminas/mail
:
composer install laminas/mail
After doing so, mail can be retrieved and iterated over like so:这样做之后,可以像这样检索和迭代邮件:
<?php
use Laminas\Mail\Storage\Imap;
require_once 'vendor/autoload.php';
// Connecting with Imap:
$mail = new Imap([
'host' => 'example.com',
'user' => 'test',
'password' => 'test',
]);
echo $mail->countMessages() . " messages found\n";
foreach ($mail as $message) {
printf("Mail from '%s': %s\n", $message->from, $message->subject);
}
You can then persist to a database using the MySQLi class:然后,您可以使用 MySQLi class 持久化到数据库:
<?php
use Laminas\Mail\Storage\Imap;
require_once 'vendor/autoload.php';
// Do all configuration here.
// Database:
$dbHost = 'localhost';
$dbUsername = 'root';
$dbPassword = 'RANDOM_PASSWORD';
$dbName = 'my_database';
// Email inbox to query:
$emailHost = 'localhost';
$emailPort = 995;
$emailUsername = 'email@example.com';
$emailPassword = 'SECRET_STRING_HERE';
// Do not edit below this line.
$mysqli = new MySQLi($dbHost, $dbUsername, $dbPassword, $dbName);
// If cannot connect to MySQL database, throw an error.
if ($mysqli->connect_error) {
throw new \Exception('Could not connect to database!');
}
// Connecting with Imap:
$mail = new Imap([
'host' => $emailHost,
'user' => $emailUsername,
'password' => $emailPassword,
'port' => $emailPort,
]);
echo $mail->countMessages() . " messages found\n";
// Prepare a query.
$query = 'INSERT INTO `incoming_emails` (`date_sent`, `headers`, `from`, `subject`, `content`)';
// Prepare all emails for input to SQL database.
$mailParser = new MailMimeParser();
foreach ($mail as $message) {
$queryData[] = [
'from' => $mysqli->real_escape_string($message->getHeader('reply-to') ?? $message->getHeader('from')),
'headers' => $mysqli->real_escape_string(json_encode($message->getHeaders())),
'subject' => $mysqli->real_escape_string($message->getSubject()),
'content' => $mysqli->real_escape_string($message->getContent()),
];
// Left in for debug:
printf("Mail from '%s': %s\n", $message->from, $message->subject);
}
$query .= 'VALUES (' . implode('), (', $queryData) . ')';
$mysqli->query($query);
echo 'Done';
Please ensure you also include good database input sanitisation.请确保您还包括良好的数据库输入清理。
This is provided as-is, with no testing done so its not confirmed to work exactly.这是按原样提供的,没有进行任何测试,因此无法确认其是否可以正常工作。 You likely will need to update this for your own needs and is provided as an educational example only.
您可能需要根据自己的需要对其进行更新,并且仅作为教育示例提供。
Docs:文档:
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.