Docs

IPWorks 2022 Java Edition

Version 22.0 [Build 8171]

MIME Class

Properties   Methods   Events   Configuration Settings   Errors  

The MIME class allows for the simple encoding and decoding of MIME structures such as message attachments, file uploads, etc.

Syntax

ipworks.Mime

Remarks

The class may be used for decoding or encoding of messages. Message holds the content of the encoded message or the filename which holds the encoded data. The decoded data is provided in Parts collection.

To decode a MIME message you should first assign either the whole message (headers and body) to Message or put the message headers into the MessageHeaders property and the message body or the filename holding it into the Message property. Calling DecodeFromFile or DecodeFromString directs the class to start parsing the message: it will fill out the ContentType, ContentTypeAttr properties with message content type information, and enter information about message parts into the Parts collection, which includes: part sizes, part content types, part content type attributes, part content disposition, part content disposition attributes, part encoding, part name, part filename, part headers, or part content (part decoded string or part decoded file) for each decoded part.

Calling the DecodeFromString or DecodeFromFile to decode doesn't actually decode the message but only parses it. The real decoding is done when the part content in the Parts collection is first accessed.

To encode data into a MIME message you should first assign values for each part to either part decoded string or part decoded file in the Parts collection property, and optionally assign values to the other part attributes in the Parts collection. Assigning a value to the part decoded string or part decoded file through the Parts collection, fills out automatically the part headers into the Parts collection for the respective part. Calling EncodeToFile or EncodeToString directs the class to fill out the Message with the message body and the MessageHeaders with the headers.

The Progress event is fired as the message is parsed and the data is decoded/encoded.

Property List


The following is the full list of the properties of the class with short descriptions. Click on the links for further details.

BoundaryThe boundary separating the MIME parts. Maximum length of 80 bytes.
ContentTypeThe value of the content-type header of the message which was encoded/decoded.
ContentTypeAttrThe attributes for content-type header of the message which was encoded/decoded.
MessageContains the encoded message text or a path to a file which contains the encoded message text.
MessageHeadersThe headers of the MIME message.
MessageHeadersStringString version of the MIME message headers.
PartsContains information about all parts of a MIME message.

Method List


The following is the full list of the methods of the class with short descriptions. Click on the links for further details.

ConfigSets or retrieves a configuration setting.
DecodeFromFileDecodes from file.
DecodeFromStreamDecodes from stream.
DecodeFromStringDecodes from string.
DecodePartDecodes the specified part.
DecodePartToFileDecodes the specified part to a file on disk.
DecodePartToStreamDecodes the specified part to a stream.
EncodeToFileEncodes to file.
EncodeToStreamEncodes to stream.
EncodeToStringEncodes to string.
ResetReset the class.
ResetDataResets the values of all headers and Part- properties.

Event List


The following is the full list of the events fired by the class with short descriptions. Click on the links for further details.

ErrorInformation about errors during data delivery.
HeaderFired every time a header is parsed.
ProgressShows the progress of decoding/encoding the input data.

Configuration Settings


The following is a list of configuration settings for the class with short descriptions. Click on the links for further details.

AlternateCharsetNamesMaps alternate charset names to the specified name.
FoldHeadersTells the class whether to fold the headers.
IncludeHeadersTells the class whether to include the headers when encoding the message.
MaxPartsThe maximum number of parts to be parsed from a mime message.
RequireVersionHeaderSpecifies whether or not the class should require the version header.
SanitizeFilenameWhether invalid characters are replaced in MIME part filenames.
TempFilePathIf set, the temporary files created during MIME decoding and encoding will be put in the path specified.
BuildInfoInformation about the product's build.
GUIAvailableTells the class whether or not a message loop is available for processing events.
LicenseInfoInformation about the current license.
UseDaemonThreadsWhether threads created by the class are daemon threads.
UseInternalSecurityAPITells the class whether or not to use the system security libraries or an internal implementation.

Boundary Property (MIME Class)

The boundary separating the MIME parts. Maximum length of 80 bytes.

Syntax


public String getBoundary();


public void setBoundary(String boundary);

Default Value

""

Remarks

This property contains the boundary separating the MIME parts and has a maximum length of 80 bytes. The class will automatically generate a random boundary value during encoding if no value is given. During decoding this property is filled with the boundary from the actual MIME message.

