Bert Maurau
Bert Maurau

Reputation: 979

Best way to store Email-body in database

I'm working on some sort of application where I can get emails from my inbox via a cron job, where i just insert mail-from, mail-subject and mail-body into a MySQL database.

The problem i'm having is with the different mailtypes like HTML mails, plain text mails,..

Is there a way to get just the text? I've tried with fetchbody and HTML entitites, printable_decode but that results in sometimes an empty body insert or one with all special characters or sometimes perfect.

    //$body = mysqli_real_escape_string($db, htmlentities(quoted_printable_decode(imap_fetchbody($stream,$email_id, 1.2)), ENT_QUOTES));
$body = mysqli_real_escape_string($db, quoted_printable_decode(imap_fetchbody($stream,$email_id, 1.2)));
//$body = quoted_printable_decode(imap_fetchbody($stream,$email_id,2));
$bodyText = imap_fetchbody($stream,$email_id,1.2);
if(!strlen($bodyText)>0){
    $bodyText = "<html><body>".imap_fetchbody($stream,$email_id,1)."</body></html>";
}

Then i've tried with full html body, but that gives problems with inserting into my database and if I escape string, the HTML gets messy. I temporarly fixed it by getting the full HTML body and writing that to a .html file, but that's not really an option.

The reason why i store them into a MySQL database is so I can assign users, colors,.. to different mails (Which isn't an option with iMAP mails in Outlook for ex.)

My ultimate idea is to save the emails, just like it shows in outlook and then showing them exactly like that on a .php page, but it isn't always that easy.

Maybe i'm tackling this issue completely the wrong way, but maybe you guys have some tips, ideas or something?

Thanks in advance, Bert

Upvotes: 4

Views: 6231

Answers (1)

Robert
Robert

Reputation: 20286

If emails are sent properly there should be plain text and HTML but it is an ideal world.

So I suggest you to.

  1. Escape strings for MySQL
  2. Remove potentially danger html tags like script etc. with strip_tags

When showing to user

  1. Unescape data from MySQL
  2. Show stripped data.

You can also use eml parser and save eml files in DB.

Check:

Upvotes: 1

Related Questions