解码邮件编码的单词=?utf-8?B?xxxx?=,=?utf-8?Q?xxxx?=

时间:2019-05-16 17:22:08

标签: vb.net

是否可以解码已编码的电子邮件主题?我知道这样做的肮脏方法是获取=?utf-8?B之间的字符串字符。 xxx?=并将其解码。但是我有一个程序,可以获取诸如

2 0
_ _ _
_ _ _
X _ _

现在我正在做这样的事情

=?utf-8?Bxxxx?= =?UTF-8?B?xxxx?= ...

但是,当同一字符串具有多个=?utf-8?B?时,此方法将不起作用。像上面一样编码。我也可以使用=?utf-8?Q编码和=?windows-1252获得字符串。有没有办法解决所有这些编码?我正在使用Visual Studios 2017

1 个答案:

答案 0 :(得分:0)

使用此功能解码电子邮件字段值从未遇到麻烦:

它为类型B或Q查找匹配的utf-8字符串,如果类型B,则运行FromBase64String。 我确定您可以针对Windows-1252进行操作。

Private Function DecodeEmailField(byVal strString as String) as String
    DecodeEmailField = strString.toString()
    Dim strMatch

    Dim arrEncodeTypes = New String() {"B","Q"}
    Dim strEncodeType as String
    For Each strEncodeType in arrEncodeTypes    

        Dim objRegexB as RegEx = new RegEx("(?:\=\?utf\-8\?" & strEncodeType & "\?)(?:.+?)(?:\?=\s)", _
            RegexOptions.Multiline or RegexOptions.IgnoreCase)          

        if (objRegexB.IsMatch(DecodeEmailField)) then
            Dim thisMatch as Match = objRegexB.Match(DecodeEmailField)      
            For Each strMatch in thisMatch.Groups
                Dim strMatchHold as String = strMatch.toString().Substring(("=?utf-8?" & strEncodeType & "?").length)   
                strMatchHold = strMatchHold.SubString(0,(strMatchHold.Length)-("?= ".Length))

                If strEncodeType = "B" Then
                    Dim data() As Byte = System.Convert.FromBase64String(strMatchHold)
                    strMatchHold = System.Text.UTF8Encoding.UTF8.GetString(data)    
                End If                                          

                DecodeEmailField = Replace(DecodeEmailField,strMatch.toString(),strMatchHold)

            Next
        End If  
    Next        

End Function