Rfc 1521 mime multipurpose internet mail extensions

MIME – Multipurpose Internet Mail Extensions

Internet standard MIME is able to extend the e-mail format for the purpose to support the following things as text, non-text attachment, a message organization with manifold parts and non-ASCII header information. The existence of MIME protocol has become very important because SMTP as basic e-mail transmission protocol can support only 7-bit of ASCII characters set. But MIME as Presentation layer protocol can hold up 8-bit binary content by describing the ways of sending certain types of data via an electronic mail. But data types are including that text other than English language too, files with images, sounds, or movies, etc. MIME also specified about the set of e-mail’s headers to facilitate a message additional attributes specification, which may include content type, and description of transfer encoding set. MIME is as well specified the set of laws and non-ASCII character’s encoding in the message headers of e-mail. But when RFC 822-style header’s practice is being made for the attributes of MIME message then without making any change to on hand email servers, plain texted e-mails are permitted to play their role in both directions with reachable clients. But all this is possible when MIME headers are declared optional.

Anyway, following RFCs are mentioned here for your better understanding regarding the subject. RFC 1426 is dealt with 8bit MIME transportation. But RFC 1847 specifies the MIME security multiparts while RFC 3156 describes MIME security by means of OpenPGP. Similarly, RFC 2183 is dealt with the information regarding communicating presentation in e-mail messages. RFC 2387 is related with MIME multipart or related content-type but RFC 1521 covers that mechanism specifies the Internet Messaging Bodies format. Extensible MIME definition is included a scheme to schedule fresh contents types and attribute values of MIME.

Typical Header fields of MIME

Header’s typical fields are as under:

    MIME-Version such a

ut all of MIME headers must include comments enclosed within parentheses such as following comment like

can be added with MIME version specification

  • Content-Type is not necessary with RFC 2045 confirmed document. But MIME parser is requisite a top ranked Content-Type.
  • Syntax of MIME header can be mentioned below as:

Both type and as well subtype is used to define the type of content. But all other not obligatory parameters will be surrounded by semicolons. Following table is displayed with some common values of Content-Type.



text/xml Used along with SwA . application/xml Utilized for xml data that is application specific. multipart/signed Employed for several related parts within a message. multipart/mixed Employed for various self-sufficient parts within a message.
  • Content Transfer Encoding header’s field is utilized to point out the form of transformation with which this data type is encoded into a 7-bit set-up.
  • Content-ID is an optional field, which facilitates parts labeling.
  • Content-Description is an optional field, which facilitates parts depiction.

MIME encodings is performed in the form of base64 and quoted-printable encoding according to RFC 1521. In case of base64, the actual data is divided into 3 octets groups but quoted-printable encoding is suitable for the data included printable characters as 33-60 characters range and 62-126 characters range.

MIME Multipurpose Internet Mail Extensions RFC 1521

OpublikowałKsenia Dziekoński Został zmieniony 5 lat temu

Podobne prezentacje

Prezentacja na temat: «MIME Multipurpose Internet Mail Extensions RFC 1521″— Zapis prezentacji:

1 MIME Multipurpose Internet Mail Extensions RFC 1521
Michał Rajkowski Jan Dudziec

2 Plan prezentacji Definicja MIME MIME, a inne RFC Format wiadomości
Pola nagłówka Typy zawartości Podsumowanie RFC MIME

3 Definicja MIME MIME — Multipurpose Internet Mail Extensions
— Standard poczty elektronicznej — Mechanizmy specyfikacji i opisu formatu zawartości wiadomości internetowych RFC 1521 Uzupełnia wcześniejsze publikacje i rozszerza standardy o mechanizmy pozwalające na przesyłanie różnych typów zawartości RFC MIME

4 Wcześniejsze publikacje (1)
RFC 822 – Standard opisujący format wiadomości internetowych (1982r.) Treść: — Protokół reprezentacji wiadomości — Specyfikacja nagłówka — Format i zawartość wiadomości – 7 bitowy kod ASCII Wady: — wiadomości tekstowe – brak formatowania (czcionek itp) — wiadomości nie tekstowe – odrzucane lub konwertowane na ASCII -> utrata informacji RFC MIME

5 Wcześniejsze publikacje (2)
RFC 1341 i RFC 1342 – pierwsze publikacje i definicje MIME RFC MIME (Multipurpose Internet Mail Extensions): Mechanisms for Specifying and Describing the Format of Internet Message Bodies RFC Representation of Non-ASCII Text in Internet Message Headers RFC 1521 zostało wprowadzone, aby zastąpić RFC 1341, RFC 1342. RFC MIME

6 RFC 1521 RFC MIME (Multipurpose Internet Mail Extensions) Part One: Mechanisms for Specifying and Describing the Format of Internet Message Bodies Zmiana formatu wiadomości Opis mechanizmów pozwalających na przesyłanie obiektów różnego typu bez straty informacji Zawartość specyfikacji: Version Header Field Content-Type Header Field Content-Transfer-Encoding Header Field Additional Content-Header Fields Content-ID Header Field Content-Description Header Field RFC MIME

7 Format wiadomości HEADER < BODYPART Bodypart header <
MIME-version: 1.0 Content-type: multipart/mixed; boundary=»frontier» This is a multi-part message in MIME format. —frontier Content-type: text/plain Content-type: application/octet-stream Content-transfer-encoding: base64 Pgh0bWw+CiAgPGhlYWQ+CiAgPC9oZWF kPgogIDxib2R5PgogICAgPHA+VGhpcyBpc yB0aGugYm9keSBvZiB0aGUgbWVzc2FnZ S48L3A+CiAgPC9ib2R5Pgo8L2h0bWw+Cg= —frontier— BODYPART Bodypart header < Bodypart header < Body < RFC MIME

8 MIME-Version Header Field
Nowe pole nagłówka Określa numer wersji formatu zawartości wiadomości Wartość dla standardu zgodnego z RFC1521: Ogólna postać: MIME-Version: 1.0 version := «MIME-Version» «:» 1*DIGIT «.» 1*DIGIT RFC MIME

9 Content-Type Header Field
content := «Content-Type» «:» type «/» subtype *(«;» parameter) type := «application» / «audio» / «image» / «message»/ «multipart» / «text» / «video» / extension-token extension-token := x-token / iana-token iana-token :=

10 Content-Transfer-Encoding Header Field
encoding := «Content-Transfer-Encoding» «:»mechanism Nowo zdefiniowane pole Wskazuje typ transformacji ciała wiadomości użyty na potrzeby transportu wiadomości Domyślna wartość — “7bit” Część nagłówka wiadomości i nagłówka ciała wiadomości mechanism := «7bit» «quoted-printable» «base64» «8bit» «binary» x-token Przykład: Content-Type: text/plain; charset=ISO Content-transfer-encoding: base64 RFC MIME