The class will truncate any string longer than 80 bytes if assigned to Boundary.

ContentType Property (MIME Class)

The value of the content-type header of the message which was encoded/decoded.

Syntax


public String getContentType();


public void setContentType(String contentType);

Default Value

""

Remarks

This property contains the value of the content-type header of the message which was encoded/decoded. The class filters it out from the MessageHeaders. It shows the user about the type of the parts and their relation to each other.

The content-type attributes such as filename, boundary, charset etc are held in this property.

ContentTypeAttr Property (MIME Class)

The attributes for content-type header of the message which was encoded/decoded.

Syntax


public String getContentTypeAttr();


public void setContentTypeAttr(String contentTypeAttr);

Default Value

""

Remarks

This property contains content-type attributes such as "filename", "boundary", "charset", etc.

Message Property (MIME Class)

Contains the encoded message text or a path to a file which contains the encoded message text.

Syntax


public byte[] getMessage();


public void setMessage(byte[] message);

Default Value

""

Remarks

This property contains the encoded message text or a path to a file which contains the encoded message text. The class fills out this property with the message body and MessageHeaders during encoding. The user may assign both the headers and the body to this property and leave MessageHeaders empty before decoding.

This property is not available at design time.

MessageHeaders Property (MIME Class)

The headers of the MIME message.

Syntax


public HeaderList getMessageHeaders();


public void setMessageHeaders(HeaderList messageHeaders);

Remarks

This property contains the headers of the MIME message. The class fills out this property upon encoding. The user should use them as additional headers when emailing the Message.

During decoding, if this property is empty the class will try to find the headers in the beginning of the Message and will fill out this property accordingly.

MessageHeadersString Property (MIME Class)

String version of the MIME message headers.

Syntax


public String getMessageHeadersString();


public void setMessageHeadersString(String messageHeadersString);

Default Value

""

Remarks

The component fills out MessageHeadersString upon encoding. The user should use them as additional headers when emailing the Message.

This property contains a string version of the MIME message headers. During decoding, if this property is empty the class will try to find the headers in the beginning of the Message and will fill out this property accordingly.

Parts Property (MIME Class)

Contains information about all parts of a MIME message.

Syntax


public MIMEPartList getParts();


public void setParts(MIMEPartList parts);

Remarks

This property contains information about all parts of a MIME message. A MIME message consists of different parts, separated by either a user-specified or an auto-generated boundary. Each part has its own set of headers which are contained in the Headers field.

The MIMEPARTS collection is filled out by the class when a call to either DecodeFromFile or DecodeFromString is made. However, when the EncodeToFile or EncodeToString methods are called, the class encodes the data given in either DecodedFile or DecodedString into a MIME message.

This collection is indexed from 0 to size - 1.

Config Method (Mime Class)

Sets or retrieves a configuration setting.

Syntax

public String config(String configurationString);

Remarks

Config is a generic method available in every class. It is used to set and retrieve configuration settings for the class.

These settings are similar in functionality to properties, but they are rarely used. In order to avoid "polluting" the property namespace of the class, access to these internal properties is provided through the Config method.

To set a configuration setting named PROPERTY, you must call Config("PROPERTY=VALUE"), where VALUE is the value of the setting expressed as a string. For boolean values, use the strings "True", "False", "0", "1", "Yes", or "No" (case does not matter).

To read (query) the value of a configuration setting, you must call Config("PROPERTY"). The value will be returned as a string.

DecodeFromFile Method (Mime Class)

Decodes from file.

Syntax

public void decodeFromFile();

Remarks

This method decodes the data file given in Message and optionally MessageHeaders and fills out the Parts collection for each decoded part.

Example (Decoding From File)

MIMEControl.Message = "C:\filename.txt" MIMEControl.DecodeFromFile

Here, C:\filename.txt must contain the MIME headers and body. If not, the MessageHeaders property must also be set to the appropriate MIME headers.

DecodeFromStream Method (Mime Class)

Decodes from stream.

Syntax

public void decodeFromStream(java.io.InputStream inputStream);

Remarks

This method decodes from stream. Same as DecodeFromString, but now the MIME message is passed to this method as a stream.

