'Extract Plain Text from Email Body (IMAP Extension)

I'm a bit new to using the IMAP Extension in PHP to check for emails. I don't fully understand all the encoding used in emails. I would like to extract plain text from Multipart messages. I don't need the pictures, formatting and other stuff - just the text.

I've tried using the following code:

$emailBody = imap_fetchbody($connection, $messageNumber, 1);
echo strip_tags($emailBody);

and then I get the following output:

------=_Part_1806898_1525547978.1599580326255 Content-Type: multipart/alternative; boundary="----=_Part_1806899_1364040934.1599580326255" ------=_Part_1806899_1364040934.1599580326255 Content-Type: text/plain; charset=us-ascii Content-Transfer-Encoding: 7bit Welcome Onboard Hi there! A professional email address is the first step to setting up your business. Your email comes with the following cool features - 1 GB storage / mailbox - Built-in calendar - Feature rich webmail - Rich Android / iOS apps - Free trial of video calling - Free trial of read receipts to track your emails - Advanced features like rules, forwarding and auto responders Let's get you started with Flockmail. Happy emailing :) ------=_Part_1806899_1364040934.1599580326255 Content-Type: text/html; charset=utf-8 Content-Transfer-Encoding: quoted-printable Flockmail @import url(http://fonts.googleapis.com/css?family=3DOpen+Sans:800,= 700,400,500,600,300); img + div { display:none; } Hi there! A professio= nal email address is the first step to setting up your business.=20 =20 = = Your email comes with the following cool features = = = = 1GB storage/mailbox = = = = Built-in calendar = = = = Feature rich webmail client = = = = Rich Android/iOS apps = = = = Free trial of video calling = = = = Free trial of read receipts to track your emails = = = = Advanced features like rules, forwarding and = auto responders = =20 = ------=_Part_1806899_1364040934.1599580326255-- ------=_Part_1806898_1525547978.1599580326255--

I'm not sure how to get ride of all the nonsense at the beginning and at the end, and just keep the plain text of the email? I've already searched other posts, none of the solutions here: Extract body text from Email PHP are working for me.



Solution 1:[1]

$emailBody = imap_fetchbody($connection, $messageNumber, 1);

$m= strip_tags($emailBody);

$m1 = preg_replace('/\s+/', ' ', $m);

echo strip_tags($m1);

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Robot