11 Content-Transfer-Encoding Header Field
“7bit”,”8bit”,”binary” => brak kodowania Quoted-printable Standardowo do przesyłania tekstu Drukowalne znaki ASCII Znaki o kodach >127 -> 3 znaki Przykład: Ó (ISO ) => “=F3” Base64 stosowany głownie do plików binarnych (grafika, dźwięk) możliwy do zastosowania także dla zwykłego tekstu RFC MIME

12 Content-Transfer-Encoding Header Field
The Base64 Alphabet RFC MIME

13 Additonal Content-Header Fields
Optional Content-ID Header Field Etykieta zawartości Analogiczne wykorzystanie jak “Message-ID” Obowiązkowy dla typu “message/external-body” Optional Content-Description Header Field Opisowe informacje Standardowo w postaci US-ASCII, RFC-1522 posiada mechanizm pozwalający na korzystanie z innego kodowania niż US-ASCII Przykład: Description := “Content-Description “:” *text RFC MIME

14 Typy zawartosći Text Multipart Message Application Image Audio Video
Experimental RFC MIME

15 TEXT Zasadniczo do przesyłania zawartości tekstowej
CHARSET — krytyczny parametr używany do zdefiniowania podtypów Domyślnie — “text/plain;charset=us-ascii” Zdefiniowane wartości charset: US-ASCII, ISO-8859-X Przykład: text-type := «text» «/» text-subtype [«;» «charset» «=» charset] text-subtype := «plain» charset := «us-ascii»/ «iso «/ «iso «/ «iso » / «iso «/ «iso «/ «iso «/ «iso » / «iso » / «iso » RFC MIME

16 MULTIPART Umożliwia przesyłanie kilku różnych typów danych w 1 wiadomości Każda część to osobne “bodypart” z osobnym nagłówkiem Enkapsulacja- każda część oddzielona granicami boundary := 0*69 bcharsnospace W przypadku wystapienia średnika „:” — Dozwolone kodowania- “7bit”, “8bit”, “binary” Podtyp: “mixed” (podstawowy),“alternative”, “digest”, ”parallel” Content-Type: multipart/mixed; boundary=gc0p4Jq0M2Yt08jU534c0p RFC MIME

17 MULTIPART-przykład From: Nathaniel Borenstein
To: Ned Freed Subject: Formatted text mail MIME-Version: 1.0 Content-Type: multipart/alternative; boundary=boundary42 —boundary42 Content-Type: text/plain; charset=us-ascii —TEKST niesformatowany—- Content-Type: text/richtext —TEKST w fromacie richtext— Content-Type: text/x-whatever —Oryginalna postać tekstu—- —boundary42— RFC MIME

18 MESSAGE Dołączenie innej wiadomości
Możliwe podtypy: “rfc822”, “partial” , “external- body” Wymaga kodowania “7bit”, “8bit”,”binary” Message header: us-ascii (zawsze) Partial – umożwilia przesyłanie duży obiektów podzielonych na części (łączenie po “content-id”) External-body-obowiązkowy parametr “acces-type” Parametry opcjonalne: “expiration”, “size”,”permission”, “name”,”site”, “directory”,”mode”, “server”,”subject” RFC MIME

19 MESSGE-przykład 1 X-Weird-Header-1: Foo From: Bill@host.com
To: Subject: Audio mail Message-ID: MIME-Version: 1.0 Content-type: message/partial; number=1; total=2 X-Weird-Header-1: Bar X-Weird-Header-2: Hello Message-ID: Content-type: audio/basic Content-transfer-encoding: base64 Message-ID: number=2; total=2 RFC MIME

20 Message-przykład 2 From: Whomever To: Someone Subject: whatever
MIME-Version: 1.0 Message-ID: Content-Type: multipart/alternative; boundary=42 Content-ID: —42 Content-Type: message/external-body; name=»BodyFormats.ps»; site=»thumper.bellcore.com»; access-type=ANON-FTP; directory=»pub»; mode=»image»; expiration=»Fri, 14 Jun :13: (EDT)» Content-type: application/postscript Content-ID: access-type=mail-server get RFC-MIME.DOC —42— RFC MIME

21 APPLICATION Przesyłanie danych nie zakwalifikowanych do pozostałych kategorii Przetwarzanie zawartosci przed pokazaniem jej uzytkownikowi Podtypy: “octet-stream”(dane binarne), “Postscript”(program napisany w jezyku Postscript/Postscript2 – Adobe Systems Inc.) “octet-stream” — parametry: “type”, “padding” Kolejne typy mają być zdefiniowane w przyszłości RFC MIME

22 IMAGE, AUDIO, VIDEO IMAGE Do przesyłania obrazów
Podtyp- format obrazu: “jpeg”, “gif” itp. AUDIO Podstawowy podtyp “basic”- kodowanie 8 bitowe [PCM] VIDEO Do przesyłania plików video (dopuszczalnie z dźwiękiem) Podtyp- format video: “mpeg” RFC MIME

23 EXPERIMENTAL Eksperymentalne podtypy Zaczynają się na “X-”
Formaty bez jednoznacznej i publicznej definicji Prywatne wartości Odradza się tworzenie nowych typów – powinno się stosować rozszerzanie już istniejących RFC MIME

24 Zasady korzystania z MIME
Agent pocztowy używający MIME musi: Zawsze tworzyć pole “»MIME-Version: 1.0″” Rozpoznawać “Content-Transfer-Encoding” i przeprowadzić odpowiednie dekodowanie Rozpoznawać i odpowiednio prezentować dane inne niż “text” “Text”- wyświetlać za pomocą US-ASCII, jak nie zna podtypu to prezentować nieprzetworzone dane, rozpoznawać “charset”, rozpoznawać “ISO-8859-X” “Message”- rozpoznawać podtyp “822” “Multipart”- rozpoznawać podtyp “mixed” i “alternative” “Application”- rozpoznawać podtyp i umieszczać zawartość w pliku RFC MIME

25 Podsumanie MIME jest powszechnie stosowanym standardem do przesyłania i przetwarzania wiadomości RFC 1521 jest pierwszym i podstawowym dokumentem opisującym przesyłanie różnych typów wiadomości Dalsze wersje: RFC Multipurpose Internet Mail Extensions (MIME) Part One: Format of Internet Message Bodies RFC 2046-Multipurpose Internet Mail Extensions (MIME) Part Two: Media Types RFC MIME (Multipurpose Internet Mail Extensions) Part Three: Message Header Extensions for Non-ASCII Text RFC 2048-Multipurpose Internet Mail Extensions (MIME) Part Four: Registration Procedures RFC 2049-Multipurpose Internet Mail Extensions (MIME) Part Five: Conformance Criteria and Examples RFC MIME

