MIME エンコーディングを使う方法
メール添付やマルチパートメッセージのための MIME(改行付き Base64)のエンコード・デコードを行います。
问题
バイナリファイルをメールに添付する必要があり、特定の行長ルールに従った MIME Base64 エンコードが必要です。
前提条件
- メール構造の基礎理解
- Base64 への習熟
ステップ
-
1. Understand MIME line wrapping
MIME Base64 inserts a CRLF line break every 76 characters. This is required by RFC 2045 for email transport. Standard Base64 encoders may not add these breaks, so you must use a MIME-aware encoder.
入力binary attachment输出Base64 with CRLF every 76 chars -
2. Add MIME headers
Wrap the encoded data with Content-Type, Content-Transfer-Encoding: base64, and Content-Disposition headers. These tell the email client how to decode and present the attachment.
入力image.png输出Content-Type: image/png\nContent-Transfer-Encoding: base64\n\n<iVBOR...> -
3. Decode on the receiving end
A MIME parser reads the headers, strips the CRLF line breaks from the Base64 body, and decodes it back to the original binary. Use a MIME decoder rather than a raw Base64 decoder to handle the line breaks automatically.
入力MIME part输出original file
期待される結果
メールクライアントがデコードして添付ファイルとして表示できる、有効な MIME パート。
よくあるエラー
- Email client shows corrupted attachment
- Ensure line breaks are CRLF (\r\n), not just LF. Some servers reject bare LF.
- Decoder fails on the MIME body
- Strip all whitespace and CRLF before passing to a raw Base64 decoder, or use a MIME-specific decoder.
トラブルシューティング指引
- If the attachment is truncated, check that your mail server does not have a line-length limit below 76.
- Verify the Content-Transfer-Encoding header matches the actual encoding used.
セキュリティ上の制限
- MIME encoding does not encrypt content. Use S/MIME or PGP for confidential attachments.