This method decodes the data given by the InputStream and optionally MessageHeaders and fills out the Parts collection.

Example (Decoding Mail Message)

MIMEControl.MessageHeaders.AddRange(MailControl.MessageHeaders) MIMEControl.DecodeFromStream(InputStream)

DecodeFromString Method (Mime Class)

Decodes from string.

Syntax

public void decodeFromString();

Remarks

This method decodes from string. Same as DecodeFromFile, but now the Message denotes the real encoded message rather than a filename.

This method decodes the data given in Message and optionally MessageHeaders and fills out the Parts collection.

Example (Decoding Mail Message)

MIMEControl.MessageHeaders.AddRange(MailControl.MessageHeaders) MIMEControl.Message = MailControl.MessageText MIMEControl.DecodeFromString

DecodePart Method (Mime Class)

Decodes the specified part.

Syntax

public byte[] decodePart(int index);

Remarks

This method decodes the part specified by Index and returns the decoded part data.

DecodeFromString or DecodeFromFile must be called before calling this method. Calling this method will return the decoded bytes, and in addition the DecodedString field will be populated with the string representation of the decoded data.

For instance: mime.MessageHeadersString = myMessageHeaders; mime.Message = myMessageBody; mime.DecodeFromString(); byte[] myPartContent = await mime.DecodePart(0);

DecodePartToFile Method (Mime Class)

Decodes the specified part to a file on disk.

Syntax

public String decodePartToFile(int index);

Remarks

This method decodes the part specified by Index to a temporary file. The full path to the temporary file is returned by this method. The user is responsible for deleting the temporary file.

DecodeFromString or DecodeFromFile must be called before calling this method.

DecodePartToStream Method (Mime Class)

Decodes the specified part to a stream.

Syntax

public void decodePartToStream(int index, java.io.OutputStream outputStream);

Remarks

This method decodes the part specified by Index to stream specified by OutputStream.

DecodeFromString or DecodeFromFile must be called before calling this method.

EncodeToFile Method (Mime Class)

Encodes to file.

Syntax

public void encodeToFile();

Remarks

This method encodes the data given in Parts collection (either decoded file or decoded string) into a MIME message at Message and MessageHeaders using the values optionally given in Parts collection. To encode several objects into a MIME envelope, the user should first clear any old values left in the Parts collection.

The class will check for each item in Parts collection (first decoded file and then the decoded string) for the data to encode.

The encoded message will be saved in the file pointed to by Message; the message headers will be held by MessageHeaders.

Example (Encoding Data)

MIMEControl.ResetData() MIMEControl.Parts.Add(new MIMEPart()) MIMEControl.Parts.Add(new MIMEPart()) MIMEControl.Parts[0].DecodedString = "This is plain text data" MIMEControl.Parts[0].Encoding = peQuotedPrintable MIMEControl.Parts[0].ContentType = "text/plain" MIMEControl.Parts[1].DecodedFile = "C:\filename.txt" MIMEControl.Message = "temp.tmp" MIMEControl.EncodeToFile()

EncodeToStream Method (Mime Class)

Encodes to stream.

Syntax

public void encodeToStream(java.io.OutputStream outputStream);

Remarks

This method encodes to stream. Same as EncodeToString but the encoded data is written to a stream instead of to the Message property.

This method encodes the data given in Parts collection into a MIME message. The Message gets written to the specified OutputStream and MessageHeaders using the values optionally given in Parts collection. To encode several objects into a MIME envelope, the user should first clear any old values left in the Parts collection by calling ResetData.

The class will check each item in Parts collection (first decoded file and then decoded string) for the data to encode.

The encoded message will be written to the specified OutputStream, and the message headers will be held by MessageHeaders.

Example (Encoding Data)

MIMEControl.ResetData() MIMEControl.Parts.Add(new MIMEPart()) MIMEControl.Parts.Add(new MIMEPart()) MIMEControl.Parts[0].DecodedString = "This is plain text data" MIMEControl.Parts[0].Encoding = peQuotedPrintable MIMEControl.Parts[0].ContentType = "text/plain" MIMEControl.Parts[1].DecodedFile = "C:\filename.txt" MIMEControl.EncodeToStream(OutputStream)

EncodeToString Method (Mime Class)

Encodes to string.

