2008年4月11日金曜日

POP で受け取ったメールのデコード方法

http://www.nsoftware.com/kb/showentry.aspx?entry=06170422

該当製品:


  • IP*Works!


現象:


メッセージ受信の際に、POP オブジェクトから受け取ったメッセージがエンコードされています。どうしてこのようにエンコードされたままなのでしょうか。また、そのメッセージを市販の製品と同じように表示するにはどうすればよいのでしょうか。

解決法:


平文より複雑なメッセージは MIME エンコードされます。アタッチメントや HTML パート、インラインイメージやフォーマット済み文書は単一のエンティティにエンコードされます。これらのメッセージはメールクライアントによってデコードされるまでは MIME 形式のままです。POP サーバから受け取ったメッセージを対応するパートへとデコードするには、MIME オブジェクトを使用する必要があります。MIME エンコーディングは何階層にもカプセル化することができるため、MIME エンティティが埋め込まれていることを検出した場合は自分自身を呼び出し可能な再起呼び出しルーチンを使いと思うでしょう。以下に示すのは MIME デコード用の一般用途向けのルーチンです。このルーチンを、POP の MessageHeaders と MessageText の値を使って呼び出すことになります。
Private Sub MimeDecode(ByVal EntityHeaders As String, ByVal Entity As String)
Dim Mime1 As New nsoftware.IPWorks.Mime
Dim i As Integer
Mime1.MessageHeaders = EntityHeaders
Mime1.Message = Entity
Try
Mime1.DecodeFromString()
Catch
'If an error is encountered, the entity is not a valid MIME entity
Exit Sub
End Try
For i = 0 To Mime1.PartCount - 1
'If the Content-Type is "Multipart/????", then that part is an encoded entity
'You will want to call this routine again
If LCase(Mime1.PartContentType(i)).StartsWith("multipart") Then
MimeDecode(Mime1.PartHeaders(i), Mime1.PartDecodedString(i))
End If

'If a part is text/plain and is not an attachment, it is generally
'the plain text body of the message
If Mime1.PartFilename(i) = "" And LCase(Mime1.PartContentType(i)) = "text/plain" Then
'Display your text here; you'll want to read from
Mime1.PartDecodedString(i)
End If

'If you're going to support HTML messages, you'll want to look for this
'part, and if found, use it in place of the plain text
If LCase(Mime1.PartContentType(i)) = "text/html" Then
'Again, read from Mime1.PartDecodedString(i) to access
End If

'External attachments show up with a content-disposition of "attachment"
If LCase(Mime1.PartContentDisposition(i)) = "attachment" Then
'Mime1.PartFilename(i) will contain the name of the file.
'To actually get the file itself, you must read the value of
'Mime1.PartDecodedFile(i). Doing so will return the name of a
'temporary file that contains the file data; this file will not
'be created until PartDecodedFile is queried. Once you have the name
'of a temporary file with the data, simply rename the file to the
'location and name of where you wish to save the file
End If

'Inline data that are sent in the email will generally have a
'content-ID header and a content-disposition of "inline"
If LCase(Mime1.PartContentID(i)) <> "" Then
'Treat these cases as you would external attachments. The HTML that
'is returned will include CID tags that should correspond with this
'data, or you can simply save the images as you would an attachment
'if you do not wish to support HTML
End If
Next
End Sub

0 件のコメント: