Home » Php » php – how to decode the subject in an email?

php – how to decode the subject in an email?

Posted by: admin July 12, 2020 Leave a comment


I have send a mail with Subject line as

[BILLING #PHY-945-49853]: [Ticket #12622] Payment Method

But in the source of the message the line is like below


It is encoded in Base64. How can I decode it back to the original subject line in English using php? I have tried with the php base64_decode($subject) but it does not decode it to the original subject ([BILLING #PHY-945-49853]: [Ticket #12622] Payment Method)

I’m also attaching a sample email message:

Return-Path: .........
X-Original-To: ..........
Delivered-To: ........
Received: ......
X-DKIM: ........
To: ....
From: =?UTF-8?B?U0FWVllFSE9TVElORyBTQUxFUw==?=
X-Priority: ..
X-MSMail-Priority: normal
X-MimeOLE: Produced By Kayako Fusion v4.01.204
X-Mailer: Kayako Fusion v4.01.204
Reply-To: .......
Date: .....
Content-Type: multipart/alternative;
MIME-Version: 1.0
Message-Id: ....

This is a message in MIME Format. If you see this, your mail reader does not support this format.

Content-Type: text/plain;
Content-Transfer-Encoding: quoted-printable
Content-Disposition: inline

Support Center:
Content-Type: text/html;
Content-Transfer-Encoding: quoted-printable
Content-Disposition: inline
How to&Answers:

You’re probably looking for iconv_mime_decode.

From the link:

string iconv_mime_decode ( string $encoded_header [, int $mode = 0 [, string $charset = 
ini_get("iconv.internal_encoding") ]] )

Decodes a MIME header field.

Your example:

echo iconv_mime_decode($string);


Subject: [SALES #BBN-935-37917]: [Ticket #12622] Payment


I also had this issue and came up with an alternate route to resolve this. For anyone else looking in the future, this may be of some assistance.

I pieced this code together once I realised which part of the message is actually the Base64 portion of the string;

if(stripos($subject, "=?utf-8?b?") !== false) {
    $output = str_ireplace("=?utf-8?B?", "", $subject);
    $output = str_replace("==?=", "", $output);
    $output = base64_decode($output);
    $output = $subject;

Effectivly what you are doing is detecting that the string is in face base64. and then trimming the identifiers before decoding it with base64_decode()

Ensure you use the case-insensitive versions of the string functions as not all mail providers stick with upper or lower case.

**Sorry to respond to an old question but I found this a more useful alternative.