Syntax

public void encodeToString();

Remarks

This method encodes to string. Same as EncodeToFile but the encoded data is held in the Message property rather than saved to a file.

This method encodes the data given in Parts collection into a MIME message. The Message gets stored in Message and MessageHeaders using the values optionally given in Parts collection. To encode several objects into a MIME envelope, the user should first clear any old values left in the Parts collection by calling ResetData.

The class will check each item in Parts collection (first decoded file and then decoded string) for the data to encode.

The encoded message will be stored in the Message property; the message headers will be held by MessageHeaders.

Example (Encoding Data)

MIMEControl.ResetData() MIMEControl.Parts.Add(new MIMEPart()) MIMEControl.Parts.Add(new MIMEPart()) MIMEControl.Parts[0].DecodedString = "This is plain text data" MIMEControl.Parts[0].Encoding = peQuotedPrintable MIMEControl.Parts[0].ContentType = "text/plain" MIMEControl.Parts[1].DecodedFile = "C:\filename.txt" MIMEControl.EncodeToString()

Reset Method (Mime Class)

Reset the class.

Syntax

public void reset();

Remarks

This method will reset the class's properties to their default values.

ResetData Method (Mime Class)

Resets the values of all headers and Part- properties.

Syntax

public void resetData();

Remarks

This method resets the values of all headers and Part- properties. It is an easy way to reset the class's properties before starting to populate the Part- properties with new values.

Error Event (Mime Class)

Information about errors during data delivery.

Syntax

public class DefaultMimeEventListener implements MimeEventListener {
  ...
  public void error(MimeErrorEvent e) {}
  ...
}

public class MimeErrorEvent {
  public int errorCode;

  public String description;

}

Remarks

The Error event is fired in case of exceptional conditions during message processing. Normally the class throws an exception.

ErrorCode contains an error code and Description contains a textual description of the error. For a list of valid error codes and their descriptions, please refer to the Error Codes section.

Header Event (Mime Class)

Fired every time a header is parsed.

Syntax

public class DefaultMimeEventListener implements MimeEventListener {
  ...
  public void header(MimeHeaderEvent e) {}
  ...
}

public class MimeHeaderEvent {
  public int partIndex;

  public String field;

  public byte[] value;

}

Remarks

The PartIndex parameter contains the index of the part containing the current header. If the header is from the MIME body, this value will be -1. The Field parameter contains the name of the MIME header. The Value parameter contains the header contents. The Header event is fired when a header is parsed, which occurs for each header of the Message when DecodeFromFile, DecodeFromString, or DecodeFromStream is called.

Progress Event (Mime Class)

Shows the progress of decoding/encoding the input data.

Syntax

public class DefaultMimeEventListener implements MimeEventListener {
  ...
  public void progress(MimeProgressEvent e) {}
  ...
}

public class MimeProgressEvent {
  public int percentDone;

}

Remarks

The Progress allows the user to visualize the progress of processing the input data.

The PercentDone parameter shows what percentage of the input has been read.

Header Type

An HTTP header as it is received from the server.

Remarks

When a header is received through a Header event, it is parsed into a Header type. This type contains a Field, and its corresponding Value.

Fields

Field
String

This field contains the name of the HTTP Header (same case as it is delivered).

Value
String

This field contains the Header contents.

Constructors

public Header();



public Header(String field, String value);



MIMEPart Type

A part of the MIME message.

Remarks

Each MIME message is split into parts. A message must have at least one part to be a valid MIME message. The message itself is split into the MessageHeaders and the Message body. The body is then split into MIME parts by a specified or generated Boundary. Each part of a MIME message has its own Headers as well. These headers describe the MIMEPart and its contents.

The decoded data will be held in DecodedString or otherwise saved in a temporary file given by DecodedFile when the user asks for the value of the respective field.

If the encoded data is file data, the decoded file(s) will be given in the DecodedFile field. Otherwise, the decoded data will be in the DecodedString field.

When the EncodeToString method is called, the class will check for each item in the Parts collection (first the DecodedFile and then the DecodedString) for the data to encode.

Fields

ContentDisposition
String

Content disposition for each part.

The value in this field is used in the Content-Disposition header. Typical values include "form-data", "attachment" etc. The class fills it out each time the DecodedFile is changed. Changing the ContentDisposition recalculates the Headers as well.

