When we retrieve messages from a mail server we will have two parts, on the one hand we will obtain a summary with the subject of the message and information about the person who sent it and in a second step we will have the content of the message. In this example we are going to obtain the body of a message with PHP.
To do this, the first thing we will do is connect via imap to the mail server using the function
.
imap_open()
To the function
we give you the server name, username and password to connect.
imap_open()
$hostname = '{mail.mail.com/notls}INBOX';
$username = '[email protected]';
$password = 'password';
$inbox = imap_open($hostname,$username,$password) or die('Connection failed: ' . imap_last_error());
Once we have connected to the mail server we must recover the emails from one of the mailboxes, in this case we are going to recover all the emails from the main mailbox using the function
.
imap_search()
$emails = imap_search($inbox,'ALL');
In the variable $emails
we will have all the emails from the main mailbox. Now we are going to obtain the body of one of the messages, specifically, and as an example we will do it from the first message.
The function that helps us obtain the body of a message with PHP is imap_fetchbody()
. This function receives four parameters:
imap_fetchbody($stream_mails, $message_number, $section, $options);
The $stream_mails
are all the emails obtained through
,
imap_search()
$message_number
is the message number within the list, the first number will be 1.
With respect to $section
what we will be able to collect is either the header, whose value would be 0, or what would be the body of the message whose value would be 1.
In this way the code that would recover the message body of the first message would be:
$body = imap_fetchbody($inbox,1,1);
The content of the message body will be encoded, so we must use the imap_qprint()
function to dump the content.
echo imap_qprint($body);
We will only have to close the imap connection to the server to finish our example that allows us to obtain the body of a message with PHP.
imap_close($inbox);