26 Pytania na kolokwium W przypadku stosowania Quoted-printable, co się dzieje gdy mamy znak o wartości większej od 127 Nie jest on przesyłany Jest kodowany za pomocą 3 znaków Ani a), ani b) Co jest typem podstawowym dla Multipart? Parallel Mixed Digest Czy możemy ustawić (dla typu zawartości Message) message header inny niż us-ascii? Tak, jeżeli użyjemy kodowania 7 bit Tak, jeżeli użyjemy kodowania 8bit lub binary RFC MIME

Rfc 1521 mime multipurpose internet mail extensions

Network Working Group
Request for Comments: 1521
Obsoletes: 1341
Category: Standards Track

N. Borenstein
N. Freed
September 1993

MIME (Multipurpose Internet Mail Extensions) Part One:
Mechanisms for Specifying and Describing
the Format of Internet Message Bodies

Status of this Memo

This RFC specifies an Internet standards track protocol for the Internet community, and requests discussion and suggestions for improvements. Please refer to the current edition of the «Internet Official Protocol Standards» for the standardization state and status of this protocol. Distribution of this memo is unlimited.


STD 11, RFC 822 defines a message representation protocol which specifies considerable detail about message headers, but which leaves the message content, or message body, as flat ASCII text. This document redefines the format of message bodies to allow multi-part textual and non-textual message bodies to be represented and exchanged without loss of information. This is based on earlier work documented in RFC 934 and STD 11, RFC 1049, but extends and revises that work. Because RFC 822 said so little about message bodies, this document is largely orthogonal to (rather than a revision of) RFC 822.

Илон Маск рекомендует:  Что такое код asp httperrors

In particular, this document is designed to provide facilities to include multiple objects in a single message, to represent body text in character sets other than US-ASCII, to represent formatted multi- font text messages, to represent non-textual material such as images and audio fragments, and generally to facilitate later extensions defining new types of Internet mail for use by cooperating mail agents.

This document does NOT extend Internet mail header fields to permit anything other than US-ASCII text data. Such extensions are the subject of a companion document [RFC-1522].

This document is a revision of RFC 1341. Significant differences from RFC 1341 are summarized in Appendix H.

Table of Contents

Next: 1. Introduction Connected: An Internet Encyclopedia
RFC 1521

Rfc 1521 mime multipurpose internet mail extensions

STD 11, RFC 822, defines a message representation protocol specifying considerable detail about US-ASCII message headers, and leaves the message content, or message body, as flat US-ASCII text. This set of documents, collectively called the Multipurpose Internet Mail Extensions, or MIME, redefines the format of messages to allow for: (1) textual message bodies in character sets other than US-ASCII, (2) an extensible set of different formats for non-textual message bodies, (3) multi-part message…

What is MIME ( Multi-Purpose Internet Mail Extensions )

What is MIME?

The MIME stands for Multi-Purpose Internet Mail Extensions. As the name indicates, it is an extension to the Internet email protocol that allows it’s users to exchange different kinds of data files over the Internet such as images, audio, and video. The MIME is required if text in character sets other than ASCII. Virtually all human-written Internet email and a fairly large proportion of automated email is transmitted via SMTP in MIME format. Actually, MIME was designed mainly for SMTP, but the content types defined by MIME standards are important also in communication protocols outside of email, such as HTTP. In 1991, Nathan Borenstein of Bellcore proposed to the IETF that SMTP be extended so that Internet (but mainly Web) clients and servers could recognize and handle other kinds of data than ASCII text. As a result, new file types were added to “mail” as a supported Internet Protocol file type.

MIME Working

The web servers insert the MIME header at the beginning of any Web transmission. Clients use this content type or media type header to select an appropriate “player” application for the type of data the header indicates.

MIME headers

Now, let’s see the MIME headers. There are many sub parts come under MIME headers. Let’s see each in detail.


MIME-Version header is used to indicate that the message is MIME formatted. This header is having a value of “1.0” typically. So this header will be as follows.

eg: MIME-Version: 1.0

When the MIME was developed, the developers had a plan to further issue the newer versions, but the problems caused by changes in a standard discouraged further release of the same.


This header is used to describe the content type of the message. The Content-Type header includes the type and a sub-type parts.

eg: Content-Type: text/plain

Through the use of the multi-part type, MIME allows mail messages to have parts arranged in a tree structure where the leaf nodes are any non-multipart content type and the non-leaf nodes are a variety of multi-part types. This mechanism supports:

1) Simple text messages using text/plain (the default value for “Content-Type: “).

2) Text plus attachments (multipart/mixed with a text/plain part and other non-text parts). A MIME message including an attached file generally indicates the file’s original name with the “Content-disposition:” header, so the type of file is indicated both by the MIME content-type and the (usually OS-specific) filename extension.

3) Reply with original attached (multipart/mixed with a text/plain part and the original message as a message/rfc822 part).

4) Alternative content, such as a message sent in both plain text and another format such as HTML (multipart/alternative with the same content in text/plain and text/html forms).

5) Image, audio, video, and application (for example, image/jpeg, audio/mp3, video/mp4, and application/msword and so on).

6) Many other message constructs.


The original MIME specifications only described the structure of mail messages. They did not address the issue of presentation styles. The content-disposition header field was added in RFC 2183. It specifies the presentation style.

There are two types of Content-Disposition:

1) Inline Content-Disposition

2) Attachment Content-Disposition

Inline Content-Disposition

The Inline Content-Disposition would be automatically displayed when the message is shown.

Attachment Content-Disposition

The Attachment Content-Disposition will not be displayed automatically. It needs the user action to get opened and displayed.

The content-disposition header also provides fields for specifying the name of the file, the creation date, and modification date, which can be used by the reader’s mail user agent to store the attachment.

eg: Content-Disposition: attachment; filename=genome.jpeg;

modification-date=”Wed, 12 Feb 1997 16:29:51 -0500″;

Now a day, a good majority of mail user agents do not follow this prescription fully. The widely used Mozilla Thunderbird mail client makes its own decisions about which MIME parts should be automatically displayed, ignoring the content-disposition headers in the messages. Thunderbird prior to version 3 also sends out newly composed messages with inline content-disposition for all MIME parts.

Many mail user agents also send messages with the file name in the name parameter of the content-type header instead of the filename parameter of the content-disposition header. This practice is discouraged – the file name should be specified either through just the filename parameter, or through both the filename and the name parameters.


In June 1992, MIME (RFC 1341) defined a set of methods for representing binary data in formats other than ASCII text format. The content-transfer-encoding: MIME header has 2-sided significance:

It indicates whether or not a binary-to-text encoding scheme has been used on top of the original encoding as specified within the Content-Type header:

1) If such a binary-to-text encoding method has been used, it states which one.

2) If not, it provides a descriptive label for the format of content, with respect to the presence of 8-bit or binary content.

The RFC and the IANA’s list of transfer encodings define the values shown below, which are not case sensitive. Note that ‘7bit’, ‘8bit’, and ‘binary’ mean that no binary-to-text encoding on top of the original encoding was used. In these cases, the header is actually redundant for the email client to decode the message body, but it may still be useful as an indicator of what type of object is being sent. Values ‘quoted-printable’ and ‘base64’ tell the email client that a binary-to-text encoding scheme was used and that appropriate initial decoding is necessary before the message can be read with its original encoding (e.g. UTF-8).

Suitable for use with normal SMTP:

1) 7bit – up to 998 octets per line of the code range 1..127 with CR and LF (codes 13 and 10 respectively) only allowed to appear as part of a CRLF line ending. This is the default value.

2) quoted-printable – used to encode arbitrary octet sequences into a form that satisfies the rules of 7bit. Designed to be efficient and readable when used for text data consisting primarily of US-ASCII characters, but also containing a small proportion of bytes with values outside that range.

3) base64 – used to encode arbitrary octet sequences into a form that satisfies the rules of 7bit. Designed to be efficient for non-text 8 bit and binary data. It is sometimes used for text data that frequently uses non-US-ASCII characters.

Suitable for use with SMTP servers that support the 8BITMIME SMTP extension (RFC 6152):

1) 8bit – up to 998 octets per line with CR and LF (codes 13 and 10 respectively) only allowed to appear as part of a CRLF line ending.

2) Suitable for use with SMTP servers that support the BINARYMIME SMTP extension (RFC 3030):

3) Binary – any sequence of octets.


Since RFC 2822, conforming message header names and values should be ASCII characters. Values that contain non-ASCII data should use the MIME encoded-word syntax (RFC 2047) instead of a literal string. This syntax uses a string of ASCII characters indicating both the original character encoding (the “charset”) and the content-transfer-encoding used to map the bytes of the charset into ASCII characters.

The form is: “=?charset?encoding?encoded text?=”.

charset: The charset can be any character set registered with IANA. Typically, it would be the same charset as the message body.

encoding: The encoding can be either “Q” denoting Q-encoding that is similar to the quoted-printable encoding, or “B” denoting base64 encoding.

encoded text: The encoded text is the Q-encoded or base64-encoded text.

encoded-word: An encoded-word may not be more than 75 characters long, including charset, encoding, encoded text, and delimiters. If it is desirable to encode more text than will fit in an encoded-word of 75 characters, multiple encoded-words (separated by CRLF SPACE) may be used.

If you need any further assistance please contact our support department.

Standard MIME (Multipurpose Internet Mail Extensions)

MIME (Multipurpose Internet Mail Extensions) è uno standard proposto dai laboratori Bell Communications nel 1991 per estendere le possibilità limitate della posta elettronica (mail) e soprattutto per permettere di inserire dei documenti (immagini, suoni, testo, ecc.) in un messaggio. È definito all’origine dai RFC 1341 e 1342 del giugno 1992.

Introduzione al MIME

MIME propone di descrivere, grazie a delle intestazioni, il tipo di contenuto del messaggio e la codifica usata. MIME apporta alla messaggeria le seguenti funzionalità: possibilità d’avere più oggetti (allegati) in uno stesso messaggio, una lunghezza di messaggio illimitata, l’uso di set di caratteri (alfabeti) oltre a quelli del codice ASCII; l’uso di testi arricchiti (sotto forma di messaggi, tipi di carattere, colori, ecc.) e di allegati binari (eseguibili, immagini, file audio o video, ecc.), eventualmente composti da più parti.

MME usa delle direttive d’intestazione specifiche per descrivere il formato utilizzato nel corpo di un messaggio, per permettere al client di messaggeria di poterlo interpretare correttamente:

MIME-Version, si tratta della versione dello standard MIME usata nel messaggio. Attualmente esiste solo la versione 1.0;

Content-type, descrive il tipo e i sotto-tipi di dati. Può avere un parametro « charset », separato da un punto virtuale, che definisce il set di caratteri usati;

Content-Transfer-Encoding, definisce la decodifica usata nel corpo del messaggio;

Content-ID, rappresenta un identificativo unico di parte del messaggio;

Content-Description, fornisce delle informazioni complementari sul contenuto del messaggio;

Content-Disposition, definisce i parametri dell’allegato, soprattutto il nome associato al file attraverso l’attributo filename.

Principali Tipi MIME

Il type MIME, usato nell’intestazione Content-Type, è utilizzato per classificare i documenti allegati ad un messaggio. Un type MIME è costituito nel modo seguente: . Ad esempio, un’immagine GIF avrà il seguente type MIME: .

I principali tipi di dati, detti talvolta, tipi di dati discreti, sono i seguenti:

Text, dati testuali leggibili. text/rfc822 [RFC822]; text/plain [RFC2646]; text/html [RFC2854] .

Image, dati binari che rappresentano delle immagini digitali image/JPEG; image/GIF; image/PNG.

Audiom dati digitali sonori audio/basic; audio/WAV.

Video, dati video, video/MPEG.

Application, altri dati binari, application/octet-stream; application/PDF.

Il type MIME è anche usato nel Web, per classificare i documenti trasferiti dal protocollo HTTP. Al momento di una transazione tra un server web e un navigatore internet, il server invia in primo luogo il type MIME del file inviato al navigatore, affinché quest’ultimo possa sapere come visualizzare il documento.

Formati di codifica

Per trasferire dei dati binari, MIME propone cinque formati di codifica utilizzabili nell’intestazione Transfer-encoding:

7bit, formato testo codificato su 7 bit (per i messaggi non accentuati);

8bit, formato test 8 bit;

quoted-printable, formato Quoted-Printable, raccomandato per i messaggi che usano un alfabeto codificato su più di 7 bit (ad esempio presenza di accenti);

base64, formato Base 64, raccomandato per l’invio di file binari in allegato;

binary, formato binario, sconsigliato.

MIME, essendo molto aperto, permette di usare altri formati di codifica come i seguenti:

BinHex (formato proprietario di Apple);

Decodifica dell’intestazione

L’uso dell’intestazione Transfer-encoding permette di precisare un formato di decodifica per il corpo del messaggio, ma non risolve il problema della decodifica delle intestazioni stesse (ad esempio l’oggetto del messaggio).

Илон Маск рекомендует:  Сообщение об ошибке

Così, per permettere di decodificare le intestazioni con degli alfabeti di più di 7 bit, e permettere ad esempio d’avere un oggetto della mail accentuato, lo standard MIME propone il formato seguente: .

Charset rappresenta il set di carattere usato;

Decodifica definisce la decodifica voluta con due valori possibili:

Q per quoted-printable;

Risultato: testo codificato secondo il metodo specifico. Ecco qui sotto un esempio di codifica in Quoted-Printable con «Realtà» come oggetto del messaggio:

Messaggi compositi

Attraverso il type MIME multipart lo standard MIME permette di definire dei messaggi compositi, cioè dei messaggi con più allegati, eventualmente inclusi. Per fare questo, MIME permette di definire un separatore detto boundary. Si tratta di una catena arbitraria definita nell’attributo dell’intestazione Content-type:

Ogni separatore delimita un contenuto cominciando dalle intestazioni Content-Type e Content-Encoding. È essenziale che il valore di questo separatore non esista nel contenuto del messaggio. Esistono differenti tipi di separatore:

Multipart/mixed definisce una lista di più elementi;

Multipart/alternative definisce diverse alternative per una stessa informazione, ad esempio un messaggio in formato testo e HTML. Se il client di messaggeria è capace ed è configurato per la visualizzazione con un formato, visualizzerà la versione HTML, altrimenti userà la versione testo.

Multipart/parallel definisce dei dati presentati nello stesso momento (suono e immagine ad esempio);

Multipart/signed definisce una firma digitale per i dati del messaggio;

Multipart/related definisce delle informazioni legate fra loro.

Liste dei tipi MIME

I tipi MIME sono normalizzati da un organismo chiamato IANA (Internet Assigned Numbers Authority). Ecco una lista non esaustiva dei tipi MIME più diffusi:

Tipo MIME Tipo di file Estensione associata
application/atom+xml File di formato ATOM atom
application/iges FileCAS iges
application/javascript File Javascript js
application/dxf File AutoCAD dxf
application/mp4 File MPEG4 mp4
application/iges Formato di scambio CAO IGES igs,iges
application/octet-stream File binari non interpretati bin
application/msword File da lavoro in formato Microsoft Word doc
application/pdf File Adobe Acrobat pdf
application/postscript File PostScript ai,eps,ps
application/rtf Formato di testo arricchito rtf
application/sgml File SGML sgml
application/vnd.ms-excel File tabellari in formato Microsoft Excel xls
application/vnd.ms-powerpoint File presentazione in formato Microsoft Powerpoint ppt
application/xml fichier XML xml
application/x-tar File compressi tar tar
application/zip File compressi ZIP man
audio/basic File audio basici au,snd
audio/mpeg File audio MPEG mpg,mp3
audio/mp4 File audio MPEG-4 mp4
audio/x-aiff File audio AIFF aif,aiff,aifc
audio/x-wav File audio Wave wav
image/gif Immagini gif man
image/jpeg Immagini JPEG jpg,jpeg,jpe
image/png Immagini PNG png
image/tiff Immagini Tiff tiff,tif
image/x-portable-bitmap File Bitmap PBM pbm
image/x-portable-graymap File Graymap PBM pgm
image/x-portable-pixmap File Pixmap PBM ppm
multipart/x-zip File archivio zip zip
multipart/x-gzip File archivio GNU zip gz,gzip
text/css Fogli di stile css
text/csv File di testo con separazione dei valori csv
text/html File HTML htm,html
text/plain File di testo senza formattazione txt,g,h,c,cc,hh,m,f90
text/richtext File di testo arricchiti rtx
text/rtf File di testo in formato Rich Text Format rtf
text/tab-separated-value File di testo con separazione di valori tsv
text/xml Files XML xml
video/h264 Video H.264 h264
video/dv Video in formato DV dv
video/mpeg Video MPEG mpeg,mpg,mpe
video/quicktime Video QuickTime qt,mov
video/msvideo Video Microsoft Windows avi

Ulteriori informazioni

RFC 2045, MIME Part One, Format of Internet Message Bodies;

RFC 2046, MIME Part Two, Media Types;

RFC 2047, MIME Part Three: Message Header Extensions for Non-ASCII Text;

RFC 2048, MIME Part Four: Registration Procedures;

RFC 2049, MIME Part Five: Conformance Criteria and Examples.

RFC 1524, The formal description of mailcap files. Mailcap files describe how to handle media types;

RFC 2015, MIME Security with Pretty Good Privacy (PGP);

RFC 2110, MIME E-mail Encapsulation of Aggregate Documents, such as HTML (MHTML);

RFC 2111, Content-ID and Message-ID Uniform Resource Locators;

RFC 2112, The MIME Multipart/Related Content-type;

RFC 2183, Defines the syntax and sematics of the «Content-Disposition» header to convey presentational information;

RFC 2184, MIME Parameter Value and Encoded Word Extensions: Character Sets, Languages, and Continuations.

Системное программное обеспечение

7.1 Что такое MIME?

MIME означает «Multipurpose Internet Mail Extensions» (Многоцелевые расширения почтового стандарта Internet). Этот стандарт описывает, как пересылать по электронной почте исполняемые, графические, мультимедийные, смешанные данные. Типичные применения MIME — пересылка графических изображений, аудио, документов Word, программ и даже просто текстовых файлов, то есть, когда важно, чтобы входе пересылки не производилось никаких преобразований над данными. MIME также позволяет размечать письмо на части различных типов так, чтобы получатель (почтовая программа) мог определить, что делать с каждой из частей письма.

Хотя формат первоначально создан для электронной почты, он также используется для службы WWW.

7.2 Для чего это нужно?

Так как файлы могут быть разными (.gif, .doc, .pdf . ), браузер должен понимать, что с ними делать. Эту проблему решает стандарт «MIME — типы». Он сообщает клиенту, какой тип файлов получен, например:
Content-type: image/gif (графика GIF)
Content-type: image/jpeg (графика JPG)

7.3 Как это работает?

Браузеры используют MIME-типы в своих HTTP-заголовках Accept для того, чтобы сообщить, в каких форматах они предпочитают принимать данные (если сервер может выдать файл в разных форматах). Серверы используют MIME-типы в HTTP-заголовках Content-Type, чтобы сообщить клиенту о том, в каком формате передается прилагаемое содержимое: то ли это HTML, который нужно форматировать, то ли это GIF или JPEG, требующий визуализации, то ли это данные в формате PDF, для которого нужно открывать внешнюю программу просмотра или использовать дополнительное приложение.

Формат MIME-типа — тип/подтип. Можно использовать символ *; например, следующий заголовок клиента означает, что принимаются документы во всех форматах:

Следующий заголовок клиента означает, что принимаются все типы формата text независимо от подтипа:

Серверы должны проверять данные о принимаемых типах, содержащиеся в заголовке Accept, и по возможности выдавать данные соответствующего типа. Большинство серверов определяют формат документа по расширению имени файла. Например, файлы с расширениями .htm и .html — это файлы в формате HTML, поэтому сервер посылает такой документ с типом text/html в заголовке Content-Type, пример:

Действия клиента при получении файла:

При получении клиентом файла, анализируется HTTP заголовок, если в нем находится Content-Type, то клиент производит действие с файлом, учитывая эту информацию.

Если записи нет, то клиент использует свой список MIME-типов, в котором тип определяется по расширению имени файла.

Если тип в файле не найден, то клиент не знает что делать с этим файлом. Браузер в таком случае предлагает вам выбрать сами программу, которой надо передать файл.

7.4 Некоторые основные типы и подтипы MIME.

Первый стандарт — RFC1341 MIME (Multipurpose Internet Mail Extensions): Mechanisms for Specifying and Describing the Format of Internet Message Bodies N. Borenstein, N. Freed June 1992

Последняя версия (состоит из четырех частей) :

RFC2049 (Multipurpose Internet Mail Extensions (MIME) Part Five: Conformance Criteria and Examples N. Freed, N. Borenstein November 1996)

RFC2048 (Multipurpose Internet Mail Extensions (MIME) Part Four: Registration Procedures N. Freed, J. Klensin, J. Postel November 1996)

RFC2047 (MIME (Multipurpose Internet Mail Extensions) Part Three: Message Header Extensions for Non-ASCII Text K. Moore November 1996)

RFC2046 (Multipurpose Internet Mail Extensions (MIME) Part Two: Media Types N. Freed, N. Borenstein November 1996)

RFC2045 (Multipurpose Internet Mail Extensions (MIME) Part One: Format of Internet Message Bodies N. Freed, N. Borenstein November 1996)

Text – текстовые типы.

Тип ‘text’ предназначен для пересылки текстовых материалов. Для обозначения языковой кодировки текста используется параметр «charset» для некоторых подтипов, включая подтип, «text/html», соответствующий простому (неформатированному) тексту.

Content-Type: text/html; charset=windows-1251

Основные подтипы:
Content-Type: text/html — html текст.
Content-Type: text/plain — простой текст.
Content-Type: text/x-server-parsed-html — файл созданный с помощью SSI
Content-Type: text/css — файл содержащий стили — css

Multipart — данные состоят из несколько частей разных типов.

Основные подтипы:
Content-Type: multipart/mixed — несколько частей разных типов (используется в e-mail)
Content-Type: multipart/alternative — одна из частей (используется в e-mail)
Content-Type: multipart/x-mixed-replace — после загрузки следующая часть заменяет предыдущею (используется в анимации)

Message — инкапсулированное почтовое сообщение (используется в e-mail)

Image — графические типы.

Основные подтипы:
Content-Type: image/gif — изображение gif.
Content-Type: image/jpeg — изображение jpeg.
Content-Type: image/tiff — изображение tiff.
Content-Type: image/bmp — изображение bmp

Audio — звуковые типы.

Основные подтипы:
Content-Type: audio/wav — звук в формате wav.
Content-Type: audio/midi — звук в формате midi
Content-Type: audio/mpeg — звук в формате mp3.
Content-Type: audio/vqf — звук в формате vqf
Content-Type: audio/x-pn-realaudio — звук в формате ram rm
Content-Type: audio/x-realaudio — звук в формате ra
Content-Type: audio/x-wav — звук в формате wav

Основные подтипы:
Content-Type: video/avi — видео в формате avi.
Content-Type: video/mpeg — видео в формате mpeg.

Application — представляет данные какого-нибудь приложения.

application/msword – приняв такое сообщение, браузер запустит MS Word для открытия этих данных. Если в системе нет MS Word, то браузер попросит сохранить данные в файле имя файла может находиться в параметре name. Например:

Content-Type: application/msword; name=”Mydoc.doc”

Основные подтипы:
Content-Type: application/msword — программа MS Word
Content-Type: application/pdf — программа Acrobat Reader
Content-Type: application/rtf — программа MS Word
Content-Type: application/zip — разархиватор ZIP-архивов

7.5 Серверные приложения.

Приложения на сервер можно использовать для создания счетчиков, форумов, чатов, обработки статистики, организации доступа к базам данных и т.д.

Для этого нужно чтобы клиенты могли запускать или работать с приложениями на сервере.

7.5.1 Методы использования серверных приложений.

Запуск через CGI-шлюз. Эти приложения могут быть написаны на любых языках.
— используются обычные программы (в случае Windows .bat, .exe и тд.)
— стандартизовано
— при каждом вызове программы происходит ее запуск, что не есть быстро, и при большом количестве запросов, появляется много запущенных программ.

Приложения, встроенные в сервер HTTP, как модули. Как правило, написанные на С.
— быстрота (т.к. всегда работает, не нужен запуск).
— необходимость писать модуль для конкретного сервера HTTP.

Приложения, работающие через модули-шлюзы встроенные в сервер HTTP.
— шлюз написан для конкретного приложения (например, для СУБД MySQL)
— необходимость писать модул-шлюз для конкретного приложения.

Приложения, написанные на скриптовых языках (SSI, PERL, PHP, ASP и др.), для выполнения которых должны быть встроенные интерпретаторы, как модули сервера HTTP. Код этих приложений встраивается непосредственно в HTML страницы. Сервер распознает эти страницы по расширению (.php, .asp, .shtml, .pl).
— быстрота (выше чем у CGI, но ниже чем у модуля, т.к. интерпретаторы).
— удобно использовать
— ограниченность возможностей

Приложения, работающие через Java Servlet.
— платформо-независимость
— серверо-независимость
— приложения на Java работаю медленнее

Приложения, написанные на Java и встроенные в HTML страницы (с расширением .JSP (JavaServer Pages)). В принципе это аналог скриптовых языков работающих через модуль (в место модуля в данном случае Java Servlet, а язык Java)
— платформо-независимость
— серверо-независимость
— удобно использовать
— приложения на Java работаю медленнее

7.5.2 Архитектура WWW сервера с учетом серверных приложений

Архитектура современного WWW сервера. На выходе с сервера всегда HTML, но сгенерированный приложением.

7.5.3 Примеры запросов к приложениям

В результате через CGI шлюз

Будет запущено приложение search.cgi

и будет передан запрос «text=сотрудники» приложению search.cgi

Приложение search.cgi вернет результат работы CGI-шлюзу

Будет передан запрос «text=сотрудники» интерпретатору PHP.

Интерпретатор будет выполнять команды search.php.

Интерпретатор вернет результат работы WWW-серверу.

Common Gateway Interface — стандарт для обмена данными между сервером и прикладной программой, которая запускается из-под сервера.

7.6.1 Механизмы обмена данными

Механизм можно разделить на четыре части: Переменные окружения

При запуске внешней программы сервер создает специфические переменные окружения, через которые передает приложению, как служебную информацию, так и данные.

SERVER_NAME — определяет доменное имя сервера.

GATEWAY_INTERFACE — определяет версию протокола CGI.

SERVER_PROTOCOL — протокол сервера.

SERVER_SOFTWARE — версия сервера.

SERVER_PORT — определяет порт, по которому осуществляется взаимодействие.

REQUEST_METHOD — определяет метод, значения GET, POST, HEAD и т. п.

PATH_INFO — передает программе путь с переменными, часть URL переданный клиентом (т.е. относительный путь с переменными).

PATH_TRANSLATED — абсолютный путь, путь расположения программы на диске сервера.
Пример для запроса http://ipm.kstu.ru/cgi-bin/search?text=ipm:
PATH_INFO = «/cgi-bin/search?text=ipm»
PATH_TRANSLATED = «/usr/local/etc/httpd/cgi-bin/search».

SCRIPT_NAME — относительный путь без переменных.
Пример для запроса http://ipm.kstu.ru/cgi-bin/search?text=ipm:
PATH_INFO = «/cgi-bin/search?text=ipm»
SCRIPT_NAME = «/cgi-bin/search»

QUERY_STRING — переменная определяет содержание запроса к скрипту (все что после ?).
Пример для запроса http://ipm.kstu.ru/cgi-bin/search?text=ipm:
QUERY_STRING —— «text=ipm»

Идентификация пользователя и его машины:

REMOTE_HOST — доменный адрес машины клиента.

REMOTE_ADDR — IP-адрес машины клиента.

AUTH_TYPE — тип идентификации пользователя.

Илон Маск рекомендует:  func_get_args - Возвращает массив аргументов функции

REMOTE_USER — используется для идентификации пользователя.

REMOTE_IDENT — данная переменная порождается сервером, если он поддерживает идентификацию пользователя по протоколу RFC-931. Рекомендовано использование этой переменной для первоначального использования скрипта.

Тип и длина передаваемой информации от клиента к серверу.

CONTENT_TYPE — определяет MIME-тип данных.

CONTENT_LENGTH — определяет размер данных в байтах.

Переменные заголовка HTTP.



HTTP_HOST — поле HOST. Командная строка

Командная строка используется только при запросах типа ISIN-DEX.

Rfc 1521 mime multipurpose internet mail extensions

qprint is a command line utility which encodes and decodes files in this format. It can be used within a pipeline as an encoding or decoding filter, and is most commonly used in this manner as part of an automated mail processing system. With appropriate options, qprint can encode pure binary files, but it’s a poor choice since it may inflate the size of the file by as much as a factor of three. The Base64 MIME encoding is a better choice for such data.




Please report bugs and documentation errors to [email protected].


This software is in the public domain. Permission to use, copy, modify, and distribute this software and its documentation for any purpose and without fee is hereby granted, without any conditions or restrictions. This software is provided «as is» without express or implied warranty.

Rfc 1521 mime multipurpose internet mail extensions

GMime is a C/C++ library which may be used for the creation and parsing of messages using the Multipurpose Internet Mail Extension (MIME), as defined by the following RFCs:

  • 0822: Standard for the Format of Arpa Internet Text Messages
  • 1341: MIME (Multipurpose Internet Mail Extensions): Mechanisms for Specifying and Describing the Format of Internet Message Bodies
  • 1342: Representation of Non-ASCII Text in Internet Message Headers
  • 1521: MIME (Multipurpose Internet Mail Extensions) Part One: Mechanisms for Specifying and Describing the Format of Internet Message Bodies (Obsoletes rfc1341)
  • 1522: MIME (Multipurpose Internet Mail Extensions) Part Two: Message Header Extensions for Non-ASCII Text (Obsoletes rfc1342)
  • 1544: The Content-MD5 Header Field
  • 1847: Security Multiparts for MIME: Multipart/Signed and Multipart/Encrypted
  • 1864: The Content-MD5 Header Field (Obsoletes rfc1544)
  • 2015: MIME Security with Pretty Good Privacy (PGP)
  • 2045: Multipurpose Internet Mail Extensions (MIME) Part One: Format of Internet Message Bodies
  • 2046: Multipurpose Internet Mail Extensions (MIME) Part Two: Media Types
  • 2047: Multipurpose Internet Mail Extensions (MIME) Part Three: Message Header Extensions for Non-ASCII Text
  • 2048: Multipurpose Internet Mail Extensions (MIME) Part Four: Registration Procedures
  • 2049: Multipurpose Internet Mail Extensions (MIME) Part Five: Conformance Criteria and Examples
  • 2183: Communicating Presentation Information in Internet Messages: The Content-Disposition Header Field
  • 2184: MIME Parameter Value and Encoded Word Extensions: Character Sets, Languages, and Continuations
  • 2231: MIME Parameter Value and Encoded Word Extensions: Character Sets, Languages, and Continuations (Obsoletes rfc2184)
  • 2311: S/MIME Version 2 Message Specification
  • 2312: S/MIME Version 2 Certificate Handling
  • 2315: PKCS #7: Cryptographic Message Syntax
  • 2630: Cryptographic Message Syntax
  • 2632: S/MIME Version 3 Certificate Handling (Obsoletes rfc2311)
  • 2633: S/MIME Version 3 Message Specification (Obsoletes rfc2312)
  • 2634: Enhanced Security Services for S/MIME
  • 2822: Internet Message Format (Obsoletes rfc0822)
  • 3156: MIME Security with OpenPGP (Updates rfc2015)
  • 3850: S/MIME Version 3.1 Certificate Handling (Obsoletes rfc2632)
  • 3851: S/MIME Version 3.1 Message Specification (Obsoletes rfc2633)
  • 5322: Internet Message Format (Obsoletes rfc2822)
  • 5750: S/MIME Version 3.2 Certificate Handling (Obsoletes rfc3850)
  • 5751: S/MIME Version 3.2 Message Specification (Obsoletes rfc3851)

Other RFCs of interest:

  • 1872: The MIME Multipart/Related Content-type
  • 1927: Suggested Additional MIME Types for Associating Documents
  • 2111: Content-ID and Message-ID Uniform Resource Locators
  • 2112: The MIME Multipart/Related Content-type (Obsoletes rfc1872)
  • 2387: The MIME Multipart/Related Content-Type (Obsoletes rfc2112)
  • 2388: Returning Values from Forms: multipart/form-data
  • 2424: Content Duration MIME Header Definition

Cryptography related RFCs (needed by S/MIME)

  • 2268: A Description of the RC2(r) Encryption Algorithm
  • 2313: PKCS #1: RSA Encryption
  • 2313: PKCS #10: Certification Request Syntax
  • 2631: Diffie-Hellman Key Agreement Method

GMime, Copyright (C) 2000-2014 Jeffrey Stedfast.

This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version.

This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details.

You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.

As a developer and user of Electronic Mail clients, I had come to realize that the vast majority of E-Mail client (and server) software had less-than-satisfactory MIME implementations. More often than not these E-Mail clients created broken MIME messages and/or would incorrectly try to parse a MIME message thus subtracting from the full benefits that MIME was meant to provide. GMime is meant to address this issue by following the MIME specification as closely as possible while also providing programmers with an extremely easy to use high-level application programming interface.

Information regarding GMime may be obtained from the GMime website: http://spruce.sourceforge.net/gmime/

Experimental versions of GMime may be obtained issuing the following command:

Requirements for GMime 2.6.x

For proper compilation and functionality of GMime 2.6.x, the following packages are REQUIRED:

  • Glib version >= 2.18.0
    Glib provides a number of portability-enhancing functions and types. Glib is included in most GMime-supported operating system distributions. Glib sources may be obtained from: ftp://ftp.gtk.org/pub/glib

Requirements for GMime 2.4.x

For proper compilation and functionality of GMime 2.4.x, the following packages are REQUIRED:

  • Glib version >= 2.12.0
    Glib provides a number of portability-enhancing functions and types. Glib is included in most GMime-supported operating system distributions. Glib sources may be obtained from: ftp://ftp.gtk.org/pub/glib

Requirements for GMime 2.2.x

For proper compilation and functionality of GMime 2.2.x, the following packages are REQUIRED:

  • Glib version >= 2.6.0
    Glib provides a number of portability-enhancing functions and types. Glib is included in most GMime-supported operating system distributions. Glib sources may be obtained from: ftp://ftp.gtk.org/pub/glib

This is the README file for GMime. Additional documentation related to development using GMime has been included within the source release of GMime.

docs/reference/ Contains SGML and HTML versions of the GMime API reference manual
docs/tutorial/ Contains SGML and HTML versions of the GMime programming tutorial
AUTHORS List of primary authors (source code developers)
COPYING The GNU Lesser General Public License, version 2
ChangeLog Log of changes made to the source code
INSTALL In-depth installation instructions
NEWS Release notes (Overview of changes)
TODO Description of planned GMime development
PORTING Guide for developers porting their application from an older version of GMime

You can find online developer documentation at http://library.gnome.org/devel/gmime/stable/

You can find the beginnings of a tutorial at http://spruce.sourceforge.net/gmime/tutorial

For discussion of GMime development (either of GMime itself or using GMime in your own application), you may find the GMime-Devel mailing-list helpful. To subscribe, please see http://mail.gnome.org/mailman/listinfo/gmime-devel-list.

There are a number of efforts to bring GMime bindings to other programming languages. (Note: these bindings are maintained by other people, so please don’t submit bug reports about them to me)

Binding Location Bug Reports
Perl MIME::Fast MIME::Fast Bugs
Mono/.NET Included in the GMime source packages http://bugzilla.gnome.org

For those interested in using GMime from .NET 4.0 (or later), I recommend using MimeKit.

How Multipurpose Internet Mail Extensions (MIME) Works

MIME makes it easy to send file attachments with emails

Henrik5000 / Getty Images

MIME stands for Multipurpose Internet Mail Extensions. MIME extends the original capabilities of internet email in a useful, content-rich way.

Email messages have been defined by RFC 822 (and later RFC 2822) since 1982, and they will probably continue to obey this standard for a long time to come. MIME extends RFC 822 standards beyond what was envisioned nearly 40 years ago.

Nothing but Plain Text

RFC 822 suffers from a number of shortcomings. Most notably, messages conforming to that standard must not contain anything but plain ASCII text.

To send files like pictures, text processor documents or programs, you must convert them to plain text first and then send the result of the conversion in the body of an email message. The recipient has to extract the text from the message and convert it to the binary file format again. This is a cumbersome process, and before MIME it all had to be done by hand.

MIME corrects this problem attached to RFC 822, and it makes it possible to use international characters in email messages, too. With the RFC 822 limitation to plain (English) text, this capability had not been possible before.

The Lack of Structure

In addition to being limited to ASCII characters, RFC 822 does not identify the structure of a message or the format of the data. Because with plain-text data, everything comes in one chunk, a detailed structural topography wasn’t necessary when the original standard went into effect.

MIME, in contrast, lets you send several pieces of different units data in one message (say, a picture and a Word document), and it tells the recipient’s email client what format the data is in so they can make smart choices displaying the message.

When you get a picture, you do no longer have to figure out that it can be viewed with an image viewer. Your email client either displays the image itself or start a program on your computer that can.

Building on and Extending RFC 822

Now how does the MIME magic work? Basically, it employs the cumbersome process of sending arbitrary data in plain text. The MIME message standard does not replace the standard laid down in RFC 822 but extends it. MIME messages cannot contain anything but ASCII text, either.

This means that all email data must still be encoded in plain text before the message is sent, and it must be decoded to its original format on the receiving end again. The early email users had to do that manually. MIME does it for us comfortably and seamlessly, usually through a smart process called Base64 encoding.

Life as a MIME Email Message

When you compose a message in an email program capable of MIME, the program does roughly the following:

  • If the message is in plain ASCII text only, it leaves it alone and only tells the recipient’s email client to expect nothing but plain text.
  • If the message contains one or more attachments and a body with HTML formatting, each part is looked at and treated separately.

First, the format of the data is determined. This step is necessary to tell the recipient’s email client what to do with the data and to ensure proper encoding so nothing is lost during transfer.

Then the data is encoded if it is in a format other than plain ASCII text. In the encoding process, the data is converted to the plain text suitable for RFC 822 messages.

Finally, the encoded data is inserted in the message, and the recipient’s email client is informed what kinds of data to expect: Are there attachments? How are they encoded? What format was the original file in?

On the recipient’s end, the process is reversed. First, the email client reads the information that was added by the sender’s email client: Do I have to look for attachments? How do I decode them? How do I handle the resulting files? Then, each part of the message is extracted and decoded if necessary. Finally, the email client displays the resulting parts to the user. The plain-text body is shown inline in the email client together with the image attachment. The program also attached to the message is displayed with an attachment icon, and the recipient can decide what to do with it. She can save it somewhere on her disk, or start it directly from the email program.

Понравилась статья? Поделиться с друзьями:
Кодинг, CSS и SQL