ContentDispositionAttr
String

The content disposition's attribute (if any) for each part.

Typical values for this field are the names of the form-variables while creating an HTTP post, values for filenames etc.

Setting this field recalculates the Headers.

ContentId
String

Content identifier for each part. The value of this field is used in the Content-Id header. The class fills it out each time the DecodedFile is changed. Changing This field recalculates the Headers as well.

ContentType
String

Content type for each part. The value of this field is used in the Content-Type header. Typical values include "image/gif", "text/plain" etc. The class fills it out each time the DecodedFile is changed. Changing This field recalculates the Headers as well.

ContentTypeAttr
String

The content type attribute, if any, for each part. Setting this recalculates the Headers as well.

DecodedFile
String

The filename with the decoded data. Accessing this field for the first time after calling the DecodeFromString or DecodeFromFile method, directs the class to actually decode the part and save the data in a temporary file. The user is responsible for deleting the temporary file.

Setting a value to DecodedFile directs the component to calculate the file size and fill out the respective Size.

Note: It is recommended to use the DecodePartToFile method instead of querying this property.

DecodedString
String

This field holds the actual content of each part. The class decodes the actual part of Message to DecodedString when DecodedString's value is first queried.

Setting a value to DecodedString fills out the corresponding Size with the string size if the corresponding DecodedFile is empty.

The class checks during encoding first DecodedFile: if it is empty then the class uses the value of DecodedString.

Note: It is recommended to use the DecodePart method instead of querying this property.

DecodedStringB
byte[]

This field holds the actual content of each part. The class decodes the actual part of Message to DecodedString when DecodedString's value is first queried.

Setting a value to DecodedString fills out the corresponding Size with the string size if the corresponding DecodedFile is empty.

The class checks during encoding first DecodedFile: if it is empty then the class uses the value of DecodedString.

Note: It is recommended to use the DecodePart method instead of querying this property.

Encoding
int

This field contains the actual content encoding type for each part. This field determines how to encode the data or how they were actually encoded in the Message as specified in the Content-Transfer-Encoding header.

Possible values for the this field are:

pe7bit (0)7 Bit data, no encoding.
peQuotedPrintable (1)Quoted-Printable encoding of (typically) text.
peBase64 (2)Base64 encoding of binary data.
pe8Bit (3)No encoding, 8 Bit characters may be contained as well.
peBinary (4)Binary data without any encoding. Similar to 3 (8 Bit encoding).
peUUEncode (5)Uuencoding of binary data.

Filename
String

This field contains the filename attribute specified in the headers of the part. Changing the value of the corresponding DecodedFile sets automatically the Filename and consequently the Headers.

Headers
String

This field contains the headers for each MIME part. The class fills out this field each time any of the other corresponding Part- properties is changed. If additional headers are needed, they should be appended after all the other corresponding Part- properties are set.

Name
String

This field contains the name given to a part, such as the filename. Changing the value of DecodedFile sets automatically the corresponding Name and consequently the Headers.

PartInputStream
java.io.InputStream

This field contains a stream which contains the actual content of each part before the message is encoded.

PartOutputStream
java.io.OutputStream

The class decodes the actual part of Message when This field's value is first set, and writes the decoded value to the stream.

Note: It is recommended to use the DecodePartToStream method instead of setting this property.

Size
int

This field contains the size of the DecodedFile or DecodedString. If a non empty value is assigned to DecodedFile, then class fills out the corresponding Size with the file size or an error occurs if the file doesn't exist.

If the DecodedFile is empty and a value is assigned to DecodedString, then the corresponding Size will be equal to the string's size.

During decoding, this field is filled with the size of that part.

Constructors

public MIMEPart();



public MIMEPart(String decodedFile);



public MIMEPart(byte[] decodedString);



public MIMEPart(java.io.InputStream partInputStream);



public MIMEPart(java.io.InputStream partInputStream, String encoding);



Configuration Settings (Mime Class)

The class accepts one or more of the following configuration settings. Configuration settings are similar in functionality to properties, but they are rarely used. In order to avoid "polluting" the property namespace of the class, access to these internal properties is provided through the Config method.

MIME Configuration Settings

AlternateCharsetNames:   Maps alternate charset names to the specified name.

Use this configuration setting to map alternate charset names to a valid charset name. The mappings are set with this format: "AlternateCharsetNames=altName1:validName1;altName2:validname2".

The alternate names are case-insensitive to allow for a greater number of alternate names to be handled. The valid name is case-sensitive to ensure the correct charset is used. Mappings are done on a one-to-one basis. If there are several alternate names that are not covered by case-insensitivity, multiple mappings will need to be used. mime.Config("AlternateCharsetNames=cp-850:cp850;_cp_850:cp850"); The example above will map both "cp-850" and "_cp_850" to "cp850".

The below example is redundant, as alternate names are case-insensitive. mime.Config("AlternateCharsetNames=cp1252:windows-1252;CP1252:windows-1252");

FoldHeaders:   Tells the class whether to fold the headers.

If true, the class will fold the headers if the headers are over a certain length. If false, the headers will be on one line regardless of length.

IncludeHeaders:   Tells the class whether to include the headers when encoding the message.

If true, the class will include the headers when EncodeToFile or EncodeToString are called. If false, only the message will be encoded.

The default value for IncludeHeaders is false.

MaxParts:   The maximum number of parts to be parsed from a mime message.

This config should be set to limit the amount of parts that will be parsed by the component and saved into the collection. By default, this value is 100. Therefore up to 100 parts will be parsed from a mime message by default.

RequireVersionHeader:   Specifies whether or not the class should require the version header.

If true, the class will require that the "MIME-Version" header be included in the MessageHeaders. If the header is not present during decoding, the component throws an exception. This config is false by default.

SanitizeFilename:   Whether invalid characters are replaced in MIME part filenames.

If True, the class will replace invalid characters with an underscore when decoding the MIME message. This applies to the filename held in the Filename field. When True the following characters are considered invalid:

  • \
  • /
  • "
  • :
  • ?
  • *
  • <
  • >
  • |
Any characters with ASCII values between 0-31 are also considered invalid. The default value is False.
TempFilePath:   If set, the temporary files created during MIME decoding and encoding will be put in the path specified.

The TempFilePath property sets the path at which the temporary files will be created.

Base Configuration Settings

BuildInfo:   Information about the product's build.

When queried, this setting will return a string containing information about the product's build.

GUIAvailable:   Tells the class whether or not a message loop is available for processing events.

In a GUI-based application, long-running blocking operations may cause the application to stop responding to input until the operation returns. The class will attempt to discover whether or not the application has a message loop and, if one is discovered, it will process events in that message loop during any such blocking operation.

In some non-GUI applications, an invalid message loop may be discovered that will result in errant behavior. In these cases, setting GUIAvailable to false will ensure that the class does not attempt to process external events.

LicenseInfo:   Information about the current license.

When queried, this setting will return a string containing information about the license this instance of a class is using. It will return the following information:

  • Product: The product the license is for.
  • Product Key: The key the license was generated from.
  • License Source: Where the license was found (e.g., RuntimeLicense, License File).
  • License Type: The type of license installed (e.g., Royalty Free, Single Server).
UseDaemonThreads:   Whether threads created by the class are daemon threads.

If set to True (default), when the class creates a thread, the thread's Daemon property will be explicitly set to True. When set to False, the class will not set the Daemon property on the created thread. The default value is True.

UseInternalSecurityAPI:   Tells the class whether or not to use the system security libraries or an internal implementation.

By default the class will use the system security libraries to perform cryptographic functions. Setting this to True tells the class to use the internal implementation instead of using the system's security API.

Trappable Errors (Mime Class)

MIME Errors

3   Can't create the file for write (illegal name or disk is write-protected).
4   Can't open the file for read (doesn't exist?).
5   Can't read from file.
6   Can't write to file (disk full?).
280   Invalid Part Index.
281   Unknown MIME type.
282   No MIME-boundary found.
283   No file given.
284   The class is busy.
285   Could not create a temporary file to decode the data.
286   Can't read Message file.
287   No header separator found.
289   No separator found.
290   Input stream must have seeking enabled.

Copyright (c) 2022 /n software inc. - All rights reserved.
IPWorks 2022 Java Edition - Version 22.0 [Build 8171]