简体   繁体   English

有谁知道我如何读取 PHP 中的电子邮件,然后将它们写入数据库?

[英]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:文档:

  1. https://www.php.net/manual/en/mysqli.query.php https://www.php.net/manual/en/mysqli.query.php
  2. https://docs.laminas.dev/laminas-mail/read/ https://docs.laminas.dev/laminas-mail/read/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 有谁知道我可以在php中找到A *算法的简单版本? - Does anyone know where I can find a simple version of the A* algorithm in php? 有没有人知道跟踪电子邮件读取时间的方法? - Does anyone know a way of tracking how long an email was read? 我是PHP新手,我创建了一个For循环,想知道是否有人知道如何将其重写为while循环? - I'm new to PHP and I created a For loop and would like to know if anyone knows how to re-write it to a while loop? 有谁知道如何在PHP中将序数转换为基数? - Does anyone know how to convert an ordinal to a cardinal number in PHP? 有谁知道如何将此Perl脚本转换为PHP? - Does anyone know how to convert this Perl script into PHP? 有谁知道如何在 smarty 中检查 href 是否等于当前页面链接? - Does anyone know how can i check if href is equal to current page link in smarty? 如何使用 Google Gmail 阅读电子邮件? - How can I read emails with Google Gmail? 我知道PHP的读取,写入和附加…但是可以插入吗? 或删除最后一行? - I know PHP's read, write, and append… but can you insert? or remove last line? 有谁知道Group By如何在CakePHP中与分页一起使用? - Does anyone know how Group By can work with paginate in CakePHP? 无法使用php在数据库上读写 - Can't read or write on database using php
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM