Class Mht

All Implemented Interfaces:
AutoCloseable

public class Mht extends ChilkatObject
<section class="mht-summary">

Create, save, zip, email, and unpack MHT web archives.

Chilkat.Mht creates MHT web archives and EML email messages from HTTP/HTTPS pages, local HTML files, or in-memory HTML strings. It analyzes the supplied HTML source, resolves and retrieves supported static resources, rewrites references as needed, and packages the result as MIME. It also supports disk caching, proxies, authentication, file or ZIP output, and unpacking existing MHT data.

Create MHT archives

Convert a web page, local HTML file, or HTML string into an MHT archive with supported related resources embedded when settings permit and each resource can be obtained.

Generate EML messages

Produce an HTML-email MIME draft from HTML. Image embedding follows EmbedImages and EmbedLocalOnly; scripts, frames, and comments are removed. Addressing, subject, and sending remain application tasks.

Embed static resources

Capture images, CSS, CSS imports and backgrounds, and—when producing MHT—frames and supported external scripts.

Network configuration

Use proxy settings, authentication, caching, redirects, capture-scoped cookies, and related options when fetching pages and dependent resources.

Save or zip output

Return generated MHT or EML text in memory, save it to disk, or place it into a ZIP archive.

Unpack MHT files

Extract an MHT archive into an HTML file plus supporting resource files for inspection, editing, or republishing.

Not a browser rendering engine: Mht does not execute JavaScript, build or wait for a browser DOM, trigger lazy loading, or capture AJAX, fetch, XHR, React, Angular, Vue, or other client-rendered content. It captures the original HTML source and resources that are statically referenced by that source. MHT output can preserve scripts so they may execute when the saved archive is later opened; EML output always removes scripts.

URL or local file: Methods accepting a URL-or-file argument use a strict prefix rule. A value is a web URL only if it begins, case-insensitively, with http: or https:. Every other value is treated as a local path. file:// is not recognized. Relative paths use the process current working directory, and a local source file must already exist and be readable.

Base resolution: Resolution precedence is the HTML <base href> element, then BaseUrl, then the source page URL or local file directory. Use a URL—not a filesystem directory—for BaseUrl, and end a directory-style base URL with /. Downloaded CSS resolves its own relative url(...) and @import references against the stylesheet URL; inline CSS resolves against the page base.

Default static resource handling:

HTML/CSS reference Behavior

<img src> Captured by default, subject to EmbedImages and EmbedLocalOnly.

srcset / sizes Not used for candidate selection. These attributes are stripped and the ordinary src is used; obvious spacer placeholders are detected so the real image can be captured.

CSS url(...) Captured from external style sheets, <style> blocks, and inline style attributes.

CSS @import Downloaded, inlined, and processed recursively.

<link rel="stylesheet"> Downloaded and inlined; its CSS references are then processed recursively.

<iframe> / <frame> Fetched and captured for MHT; removed for EML.

<script src> Supported external scripts are captured for MHT and inline scripts may be retained; all scripts are removed for EML. Script handling remains subject to NoScripts and PreferMHTScripts.

<object data>, <embed src>, media elements References are made absolute, but the payload is not downloaded. This includes video, audio, source, and track.

Favicons Not captured.

Navigation and form URLs Made absolute when possible, but their targets are not downloaded.

HTTP redirects Followed for the primary page and dependent resources. After a primary redirect, relative references use the final landing URL as their base.

Dependent-resource failures do not fail the capture: If a dependent image, style sheet, imported CSS file, frame, script, or other supported resource cannot be downloaded, Chilkat omits that MIME part, restores the HTML reference to the original absolute live URL, logs the problem in LastErrorText, and continues with a successful result. No empty placeholder part is created. Failure to load the primary URL or local HTML file does fail the operation. Consequently, output is fully self-contained only to the extent allowed by the embedding properties and the resources that were successfully obtained.

String-returning methods: For GetMHT, GetEML, HtmlToMHT, HtmlToEML, and GetCacheRoot, check LastMethodSuccess. Do not infer success or failure from whether the returned string is empty. On failure the string is cleared or may contain partial output, and LastErrorText contains the diagnostic.

File output: Save methods generate the MIME document in memory before opening the destination. Existing files are overwritten, parent directories are not created, and relative paths use the process current working directory. The final write is not atomic, so a write-time I/O failure can leave partial output. Generation failure leaves an existing destination file untouched.

Redirect and cookie behavior: Redirects are followed automatically for the main page and dependent resources. Cookies received during one capture are retained and sent on later requests in that same capture. The redirect limit, exact followed status codes, and HTTPS-to-HTTP downgrade policy are controlled by the underlying HTTP engine and are not exposed as Mht settings.

Object state persists: External style sheets, exclusion patterns, custom headers, and cache roots remain configured across conversions. RestoreDefaults clears only the external style-sheet and exclusion-pattern collections; it does not clear custom headers or cache roots. Cache roots can be reset only by using a new object.

Custom headers are cross-host: Permitted custom headers are sent to the primary page, redirect targets, and every dependent-resource host. Authorization and Content-Length are rejected, but other sensitive fields such as a manually supplied Cookie can be sent to third-party hosts.

MHT versus EML: Both are MIME documents with an HTML root and related embedded resources. MHT is a web-archive form and omits Date and X-Unsent. EML adds the current Date and X-Unsent: 1, removes scripts, frames, and comments, and is best treated as an HTML-email draft. It has no generated Message-ID and no plain-text alternative; the application must add the required addressing and subject information before sending.

Returned MIME strings: Preserve CRLF line endings and write the result as UTF-8 without a BOM. Treat the string as opaque MIME text. The file-writing methods are preferable when exact serialized bytes are required.

ZIP and unpack safety: ZIP methods reject an existing entry name and rewrite the complete archive non-atomically. Normal unpacking contains extracted paths beneath the requested directory, but existing files from earlier runs are overwritten. Direct unpack mode is for relative Content-Location values and skips parts whose locations are full URLs.

Common pattern: Provide an HTTP/HTTPS URL, a readable local HTML path, or an HTML string; configure the base URL, proxy, authentication, caching, and resource options; then return, save, or zip the MHT/EML output. When the desired content exists only after JavaScript executes, first obtain rendered HTML with a browser or browser-automation tool and pass that HTML to an HtmlTo* method.

For an extended overview, see Mht Class Overview.

</section>

Event-capable: long-running methods report progress through a ProgressListener installed with setProgressListener(ProgressListener), onAbortCheck(BooleanSupplier), onPercentDone(IntPredicate) or onProgressInfo(BiConsumer).

Instances hold a native Chilkat object: close them with ChilkatObject.close() (try-with-resources) when done; an unclosed instance is freed when it becomes unreachable.

See Also:
Online reference
  • Constructor Details

    • Mht

      public Mht()
      Creates a new Mht object.
  • Method Details

    • getAbortCurrent

      public boolean getAbortCurrent()
      Set to true to request cancellation of the operation currently running on this object. Long-running network and file operations periodically check this property; a fast operation may complete before the request is observed.

      A synchronous method can be cancelled from another thread by setting this property on the same object. Chilkat resets the property to false after an abort is processed, and a stale request is cleared when a later method begins.

      Cancellation request: Cancellation is cooperative rather than instantaneous. Always inspect the method's return value and diagnostic properties to determine the final outcome.

      Returns:
      the value of the AbortCurrent property
    • setAbortCurrent

      public void setAbortCurrent​(boolean value)
      Sets the AbortCurrent property; see getAbortCurrent().
      Parameters:
      value - the new value
    • getBaseUrl

      public String getBaseUrl()
      Specifies a web base URL used when relative references in a local HTML file or in-memory HTML string must be resolved in an HTTP/HTTPS context. For an HTTP/HTTPS source page, Chilkat derives the base from the fetched URL automatically.

      Resolution precedence: An HTML <base href> element takes precedence over this property. If no usable <base> exists, BaseUrl is used; otherwise Chilkat falls back to the source page URL or the directory containing the local HTML file.Local files: Relative filesystem references in a local HTML file can be resolved from the file's own directory without setting this property. Set BaseUrl when the document contains site-relative or root-relative references that should resolve against a web origin. The value should be an HTTP or HTTPS URL, not a filesystem directory.Trailing slash: URL resolution follows normal base-URL rules. Use a trailing slash for a directory-style base, such as https://www.example.com/section/. Without it, the last path segment is treated as a filename and is removed before relative resolution.

      Relative url(...) and @import references inside a downloaded external stylesheet are resolved against that stylesheet's final URL. References in inline <style> blocks and style attributes are resolved against the page base. If no usable base exists, unresolved relative references remain relative and their resources are not captured.

      Returns:
      the value of the BaseUrl property
    • setBaseUrl

      public void setBaseUrl​(String value)
      Sets the BaseUrl property; see getBaseUrl().
      Parameters:
      value - the new value (not null)
    • getConnectTimeout

      public int getConnectTimeout()
      Specifies the maximum number of seconds allowed for establishing a connection to an HTTP server. The default is 10 seconds.

      Connection timeout only: This setting limits connection establishment; it is not a limit on the total time required to download a page. Use getReadTimeout() to control inactivity while receiving data.

      Returns:
      the value of the ConnectTimeout property
    • setConnectTimeout

      public void setConnectTimeout​(int value)
      Sets the ConnectTimeout property; see getConnectTimeout().
      Parameters:
      value - the new value
    • getDebugHtmlAfter

      public String getDebugHtmlAfter()
      Specifies a local file path where Chilkat saves the HTML after it has been processed for MHT or EML generation. Leave the property empty to disable this diagnostic output.

      Troubleshooting aid: Compare this file with getDebugHtmlBefore() to inspect rewritten URLs, removed scripts, and other transformations applied before the MIME document is assembled. Do not enable diagnostic output to a sensitive or publicly accessible location.Debug-file behavior: An existing debug file is overwritten in place. Parent directories are not created, and a relative path is resolved against the process current working directory. The write is best-effort: failure to create or update the debug file is recorded diagnostically but does not cause the main MHT or EML operation to fail. The write is not atomic, so an I/O error can leave a partial debug file.

      Returns:
      the value of the DebugHtmlAfter property
    • setDebugHtmlAfter

      public void setDebugHtmlAfter​(String value)
      Sets the DebugHtmlAfter property; see getDebugHtmlAfter().
      Parameters:
      value - the new value (not null)
    • getDebugHtmlBefore

      public String getDebugHtmlBefore()
      Specifies a local file path where Chilkat saves the source HTML before it is transformed for MHT or EML generation. Leave the property empty to disable this diagnostic output.

      Troubleshooting aid: Use this together with getDebugHtmlAfter() to determine whether a problem originates in the input HTML or in the conversion and URL-rewriting process.Debug-file behavior: An existing debug file is overwritten in place. Parent directories are not created, and a relative path is resolved against the process current working directory. The write is best-effort: failure to create or update the debug file is recorded diagnostically but does not cause the main MHT or EML operation to fail. The write is not atomic, so an I/O error can leave a partial debug file.

      Returns:
      the value of the DebugHtmlBefore property
    • setDebugHtmlBefore

      public void setDebugHtmlBefore​(String value)
      Sets the DebugHtmlBefore property; see getDebugHtmlBefore().
      Parameters:
      value - the new value (not null)
    • getEmbedImages

      public boolean getEmbedImages()
      Controls whether images referenced by the HTML are downloaded or read from disk and embedded as related MIME parts in both MHT and EML output. The default is true.

      EmbedImages EmbedLocalOnly Image behavior

      false Either No images are embedded. References are made absolute when sufficient base information is available.

      true false Local and HTTP/HTTPS images are embedded when they can be obtained. This is the default combination.

      true true Only local-file images are embedded. HTTP/HTTPS images remain external references.

      Recognized image source: Chilkat captures the ordinary <img src> value. It does not use srcset or sizes to choose a candidate; those attributes are removed. Obvious spacer or 1×1 placeholder sources are detected so the real image reference can be used when available.Self-contained output: MHT or EML output is self-contained with respect to images only when the settings permit embedding and every required image is successfully obtained. A failed image is omitted and its reference remains an absolute live URL.

      Returns:
      the value of the EmbedImages property
    • setEmbedImages

      public void setEmbedImages​(boolean value)
      Sets the EmbedImages property; see getEmbedImages().
      Parameters:
      value - the new value
    • getEmbedLocalOnly

      public boolean getEmbedLocalOnly()
      When true, only images whose references resolve to the local filesystem are embedded. Images referenced through HTTP or HTTPS remain external. The default is false. This property has an effect only when getEmbedImages() is true and applies to both MHT and EML output.

      Scope: This option applies to images, including image URLs found in HTML and CSS. It does not prevent Chilkat from fetching non-image web resources such as external style sheets or, for MHT output, supported frames and scripts.

      Returns:
      the value of the EmbedLocalOnly property
    • setEmbedLocalOnly

      public void setEmbedLocalOnly​(boolean value)
      Sets the EmbedLocalOnly property; see getEmbedLocalOnly().
      Parameters:
      value - the new value
    • getFetchFromCache

      public boolean getFetchFromCache()
      When true, Chilkat attempts to satisfy page and resource requests from the configured disk cache before downloading them. Add one or more cache directories with addCacheRoot(String). The default is false.

      Related settings: getUpdateCache() controls whether network responses are written to the cache. getIgnoreMustRevalidate() and getIgnoreNoCache() control whether certain HTTP cache directives are honored.

      Returns:
      the value of the FetchFromCache property
    • setFetchFromCache

      public void setFetchFromCache​(boolean value)
      Sets the FetchFromCache property; see getFetchFromCache().
      Parameters:
      value - the new value
    • getHeartbeatMs

      public int getHeartbeatMs()
      Specifies the interval, in milliseconds, between AbortCheck event callbacks during supported long-running operations. The default is 0, which disables these periodic callbacks.

      Cancellation: An event handler may request cancellation when an AbortCheck callback occurs. Choose an interval that is responsive without generating excessive callback traffic.

      Returns:
      the value of the HeartbeatMs property
    • setHeartbeatMs

      public void setHeartbeatMs​(int value)
      Sets the HeartbeatMs property; see getHeartbeatMs().
      Parameters:
      value - the new value
    • getIgnoreMustRevalidate

      public boolean getIgnoreMustRevalidate()
      Controls how cached responses containing Cache-Control: must-revalidate are handled. When false (the default), Chilkat revalidates such a cached response before reuse. When true, a still-fresh cached response may be used without revalidation. This property is relevant only when getFetchFromCache() is true.

      Cache semantics: Ignoring must-revalidate can improve offline or high-latency operation, but it may also use content the origin server intended to be checked before reuse.

      Returns:
      the value of the IgnoreMustRevalidate property
    • setIgnoreMustRevalidate

      public void setIgnoreMustRevalidate​(boolean value)
      Sets the IgnoreMustRevalidate property; see getIgnoreMustRevalidate().
      Parameters:
      value - the new value
    • getIgnoreNoCache

      public boolean getIgnoreNoCache()
      Controls whether HTTP response directives that prohibit or restrict caching are ignored. The default is false, which honors the server's caching instructions. When true, Chilkat may store responses that would otherwise be excluded from the disk cache.

      Use carefully: Caching content against the origin server's instructions can retain stale, private, or sensitive data. Enable this only when the application controls the content or has a specific offline-caching requirement.

      Returns:
      the value of the IgnoreNoCache property
    • setIgnoreNoCache

      public void setIgnoreNoCache​(boolean value)
      Sets the IgnoreNoCache property; see getIgnoreNoCache().
      Parameters:
      value - the new value
    • getNoScripts

      public boolean getNoScripts()
      Controls script removal when creating MHT output. When true, script content is removed. When false (the default), inline scripts and supported external scripts may be preserved according to getPreferMHTScripts().

      Static HTML capture: Chilkat does not execute JavaScript or behave as a browser rendering engine. It processes the original HTML source and statically referenced resources. Content created only after JavaScript runs—including AJAX, fetch, XHR, lazy-loaded content, or framework-rendered DOM content—is not captured. MHT output can preserve scripts for execution when the saved archive is later opened; EML output removes scripts.EML behavior: Scripts are always removed when generating EML or email-oriented output, regardless of this property. Framed documents are also removed from EML output.

      Returns:
      the value of the NoScripts property
    • setNoScripts

      public void setNoScripts​(boolean value)
      Sets the NoScripts property; see getNoScripts().
      Parameters:
      value - the new value
    • getNtlmAuth

      public boolean getNtlmAuth()
      When true, Chilkat uses NTLM authentication when the origin HTTP server requests authentication. The default is false. Set getWebSiteLogin(), getWebSitePassword(), and, when required, getWebSiteLoginDomain().

      Origin versus proxy authentication: These credentials authenticate to the website. Proxy credentials are configured separately with getProxyLogin() and getProxyPassword(). Use HTTPS whenever credentials or authenticated content are transmitted.

      Returns:
      the value of the NtlmAuth property
    • setNtlmAuth

      public void setNtlmAuth​(boolean value)
      Sets the NtlmAuth property; see getNtlmAuth().
      Parameters:
      value - the new value
    • getNumCacheLevels

      public int getNumCacheLevels()
      Specifies the number of directory levels used beneath each disk-cache root. The default is 0, which stores cached items directly in the root. A value of 1 distributes items among 256 subdirectories named 0 through 255. A value of 2 uses two such levels, for example 17/204. Chilkat creates the required subdirectories automatically.

      Why use levels? Directory fan-out prevents very large caches from placing thousands of files in one directory, which can degrade filesystem tools and directory operations.

      Returns:
      the value of the NumCacheLevels property
    • setNumCacheLevels

      public void setNumCacheLevels​(int value)
      Sets the NumCacheLevels property; see getNumCacheLevels().
      Parameters:
      value - the new value
    • getNumCacheRoots

      public int getNumCacheRoots()
      Returns the number of disk-cache root directories currently configured through addCacheRoot(String). Multiple roots allow cached items to be distributed across different directories or storage volumes.

      Indexing: Cache-root indexes are zero-based. Use getCacheRoot(int) to retrieve a configured root by index.

      Returns:
      the value of the NumCacheRoots property (read-only)
    • getPreferIpv6

      public boolean getPreferIpv6()
      Controls address-family preference when a hostname resolves to both IPv4 and IPv6 addresses. The default is false, which prefers IPv4. Set to true to prefer IPv6.

      Preference, not a requirement: This setting does not guarantee that IPv6 will be used. The selected address must still be reachable, and fallback behavior depends on the available addresses and connection results.

      Returns:
      the value of the PreferIpv6 property
    • setPreferIpv6

      public void setPreferIpv6​(boolean value)
      Sets the PreferIpv6 property; see getPreferIpv6().
      Parameters:
      value - the new value
    • getPreferMHTScripts

      public boolean getPreferMHTScripts()
      Controls which content is retained when HTML contains a script together with a <noscript> alternative. When true (the default), the script is preferred and the <noscript> content is discarded. When false, the script is removed and the <noscript> content is retained.

      Interaction with NoScripts: getNoScripts() takes precedence when script removal is required. EML generation always removes scripts.Static HTML capture: Chilkat does not execute JavaScript or behave as a browser rendering engine. It processes the original HTML source and statically referenced resources. Content created only after JavaScript runs—including AJAX, fetch, XHR, lazy-loaded content, or framework-rendered DOM content—is not captured. MHT output can preserve scripts for execution when the saved archive is later opened; EML output removes scripts.

      Returns:
      the value of the PreferMHTScripts property
    • setPreferMHTScripts

      public void setPreferMHTScripts​(boolean value)
      Sets the PreferMHTScripts property; see getPreferMHTScripts().
      Parameters:
      value - the new value
    • getProxy

      public String getProxy()
      Specifies an HTTP proxy as hostname:port, for example proxy.example.com:8080. Leave the property empty when no explicit HTTP proxy is required.

      Formatting: Supply only the proxy host and port; do not include an http:// or https:// scheme. If the proxy requires credentials, set getProxyLogin() and getProxyPassword().

      Returns:
      the value of the Proxy property
    • setProxy

      public void setProxy​(String value)
      Sets the Proxy property; see getProxy().
      Parameters:
      value - the new value (not null)
    • getProxyLogin

      public String getProxyLogin()
      Specifies the username used to authenticate with the HTTP proxy configured by getProxy(). Leave empty when the proxy does not require authentication.
      Returns:
      the value of the ProxyLogin property
    • setProxyLogin

      public void setProxyLogin​(String value)
      Sets the ProxyLogin property; see getProxyLogin().
      Parameters:
      value - the new value (not null)
    • getProxyPassword

      public String getProxyPassword()
      Specifies the password used to authenticate with the HTTP proxy configured by getProxy(). Leave empty when the proxy does not require authentication.

      Credential handling: Treat proxy passwords as secrets and avoid writing them to diagnostic logs or persistent configuration in cleartext.

      Returns:
      the value of the ProxyPassword property
    • setProxyPassword

      public void setProxyPassword​(String value)
      Sets the ProxyPassword property; see getProxyPassword().
      Parameters:
      value - the new value (not null)
    • getReadTimeout

      public int getReadTimeout()
      Specifies the maximum number of seconds that an HTTP read may remain inactive while waiting for additional data. The default is 20 seconds. If data continues to arrive, a long download may run longer than this value.

      Inactivity timeout: This is not a total-operation timeout. It applies when the incoming data stream stops making progress.

      Returns:
      the value of the ReadTimeout property
    • setReadTimeout

      public void setReadTimeout​(int value)
      Sets the ReadTimeout property; see getReadTimeout().
      Parameters:
      value - the new value
    • getRequireSslCertVerify

      public boolean getRequireSslCertVerify()
      Controls verification of the TLS server certificate for HTTPS connections. When true, the connection is rejected if certificate verification fails, such as because the certificate is expired or its chain or signature cannot be validated. The default is false.

      Recommended for HTTPS: Enable certificate verification for production connections to prevent accepting an untrusted or invalid server certificate. Disabling verification removes an important protection against impersonation and man-in-the-middle attacks.

      Returns:
      the value of the RequireSslCertVerify property
    • setRequireSslCertVerify

      public void setRequireSslCertVerify​(boolean value)
      Sets the RequireSslCertVerify property; see getRequireSslCertVerify().
      Parameters:
      value - the new value
    • getSocksHostname

      public String getSocksHostname()
      Specifies the hostname or dotted-decimal IPv4 address of the SOCKS proxy. This property is used only when getSocksVersion() is 4 or 5.
      Returns:
      the value of the SocksHostname property
    • setSocksHostname

      public void setSocksHostname​(String value)
      Sets the SocksHostname property; see getSocksHostname().
      Parameters:
      value - the new value (not null)
    • getSocksPassword

      public String getSocksPassword()
      Specifies the password for SOCKS5 proxy authentication. SOCKS4 does not define password authentication, so this property is ignored when getSocksVersion() is 4.
      Returns:
      the value of the SocksPassword property
    • setSocksPassword

      public void setSocksPassword​(String value)
      Sets the SocksPassword property; see getSocksPassword().
      Parameters:
      value - the new value (not null)
    • getSocksPort

      public int getSocksPort()
      Specifies the TCP port of the SOCKS4 or SOCKS5 proxy. The default is 1080. This property is used only when getSocksVersion() is 4 or 5.
      Returns:
      the value of the SocksPort property
    • setSocksPort

      public void setSocksPort​(int value)
      Sets the SocksPort property; see getSocksPort().
      Parameters:
      value - the new value
    • getSocksUsername

      public String getSocksUsername()
      Specifies the username sent to the SOCKS4 or SOCKS5 proxy. It is used only when getSocksVersion() is 4 or 5. For SOCKS5, set getSocksPassword() when password authentication is required.
      Returns:
      the value of the SocksUsername property
    • setSocksUsername

      public void setSocksUsername​(String value)
      Sets the SocksUsername property; see getSocksUsername().
      Parameters:
      value - the new value (not null)
    • getSocksVersion

      public int getSocksVersion()
      Selects whether requests are routed through a SOCKS proxy.

      Value Behavior

      0 Do not use a SOCKS proxy. This is the default.

      4 Connect through a SOCKS4 proxy.

      5 Connect through a SOCKS5 proxy.

      Required companion settings: For versions 4 and 5, set getSocksHostname() and getSocksPort(). Configure username and password properties when the proxy requires them.

      Returns:
      the value of the SocksVersion property
    • setSocksVersion

      public void setSocksVersion​(int value)
      Sets the SocksVersion property; see getSocksVersion().
      Parameters:
      value - the new value
    • getUnpackDirect

      public boolean getUnpackDirect()
      Controls whether MHT parts are extracted directly according to their relative Content-Location values. The default is false.

      Setting Behavior

      false Normal mode: Chilkat selects the primary HTML part, writes related resources beneath the parts subdirectory, rewrites HTML references, and applies path-containment and filename-collision handling.

      true Direct mode: relative Content-Location paths are written beneath the unpack directory without the normal HTML-reference rewriting. The partsSubDir method argument is ignored.

      Full URLs are not valid in direct mode: If a part has a Content-Location beginning with http://, https://, or file:/, Chilkat logs the problem and does not write that part. Direct mode is intended for archives whose locations are already relative; use normal mode for web-captured MHT data.

      Returns:
      the value of the UnpackDirect property
    • setUnpackDirect

      public void setUnpackDirect​(boolean value)
      Sets the UnpackDirect property; see getUnpackDirect().
      Parameters:
      value - the new value
    • getUnpackUseRelPaths

      public boolean getUnpackUseRelPaths()
      Controls how extracted resources are referenced from the rewritten HTML produced by the normal unpacking mode. The default is true, which uses relative paths. Set to false to write absolute local paths.

      Portability: Relative paths keep the unpacked HTML and its resource directory movable as a unit. Absolute paths bind the HTML to the extraction location on the current computer.

      Returns:
      the value of the UnpackUseRelPaths property
    • setUnpackUseRelPaths

      public void setUnpackUseRelPaths​(boolean value)
      Sets the UnpackUseRelPaths property; see getUnpackUseRelPaths().
      Parameters:
      value - the new value
    • getUpdateCache

      public boolean getUpdateCache()
      Controls whether successful HTTP GET responses are written to the configured disk cache. The default is false. When true, add at least one cache root with addCacheRoot(String).

      Reading and writing are separate: getFetchFromCache() controls cache reads. Applications may enable either setting independently or enable both for normal read-through caching.

      Returns:
      the value of the UpdateCache property
    • setUpdateCache

      public void setUpdateCache​(boolean value)
      Sets the UpdateCache property; see getUpdateCache().
      Parameters:
      value - the new value
    • getUseCids

      public boolean getUseCids()
      Controls how embedded resources are identified and referenced in generated MHT and EML MIME documents. The default is false.

      Setting Resource-part headers HTML reference

      false A Content-Location containing the resolved URL or path; no Content-ID. The resource is referenced by its URL or location.

      true A generated, angle-bracketed Content-ID; no Content-Location. The resource URL is rewritten as cid:<id>.

      Mutually exclusive identification models: A generated resource part uses either Content-Location or Content-ID, not both. cid: references are common in HTML email; location-based references preserve the resolved resource URL or path.

      Returns:
      the value of the UseCids property
    • setUseCids

      public void setUseCids​(boolean value)
      Sets the UseCids property; see getUseCids().
      Parameters:
      value - the new value
    • getUseFilename

      public boolean getUseFilename()
      Controls whether the generated Content-Disposition for an embedded resource includes a filename parameter. The default is true. Setting this property to true forces an inline disposition to be emitted even when getUseInline() is false.

      UseInline UseFilename Generated Content-Disposition

      true true inline; filename="<name>"

      true false inline

      false true inline; filename="<name>"

      false false No Content-Disposition header.

      Content-Type name parameter: Every embedded resource always receives name="<name>" on its Content-Type, regardless of UseFilename and UseInline. The MIME filename is presentation metadata, not the source filesystem path.

      Returns:
      the value of the UseFilename property
    • setUseFilename

      public void setUseFilename​(boolean value)
      Sets the UseFilename property; see getUseFilename().
      Parameters:
      value - the new value
    • getUseIEProxy

      public boolean getUseIEProxy()
      When true, Chilkat uses the proxy configuration associated with Windows Internet Options / Internet Explorer. This setting is relevant on Windows systems.

      Explicit configuration: Use getProxy() when the application should specify a particular proxy directly rather than relying on the current user's Windows proxy settings.

      Returns:
      the value of the UseIEProxy property
    • setUseIEProxy

      public void setUseIEProxy​(boolean value)
      Sets the UseIEProxy property; see getUseIEProxy().
      Parameters:
      value - the new value
    • getUseInline

      public boolean getUseInline()
      Controls whether embedded resource parts receive an inline Content-Disposition when getUseFilename() does not independently require the header. The default is true.

      UseInline UseFilename Generated Content-Disposition

      true true inline; filename="<name>"

      true false inline

      false true inline; filename="<name>"

      false false No Content-Disposition header.

      No attachment mode: Whenever Chilkat emits this header, the disposition is inline; these properties do not produce attachment. Every embedded resource always receives a name parameter on its Content-Type, independent of both settings.

      Returns:
      the value of the UseInline property
    • setUseInline

      public void setUseInline​(boolean value)
      Sets the UseInline property; see getUseInline().
      Parameters:
      value - the new value
    • getWebSiteLogin

      public String getWebSiteLogin()
      Specifies the username used when the origin website requires HTTP authentication. It is optional for public pages. For NTLM authentication, also set getNtlmAuth() to true and provide a domain when required.
      Returns:
      the value of the WebSiteLogin property
    • setWebSiteLogin

      public void setWebSiteLogin​(String value)
      Sets the WebSiteLogin property; see getWebSiteLogin().
      Parameters:
      value - the new value (not null)
    • getWebSiteLoginDomain

      public String getWebSiteLoginDomain()
      Specifies the optional Windows domain used with NTLM website authentication. This property is relevant when getNtlmAuth() is true.
      Returns:
      the value of the WebSiteLoginDomain property
    • setWebSiteLoginDomain

      public void setWebSiteLoginDomain​(String value)
      Sets the WebSiteLoginDomain property; see getWebSiteLoginDomain().
      Parameters:
      value - the new value (not null)
    • getWebSitePassword

      public String getWebSitePassword()
      Specifies the password used with getWebSiteLogin() when the origin website requires HTTP authentication.

      Credential handling: Treat this value as a secret. Use HTTPS for authenticated pages and avoid exposing credentials through debug output or application logs.

      Returns:
      the value of the WebSitePassword property
    • setWebSitePassword

      public void setWebSitePassword​(String value)
      Sets the WebSitePassword property; see getWebSitePassword().
      Parameters:
      value - the new value (not null)
    • addCacheRoot

      public void addCacheRoot​(String dir)
      Adds dir as a persistent root directory for the disk cache. Call this method once for each cache location the application wants Chilkat to use. Multiple roots may be placed on different directories or storage volumes.

      Enabling cache use: Adding a root defines a storage location but does not by itself read or write cached content. Use getFetchFromCache() and getUpdateCache() to enable cache reads and writes. Persistent collection: Cache roots remain configured across conversions, duplicates are accepted, and no method removes an individual root. restoreDefaults() does not clear them. Use a new Mht object when the cache-root list must be reset.

      Parameters:
      dir - the dir argument (not null)
    • addCustomHeader

      public void addCustomHeader​(String name, String value)
      Adds an HTTP request header to the persistent custom-header collection used for the main page, redirect targets, and every HTTP/HTTPS dependent-resource request, including requests to third-party hosts. name is the field name without a trailing colon, and value is the field value.

      Field name Behavior when added again

      User-Agent or Accept-Language Replaces the existing value.

      Any other permitted field Appends another header line with the same name; it does not replace the earlier line.

      Rejected fields: Authorization and Content-Length are rejected case-insensitively and are not added. Use the website-login properties for supported HTTP authentication rather than attempting to add Authorization here. Cross-host security: Permitted fields such as Cookie, Host, and application-defined headers are reused for every destination contacted during the capture. Do not place a secret in a custom header unless it is safe to send to the primary host, every redirect target, and every third-party resource host. Header syntax: Raw CR or LF characters must not be placed in a header name or value. Header-splitting prevention should be treated as the caller's responsibility; this API does not document a validation guarantee.

      Custom headers persist until removed with removeCustomHeader(String), cleared with clearCustomHeaders(), or the object is discarded. restoreDefaults() does not clear them.

      Parameters:
      name - the name argument (not null)
      value - the value argument (not null)
    • addExternalStyleSheet

      public void addExternalStyleSheet​(String url)
      Adds the style-sheet URL in url to the persistent list of external CSS resources downloaded and embedded during conversion. This is normally unnecessary because Chilkat automatically discovers <link rel="stylesheet"> references present in the static HTML.

      When to use it: Call this method when the application knows about a style sheet that is not referenced in the original HTML—for example, one that browser-side JavaScript would normally insert. Chilkat does not execute that JavaScript during capture. Recursive CSS processing: The downloaded style sheet is inlined and inspected for @import and url(...) references. Imported sheets are processed recursively, and relative references are resolved against the URL of the style sheet that contains them. Persistent collection: Entries remain configured across conversions. Duplicate URLs are accepted and are not deduplicated. There is no individual remove method; restoreDefaults() clears the entire external-style-sheet list.

      Parameters:
      url - the url argument (not null)
    • clearCustomHeaders

      public void clearCustomHeaders()
      Removes all HTTP request headers previously added with addCustomHeader(String, String). Automatically generated and built-in HTTP headers are not removed.

      The custom-header collection otherwise persists across conversions and is not cleared by restoreDefaults().

    • excludeImagesMatching

      public void excludeImagesMatching​(String pattern)
      Adds pattern to the persistent list of exclusion patterns used while gathering embeddable resources. Despite the historical method name, the test is applied to embeddable resources generally, not only to images. Each candidate is tested against its fully resolved reference: an absolute URL for web content or the resolved local path for a local resource.

      Test Matching rule

      Wildcard / glob Case-insensitive match against the entire resolved reference. * matches zero or more characters, and ? matches exactly one character.

      Plain substring Case-sensitive containment test anywhere within the resolved reference.

      Practical examples: *banner* performs a case-insensitive contains-style match; logo.png performs a case-sensitive substring test; */ads/* can match a path; *doubleclick* can match a host; and *.gif can match an extension. The scheme, host, path, filename, query string, and fragment participate when present. State and scope: Patterns apply to local and HTTP/HTTPS resources. Multiple calls accumulate and are OR-ed; duplicates are accepted. There is no individual remove method. Call restoreDefaults() to clear the exclusion list, or use a new Mht object.

      Parameters:
      pattern - the pattern argument (not null)
    • getAndSaveEML

      public void getAndSaveEML​(String url_or_htmlFilepath, String emlPath)
      Creates EML output from the HTTP/HTTPS page or local HTML file in url_or_htmlFilepath and saves it to the destination path in emlPath. Style sheets and their CSS resources are captured. Images are embedded according to getEmbedImages() and getEmbedLocalOnly(). Scripts and framed documents are removed.

      How url_or_htmlFilepath is classified: Chilkat treats url_or_htmlFilepath as a web URL only when it begins, case-insensitively, with http: or https:. Every other value is treated as a local file path. file:// URLs are not supported; pass a plain filesystem path instead. Relative paths are resolved against the process current working directory, and the local file must already exist and be readable. A value such as www.example.com/page.html has no recognized scheme and is therefore treated as a local path.Static HTML capture: Chilkat does not execute JavaScript or behave as a browser rendering engine. It processes the original HTML source and statically referenced resources. Content created only after JavaScript runs—including AJAX, fetch, XHR, lazy-loaded content, or framework-rendered DOM content—is not captured. MHT output can preserve scripts for execution when the saved archive is later opened; EML output removes scripts.Return value: Returns true on success and false on failure.Dependent-resource failures: If an image, style sheet, imported CSS file, frame, script, or other dependent resource cannot be downloaded or included, Chilkat omits that MIME part, creates no empty placeholder, restores the HTML reference to the resource's original absolute URL, records the problem in LastErrorText or the diagnostic log, and continues. The overall conversion still reports success. This resilience applies only to dependent resources; failure to fetch the primary URL or read the primary local HTML file fails the operation.Destination file behavior: Chilkat first generates the complete MIME output in memory and writes the destination only after generation succeeds. An existing destination file is truncated and replaced; data is never appended and no confirmation is requested. Parent directories are not created. Relative paths are resolved against the process current working directory. If generation fails, an existing destination file is left untouched. The final write is direct rather than atomic, so a write-time error such as a full disk or permission failure can leave a truncated or partially written file. A read-only or otherwise unwritable destination causes the method to return false. Using the same local file as both source and destination is mechanically allowed because the source is read first, but the subsequent write destroys the original HTML file. On Windows, this method also rejects destination paths containing characters that are invalid in Windows filenames, such as ?, before generation begins.Redirects and capture cookies: HTTP redirects are followed for the primary page and dependent resources. After the primary request redirects, relative page references are resolved against the final landing URL. Cookies received during the capture are retained and sent on subsequent requests in that same capture, including redirect and dependent-resource requests. The redirect limit, exact followed status codes, and HTTPS-to-HTTP downgrade policy are governed by the underlying HTTP engine and are not configurable through Mht.EML is an HTML-email draft: The output adds the current RFC-822 Date and X-Unsent: 1, removes scripts, frames, and HTML comments, and contains an HTML root with related resources. It does not create a plain-text alternative, does not generate Message-ID, and does not automatically make a fully addressed, ready-to-send message. Load it into Chilkat.Email or a mail client and set the required addressing and subject information before sending.

      Parameters:
      url_or_htmlFilepath - the url_or_htmlFilepath argument (not null)
      emlPath - the emlPath argument (not null)
      Throws:
      ChilkatException - if the operation fails; ChilkatException.getLastErrorText() says why
    • getAndSaveMHT

      public void getAndSaveMHT​(String url_or_htmlFilepath, String mhtPath)
      Creates MHT output from the HTTP/HTTPS page or local HTML file in url_or_htmlFilepath and saves it to the destination path in mhtPath. Supported statically referenced resources are captured according to the current MHT properties.

      How url_or_htmlFilepath is classified: Chilkat treats url_or_htmlFilepath as a web URL only when it begins, case-insensitively, with http: or https:. Every other value is treated as a local file path. file:// URLs are not supported; pass a plain filesystem path instead. Relative paths are resolved against the process current working directory, and the local file must already exist and be readable. A value such as www.example.com/page.html has no recognized scheme and is therefore treated as a local path.Static HTML capture: Chilkat does not execute JavaScript or behave as a browser rendering engine. It processes the original HTML source and statically referenced resources. Content created only after JavaScript runs—including AJAX, fetch, XHR, lazy-loaded content, or framework-rendered DOM content—is not captured. MHT output can preserve scripts for execution when the saved archive is later opened; EML output removes scripts.Script output: Script handling is controlled by getNoScripts() and getPreferMHTScripts().Dependent-resource failures: If an image, style sheet, imported CSS file, frame, script, or other dependent resource cannot be downloaded or included, Chilkat omits that MIME part, creates no empty placeholder, restores the HTML reference to the resource's original absolute URL, records the problem in LastErrorText or the diagnostic log, and continues. The overall conversion still reports success. This resilience applies only to dependent resources; failure to fetch the primary URL or read the primary local HTML file fails the operation.Destination file behavior: Chilkat first generates the complete MIME output in memory and writes the destination only after generation succeeds. An existing destination file is truncated and replaced; data is never appended and no confirmation is requested. Parent directories are not created. Relative paths are resolved against the process current working directory. If generation fails, an existing destination file is left untouched. The final write is direct rather than atomic, so a write-time error such as a full disk or permission failure can leave a truncated or partially written file. A read-only or otherwise unwritable destination causes the method to return false. Using the same local file as both source and destination is mechanically allowed because the source is read first, but the subsequent write destroys the original HTML file. On Windows, this method also rejects destination paths containing characters that are invalid in Windows filenames, such as ?, before generation begins.Redirects and capture cookies: HTTP redirects are followed for the primary page and dependent resources. After the primary request redirects, relative page references are resolved against the final landing URL. Cookies received during the capture are retained and sent on subsequent requests in that same capture, including redirect and dependent-resource requests. The redirect limit, exact followed status codes, and HTTPS-to-HTTP downgrade policy are governed by the underlying HTTP engine and are not configurable through Mht.MHT MIME structure: The result is a MIME document whose root is HTML (or XML) and whose successfully embedded resources are related parts. When resources are present, the message is normally multipart/related; when none are embedded, it can collapse to a single text/html part. MHT output omits the Date and X-Unsent headers and can preserve scripts, frames, and comments according to the script settings.

      Parameters:
      url_or_htmlFilepath - the url_or_htmlFilepath argument (not null)
      mhtPath - the mhtPath argument (not null)
      Throws:
      ChilkatException - if the operation fails; ChilkatException.getLastErrorText() says why
    • getAndZipEML

      public void getAndZipEML​(String url_or_htmlFilepath, String zipEntryFilename, String zipFilename)
      Creates EML output from the HTTP/HTTPS page or local HTML file in url_or_htmlFilepath and stores it as the ZIP entry named by zipEntryFilename inside the archive file in zipFilename. The ZIP is created if it does not exist; otherwise the new entry is appended. Style sheets are captured, images follow getEmbedImages() and getEmbedLocalOnly(), and scripts and frames are removed.

      How url_or_htmlFilepath is classified: Chilkat treats url_or_htmlFilepath as a web URL only when it begins, case-insensitively, with http: or https:. Every other value is treated as a local file path. file:// URLs are not supported; pass a plain filesystem path instead. Relative paths are resolved against the process current working directory, and the local file must already exist and be readable. A value such as www.example.com/page.html has no recognized scheme and is therefore treated as a local path.Static HTML capture: Chilkat does not execute JavaScript or behave as a browser rendering engine. It processes the original HTML source and statically referenced resources. Content created only after JavaScript runs—including AJAX, fetch, XHR, lazy-loaded content, or framework-rendered DOM content—is not captured. MHT output can preserve scripts for execution when the saved archive is later opened; EML output removes scripts.Argument order: url_or_htmlFilepath is the source, zipEntryFilename is the entry name inside the ZIP, and zipFilename is the ZIP file path.Dependent-resource failures: If an image, style sheet, imported CSS file, frame, script, or other dependent resource cannot be downloaded or included, Chilkat omits that MIME part, creates no empty placeholder, restores the HTML reference to the resource's original absolute URL, records the problem in LastErrorText or the diagnostic log, and continues. The overall conversion still reports success. This resilience applies only to dependent resources; failure to fetch the primary URL or read the primary local HTML file fails the operation.Redirects and capture cookies: HTTP redirects are followed for the primary page and dependent resources. After the primary request redirects, relative page references are resolved against the final landing URL. Cookies received during the capture are retained and sent on subsequent requests in that same capture, including redirect and dependent-resource requests. The redirect limit, exact followed status codes, and HTTPS-to-HTTP downgrade policy are governed by the underlying HTTP engine and are not configurable through Mht.Entry-name collision: If zipEntryFilename already exists in a valid opened ZIP archive, the method returns false. It neither replaces the existing entry nor creates a duplicate. Archive handling: A valid existing archive is loaded, the new entry is added, and the entire archive is rewritten after capture succeeds. If the path does not exist, a new unencrypted ZIP is created. If a file exists but cannot be opened as a valid ZIP, Chilkat creates a new archive at that path, overwriting that file. Use forward slashes in zipEntryFilename for entry subdirectories; explicit directory entries are unnecessary. Failure and write safety: A capture failure leaves a valid existing archive untouched. The final archive write is not atomic and rewrites the complete ZIP, so a write-time I/O failure can damage or partially replace the archive. Parent directories are not created. On Windows, an output ZIP path containing invalid filename characters such as ? is rejected.EML is an HTML-email draft: The output adds the current RFC-822 Date and X-Unsent: 1, removes scripts, frames, and HTML comments, and contains an HTML root with related resources. It does not create a plain-text alternative, does not generate Message-ID, and does not automatically make a fully addressed, ready-to-send message. Load it into Chilkat.Email or a mail client and set the required addressing and subject information before sending.

      Parameters:
      url_or_htmlFilepath - the url_or_htmlFilepath argument (not null)
      zipEntryFilename - the zipEntryFilename argument (not null)
      zipFilename - the zipFilename argument (not null)
      Throws:
      ChilkatException - if the operation fails; ChilkatException.getLastErrorText() says why
    • getAndZipMHT

      public void getAndZipMHT​(String url_or_htmlFilepath, String zipEntryFilename, String zipFilename)
      Creates MHT output from the HTTP/HTTPS page or local HTML file in url_or_htmlFilepath and stores it as the ZIP entry named by zipEntryFilename inside the archive file in zipFilename. The ZIP is created if it does not exist; otherwise the new entry is appended. Supported statically referenced resources are captured according to the current properties.

      How url_or_htmlFilepath is classified: Chilkat treats url_or_htmlFilepath as a web URL only when it begins, case-insensitively, with http: or https:. Every other value is treated as a local file path. file:// URLs are not supported; pass a plain filesystem path instead. Relative paths are resolved against the process current working directory, and the local file must already exist and be readable. A value such as www.example.com/page.html has no recognized scheme and is therefore treated as a local path.Static HTML capture: Chilkat does not execute JavaScript or behave as a browser rendering engine. It processes the original HTML source and statically referenced resources. Content created only after JavaScript runs—including AJAX, fetch, XHR, lazy-loaded content, or framework-rendered DOM content—is not captured. MHT output can preserve scripts for execution when the saved archive is later opened; EML output removes scripts.Argument order: url_or_htmlFilepath is the source, zipEntryFilename is the entry name inside the ZIP, and zipFilename is the ZIP file path.Dependent-resource failures: If an image, style sheet, imported CSS file, frame, script, or other dependent resource cannot be downloaded or included, Chilkat omits that MIME part, creates no empty placeholder, restores the HTML reference to the resource's original absolute URL, records the problem in LastErrorText or the diagnostic log, and continues. The overall conversion still reports success. This resilience applies only to dependent resources; failure to fetch the primary URL or read the primary local HTML file fails the operation.Redirects and capture cookies: HTTP redirects are followed for the primary page and dependent resources. After the primary request redirects, relative page references are resolved against the final landing URL. Cookies received during the capture are retained and sent on subsequent requests in that same capture, including redirect and dependent-resource requests. The redirect limit, exact followed status codes, and HTTPS-to-HTTP downgrade policy are governed by the underlying HTTP engine and are not configurable through Mht.Entry-name collision: If zipEntryFilename already exists in a valid opened ZIP archive, the method returns false. It neither replaces the existing entry nor creates a duplicate. Archive handling: A valid existing archive is loaded, the new entry is added, and the entire archive is rewritten after capture succeeds. If the path does not exist, a new unencrypted ZIP is created. If a file exists but cannot be opened as a valid ZIP, Chilkat creates a new archive at that path, overwriting that file. Use forward slashes in zipEntryFilename for entry subdirectories; explicit directory entries are unnecessary. Failure and write safety: A capture failure leaves a valid existing archive untouched. The final archive write is not atomic and rewrites the complete ZIP, so a write-time I/O failure can damage or partially replace the archive. Parent directories are not created. On Windows, an output ZIP path containing invalid filename characters such as ? is rejected.MHT MIME structure: The result is a MIME document whose root is HTML (or XML) and whose successfully embedded resources are related parts. When resources are present, the message is normally multipart/related; when none are embedded, it can collapse to a single text/html part. MHT output omits the Date and X-Unsent headers and can preserve scripts, frames, and comments according to the script settings.

      Parameters:
      url_or_htmlFilepath - the url_or_htmlFilepath argument (not null)
      zipEntryFilename - the zipEntryFilename argument (not null)
      zipFilename - the zipFilename argument (not null)
      Throws:
      ChilkatException - if the operation fails; ChilkatException.getLastErrorText() says why
    • getCacheRoot

      public String getCacheRoot​(int index)
      Returns the cache-root directory at zero-based index index. Cache roots are added with addCacheRoot(String), and their count is available from getNumCacheRoots().

      Index and result handling: Use an index from 0 through NumCacheRoots - 1. The returned string is cleared when the call begins. If no cache root is configured or index is outside the valid range, LastMethodSuccess is false and the returned string is empty. On success, LastMethodSuccess is true and the returned string contains the root path. Check LastMethodSuccess, not whether the returned string is empty; use LastErrorText for the failure diagnostic.

      Parameters:
      index - the index argument
      Returns:
      the result (never null)
      Throws:
      ChilkatException - if the operation fails; ChilkatException.getLastErrorText() says why
    • getEML

      public String getEML​(String url_or_htmlFilepath)
      Creates an EML MIME message from the HTTP/HTTPS page or local HTML file in url_or_htmlFilepath and returns the complete EML text in memory. Style sheets and their referenced CSS resources are captured. Images are embedded according to getEmbedImages() and getEmbedLocalOnly(). Scripts and framed documents are removed.

      How url_or_htmlFilepath is classified: Chilkat treats url_or_htmlFilepath as a web URL only when it begins, case-insensitively, with http: or https:. Every other value is treated as a local file path. file:// URLs are not supported; pass a plain filesystem path instead. Relative paths are resolved against the process current working directory, and the local file must already exist and be readable. A value such as www.example.com/page.html has no recognized scheme and is therefore treated as a local path.Static HTML capture: Chilkat does not execute JavaScript or behave as a browser rendering engine. It processes the original HTML source and statically referenced resources. Content created only after JavaScript runs—including AJAX, fetch, XHR, lazy-loaded content, or framework-rendered DOM content—is not captured. MHT output can preserve scripts for execution when the saved archive is later opened; EML output removes scripts.Redirects and capture cookies: HTTP redirects are followed for the primary page and dependent resources. After the primary request redirects, relative page references are resolved against the final landing URL. Cookies received during the capture are retained and sent on subsequent requests in that same capture, including redirect and dependent-resource requests. The redirect limit, exact followed status codes, and HTTPS-to-HTTP downgrade policy are governed by the underlying HTTP engine and are not configurable through Mht.Memory use: The complete MIME message is returned as a string. For large pages, getAndSaveEML(String, String) avoids keeping the final EML text solely in the return value.Dependent-resource failures: If an image, style sheet, imported CSS file, frame, script, or other dependent resource cannot be downloaded or included, Chilkat omits that MIME part, creates no empty placeholder, restores the HTML reference to the resource's original absolute URL, records the problem in LastErrorText or the diagnostic log, and continues. The overall conversion still reports success. This resilience applies only to dependent resources; failure to fetch the primary URL or read the primary local HTML file fails the operation.Check LastMethodSuccess: The returned string is cleared when the call begins and may be empty or partially populated if the method fails. A nonempty string does not prove success, and an empty string should not be used as the failure test. Use LastMethodSuccess as the authoritative result; when it is false, inspect LastErrorText. A failed call never returns the previous call's string.Saving the returned string: The returned MIME document uses CRLF line endings and UTF-8 text without a byte-order mark. Preserve the text as opaque UTF-8 bytes without newline translation or reflow. Raw non-ASCII text can occur. Prefer the corresponding file-writing method when exact on-disk bytes are required.EML is an HTML-email draft: The output adds the current RFC-822 Date and X-Unsent: 1, removes scripts, frames, and HTML comments, and contains an HTML root with related resources. It does not create a plain-text alternative, does not generate Message-ID, and does not automatically make a fully addressed, ready-to-send message. Load it into Chilkat.Email or a mail client and set the required addressing and subject information before sending.

      Parameters:
      url_or_htmlFilepath - the url_or_htmlFilepath argument (not null)
      Returns:
      the result (never null)
      Throws:
      ChilkatException - if the operation fails; ChilkatException.getLastErrorText() says why
    • getMHT

      public String getMHT​(String url_or_htmlFilepath)
      Creates an MHT web archive from the HTTP/HTTPS page or local HTML file in url_or_htmlFilepath and returns the complete MHT MIME text in memory. Supported statically referenced resources are captured according to the current properties.

      How url_or_htmlFilepath is classified: Chilkat treats url_or_htmlFilepath as a web URL only when it begins, case-insensitively, with http: or https:. Every other value is treated as a local file path. file:// URLs are not supported; pass a plain filesystem path instead. Relative paths are resolved against the process current working directory, and the local file must already exist and be readable. A value such as www.example.com/page.html has no recognized scheme and is therefore treated as a local path.Static HTML capture: Chilkat does not execute JavaScript or behave as a browser rendering engine. It processes the original HTML source and statically referenced resources. Content created only after JavaScript runs—including AJAX, fetch, XHR, lazy-loaded content, or framework-rendered DOM content—is not captured. MHT output can preserve scripts for execution when the saved archive is later opened; EML output removes scripts.Redirects and capture cookies: HTTP redirects are followed for the primary page and dependent resources. After the primary request redirects, relative page references are resolved against the final landing URL. Cookies received during the capture are retained and sent on subsequent requests in that same capture, including redirect and dependent-resource requests. The redirect limit, exact followed status codes, and HTTPS-to-HTTP downgrade policy are governed by the underlying HTTP engine and are not configurable through Mht.Memory use: The complete archive is returned as a string. For large pages, getAndSaveMHT(String, String) writes the result directly to a file.Dependent-resource failures: If an image, style sheet, imported CSS file, frame, script, or other dependent resource cannot be downloaded or included, Chilkat omits that MIME part, creates no empty placeholder, restores the HTML reference to the resource's original absolute URL, records the problem in LastErrorText or the diagnostic log, and continues. The overall conversion still reports success. This resilience applies only to dependent resources; failure to fetch the primary URL or read the primary local HTML file fails the operation.Check LastMethodSuccess: The returned string is cleared when the call begins and may be empty or partially populated if the method fails. A nonempty string does not prove success, and an empty string should not be used as the failure test. Use LastMethodSuccess as the authoritative result; when it is false, inspect LastErrorText. A failed call never returns the previous call's string.Saving the returned string: The returned MIME document uses CRLF line endings and UTF-8 text without a byte-order mark. Preserve the text as opaque UTF-8 bytes without newline translation or reflow. Raw non-ASCII text can occur. Prefer the corresponding file-writing method when exact on-disk bytes are required.MHT MIME structure: The result is a MIME document whose root is HTML (or XML) and whose successfully embedded resources are related parts. When resources are present, the message is normally multipart/related; when none are embedded, it can collapse to a single text/html part. MHT output omits the Date and X-Unsent headers and can preserve scripts, frames, and comments according to the script settings.

      Parameters:
      url_or_htmlFilepath - the url_or_htmlFilepath argument (not null)
      Returns:
      the result (never null)
      Throws:
      ChilkatException - if the operation fails; ChilkatException.getLastErrorText() says why
    • htmlToEML

      public String htmlToEML​(String htmlText)
      Creates an EML MIME message from the in-memory HTML string in htmlText and returns the complete EML text. Style sheets and their CSS resources are captured. Images are embedded according to getEmbedImages() and getEmbedLocalOnly(). Scripts and framed documents are removed.

      Relative references: Set getBaseUrl() when the HTML has no usable <base href> and its relative resources should resolve against a web origin. An HTML <base> element takes precedence. Without a usable base, unresolved relative resources are not captured and their references remain relative.Static HTML capture: Chilkat does not execute JavaScript or behave as a browser rendering engine. It processes the original HTML source and statically referenced resources. Content created only after JavaScript runs—including AJAX, fetch, XHR, lazy-loaded content, or framework-rendered DOM content—is not captured. MHT output can preserve scripts for execution when the saved archive is later opened; EML output removes scripts.Dependent-resource failures: If an image, style sheet, imported CSS file, frame, script, or other dependent resource cannot be downloaded or included, Chilkat omits that MIME part, creates no empty placeholder, restores the HTML reference to the resource's original absolute URL, records the problem in LastErrorText or the diagnostic log, and continues. The overall conversion still reports success, although the resulting MIME document is not fully self-contained for that resource.Check LastMethodSuccess: The returned string is cleared when the call begins and may be empty or partially populated if the method fails. A nonempty string does not prove success, and an empty string should not be used as the failure test. Use LastMethodSuccess as the authoritative result; when it is false, inspect LastErrorText. A failed call never returns the previous call's string.Redirecting dependent resources: HTTP redirects encountered while downloading images, style sheets, imported CSS, frames, or other supported resources are followed to the final content. Cookies established during the conversion are retained for later requests in the same conversion.Saving the returned string: The returned MIME document uses CRLF line endings and UTF-8 text without a byte-order mark. Preserve the text as opaque UTF-8 bytes without newline translation or reflow. Raw non-ASCII text can occur. Prefer the corresponding file-writing method when exact on-disk bytes are required.EML is an HTML-email draft: The output adds the current RFC-822 Date and X-Unsent: 1, removes scripts, frames, and HTML comments, and contains an HTML root with related resources. It does not create a plain-text alternative, does not generate Message-ID, and does not automatically make a fully addressed, ready-to-send message. Load it into Chilkat.Email or a mail client and set the required addressing and subject information before sending.

      Parameters:
      htmlText - the htmlText argument (not null)
      Returns:
      the result (never null)
      Throws:
      ChilkatException - if the operation fails; ChilkatException.getLastErrorText() says why
    • htmlToEMLFile

      public void htmlToEMLFile​(String html, String emlFilename)
      Creates EML output from the in-memory HTML string in html and saves it to the file path in emlFilename. Style sheets and their CSS resources are captured. Images are embedded according to getEmbedImages() and getEmbedLocalOnly(). Scripts and framed documents are removed.

      Relative references: Set getBaseUrl() when the HTML has no usable <base href> and its relative resources should resolve against a web origin. An HTML <base> element takes precedence. Without a usable base, unresolved relative resources are not captured and their references remain relative.Static HTML capture: Chilkat does not execute JavaScript or behave as a browser rendering engine. It processes the original HTML source and statically referenced resources. Content created only after JavaScript runs—including AJAX, fetch, XHR, lazy-loaded content, or framework-rendered DOM content—is not captured. MHT output can preserve scripts for execution when the saved archive is later opened; EML output removes scripts.Dependent-resource failures: If an image, style sheet, imported CSS file, frame, script, or other dependent resource cannot be downloaded or included, Chilkat omits that MIME part, creates no empty placeholder, restores the HTML reference to the resource's original absolute URL, records the problem in LastErrorText or the diagnostic log, and continues. The overall conversion still reports success, although the resulting MIME document is not fully self-contained for that resource.Destination file behavior: Chilkat first generates the complete MIME output in memory and writes the destination only after generation succeeds. An existing destination file is truncated and replaced; data is never appended and no confirmation is requested. Parent directories are not created. Relative paths are resolved against the process current working directory. If generation fails, an existing destination file is left untouched. The final write is direct rather than atomic, so a write-time error such as a full disk or permission failure can leave a truncated or partially written file. A read-only or otherwise unwritable destination causes the method to return false.Redirecting dependent resources: HTTP redirects encountered while downloading supported dependent resources are followed. Cookies established during the conversion are reused for later requests in that same conversion.EML is an HTML-email draft: The output adds the current RFC-822 Date and X-Unsent: 1, removes scripts, frames, and HTML comments, and contains an HTML root with related resources. It does not create a plain-text alternative, does not generate Message-ID, and does not automatically make a fully addressed, ready-to-send message. Load it into Chilkat.Email or a mail client and set the required addressing and subject information before sending.

      Parameters:
      html - the html argument (not null)
      emlFilename - the emlFilename argument (not null)
      Throws:
      ChilkatException - if the operation fails; ChilkatException.getLastErrorText() says why
    • htmlToMHT

      public String htmlToMHT​(String htmlText)
      Creates an MHT web archive from the in-memory HTML string in htmlText and returns the complete MHT MIME text. Supported statically referenced resources are captured according to the current properties.

      Relative references: Set getBaseUrl() when the HTML has no usable <base href> and its relative resources should resolve against a web origin. An HTML <base> element takes precedence. Without a usable base, unresolved relative resources are not captured and their references remain relative.Static HTML capture: Chilkat does not execute JavaScript or behave as a browser rendering engine. It processes the original HTML source and statically referenced resources. Content created only after JavaScript runs—including AJAX, fetch, XHR, lazy-loaded content, or framework-rendered DOM content—is not captured. MHT output can preserve scripts for execution when the saved archive is later opened; EML output removes scripts.Scripts: Script handling is controlled by getNoScripts() and getPreferMHTScripts().Dependent-resource failures: If an image, style sheet, imported CSS file, frame, script, or other dependent resource cannot be downloaded or included, Chilkat omits that MIME part, creates no empty placeholder, restores the HTML reference to the resource's original absolute URL, records the problem in LastErrorText or the diagnostic log, and continues. The overall conversion still reports success, although the resulting MIME document is not fully self-contained for that resource.Check LastMethodSuccess: The returned string is cleared when the call begins and may be empty or partially populated if the method fails. A nonempty string does not prove success, and an empty string should not be used as the failure test. Use LastMethodSuccess as the authoritative result; when it is false, inspect LastErrorText. A failed call never returns the previous call's string.Redirecting dependent resources: HTTP redirects encountered while downloading images, style sheets, imported CSS, frames, or other supported resources are followed to the final content. Cookies established during the conversion are retained for later requests in the same conversion.Saving the returned string: The returned MIME document uses CRLF line endings and UTF-8 text without a byte-order mark. Preserve the text as opaque UTF-8 bytes without newline translation or reflow. Raw non-ASCII text can occur. Prefer the corresponding file-writing method when exact on-disk bytes are required.MHT MIME structure: The result is a MIME document whose root is HTML (or XML) and whose successfully embedded resources are related parts. When resources are present, the message is normally multipart/related; when none are embedded, it can collapse to a single text/html part. MHT output omits the Date and X-Unsent headers and can preserve scripts, frames, and comments according to the script settings.

      Parameters:
      htmlText - the htmlText argument (not null)
      Returns:
      the result (never null)
      Throws:
      ChilkatException - if the operation fails; ChilkatException.getLastErrorText() says why
    • htmlToMHTFile

      public void htmlToMHTFile​(String html, String mhtFilename)
      Creates MHT output from the in-memory HTML string in html and saves it to the file path in mhtFilename. Supported statically referenced resources are captured according to the current properties.

      Relative references: Set getBaseUrl() when the HTML has no usable <base href> and its relative resources should resolve against a web origin. An HTML <base> element takes precedence. Without a usable base, unresolved relative resources are not captured and their references remain relative.Static HTML capture: Chilkat does not execute JavaScript or behave as a browser rendering engine. It processes the original HTML source and statically referenced resources. Content created only after JavaScript runs—including AJAX, fetch, XHR, lazy-loaded content, or framework-rendered DOM content—is not captured. MHT output can preserve scripts for execution when the saved archive is later opened; EML output removes scripts.Scripts: Script handling is controlled by getNoScripts() and getPreferMHTScripts().Dependent-resource failures: If an image, style sheet, imported CSS file, frame, script, or other dependent resource cannot be downloaded or included, Chilkat omits that MIME part, creates no empty placeholder, restores the HTML reference to the resource's original absolute URL, records the problem in LastErrorText or the diagnostic log, and continues. The overall conversion still reports success, although the resulting MIME document is not fully self-contained for that resource.Destination file behavior: Chilkat first generates the complete MIME output in memory and writes the destination only after generation succeeds. An existing destination file is truncated and replaced; data is never appended and no confirmation is requested. Parent directories are not created. Relative paths are resolved against the process current working directory. If generation fails, an existing destination file is left untouched. The final write is direct rather than atomic, so a write-time error such as a full disk or permission failure can leave a truncated or partially written file. A read-only or otherwise unwritable destination causes the method to return false.Redirecting dependent resources: HTTP redirects encountered while downloading supported dependent resources are followed. Cookies established during the conversion are reused for later requests in that same conversion.MHT MIME structure: The result is a MIME document whose root is HTML (or XML) and whose successfully embedded resources are related parts. When resources are present, the message is normally multipart/related; when none are embedded, it can collapse to a single text/html part. MHT output omits the Date and X-Unsent headers and can preserve scripts, frames, and comments according to the script settings.

      Parameters:
      html - the html argument (not null)
      mhtFilename - the mhtFilename argument (not null)
      Throws:
      ChilkatException - if the operation fails; ChilkatException.getLastErrorText() says why
    • removeCustomHeader

      public void removeCustomHeader​(String name)
      Removes custom HTTP request headers having the field name in name. Supply the name without a trailing colon. Header names are matched case-insensitively.

      No matching field: Calling this method for a name that is not present is a harmless no-op and does not report an error.

      Use clearCustomHeaders() to remove every custom header at once.

      Parameters:
      name - the name argument (not null)
    • restoreDefaults

      public void restoreDefaults()
      Restores a limited set of MHT/EML conversion settings to their defaults and clears two method-added collections.

      Reset by this method Result

      PreferMHTScripts Restored to true.

      EmbedImages Restored to true.

      EmbedLocalOnly Restored to false.

      NoScripts and related internal script-removal state Restored to the normal script-enabled MHT behavior.

      External style sheets added by AddExternalStyleSheet The entire list is cleared.

      Exclusion patterns added by ExcludeImagesMatching The entire list is cleared.

      Not reset: This method does not clear custom headers, cache roots, BaseUrl, UseCids, UseInline, UseFilename, credentials, proxy settings, or other HTTP-related properties. Remove custom headers with removeCustomHeader(String) or clearCustomHeaders(). Cache roots can be cleared only by using a new Mht object.

    • unpackMHT

      public void unpackMHT​(String mhtFilename, String unpackDir, String htmlFilename, String partsSubDir)
      Extracts MHT data from mhtFilename. mhtFilename may be either a local MHT file path or the literal MHT MIME text; Chilkat distinguishes the two by detecting MIME headers in the supplied value. unpackDir specifies the unpack directory, htmlFilename specifies the main HTML filename, and partsSubDir specifies the related-parts subdirectory used in normal unpacking.

      Defaults and file creation: If unpackDir is empty, the unpack directory defaults to . (the process current working directory). If partsSubDir is empty, the related-parts subdirectory defaults to html_parts. Chilkat creates the parts subdirectory beneath the unpack directory when needed. The main HTML file and extracted parts overwrite existing files having the same names. An empty MHT input or an empty htmlFilename HTML filename is an error and causes the method to return false.Unpack options: Set getUnpackDirect() to preserve relative Content-Location paths without rewriting HTML; in that mode partsSubDir is ignored. getUnpackUseRelPaths() controls relative versus absolute references in normal mode.Write behavior: Extraction writes directly to the target files rather than using an atomic temporary-file replacement. A write-time I/O failure can therefore leave partially written output.Untrusted archives: Extract untrusted MHT input into an isolated directory and inspect the resulting files before opening or publishing them.Required MIME structure: Normal unpacking requires a multipart/related message containing a primary HTML body. If either is missing, the method returns false. When several HTML-like parts exist, the primary HTML part is selected and the others are treated as related resources. Path containment in normal mode: Before writing a related part, Chilkat removes .. path segments, drops leading slashes, strips Windows drive prefixes, normalizes UNC-style paths to relative paths, and keeps the result beneath the unpack directory. Degenerate names such as . and .. become _; on Windows, * and ? are replaced with _. This is targeted sanitization, not a guarantee that every platform-specific illegal name is transformed. Name collisions: Parts that would receive the same filename during one unpack operation are made unique with numeric suffixes such as name_1.ext. Existing files left by an earlier run are overwritten. Direct mode: When getUnpackDirect() is true, the method is intended for MHT data whose Content-Location values are already relative paths. A part whose location begins with http://, https://, or file:/ is logged and not written. Use normal mode for web-captured MHT data.

      Parameters:
      mhtFilename - the mhtFilename argument (not null)
      unpackDir - the unpackDir argument (not null)
      htmlFilename - the htmlFilename argument (not null)
      partsSubDir - the partsSubDir argument (not null)
      Throws:
      ChilkatException - if the operation fails; ChilkatException.getLastErrorText() says why
    • unpackMHTString

      public void unpackMHTString​(String mhtString, String unpackDir, String htmlFilename, String partsSubDir)
      Extracts MHT data from mhtString. Despite the historical method name, mhtString may be either literal MHT MIME text or a local MHT file path; Chilkat distinguishes the two by detecting MIME headers in the supplied value. unpackDir specifies the unpack directory, htmlFilename specifies the main HTML filename, and partsSubDir specifies the related-parts subdirectory used in normal unpacking.

      Defaults and file creation: If unpackDir is empty, the unpack directory defaults to . (the process current working directory). If partsSubDir is empty, the related-parts subdirectory defaults to html_parts. Chilkat creates the parts subdirectory beneath the unpack directory when needed. Existing files having the same names are overwritten. An empty MHT input or an empty htmlFilename HTML filename is an error and causes the method to return false.Direct mode: When getUnpackDirect() is true, partsSubDir is ignored and relative Content-Location paths are used directly beneath the unpack directory. Otherwise, getUnpackUseRelPaths() controls relative versus absolute references in the rewritten HTML.Write behavior: Extraction writes directly to the target files rather than using an atomic temporary-file replacement. A write-time I/O failure can therefore leave partially written output.Required MIME structure: Normal unpacking requires a multipart/related message containing a primary HTML body. If either is missing, the method returns false. When several HTML-like parts exist, the primary HTML part is selected and the others are treated as related resources. Path containment in normal mode: Before writing a related part, Chilkat removes .. path segments, drops leading slashes, strips Windows drive prefixes, normalizes UNC-style paths to relative paths, and keeps the result beneath the unpack directory. Degenerate names such as . and .. become _; on Windows, * and ? are replaced with _. This is targeted sanitization, not a guarantee that every platform-specific illegal name is transformed. Name collisions: Parts that would receive the same filename during one unpack operation are made unique with numeric suffixes such as name_1.ext. Existing files left by an earlier run are overwritten. Direct mode: When getUnpackDirect() is true, the method is intended for MHT data whose Content-Location values are already relative paths. A part whose location begins with http://, https://, or file:/ is logged and not written. Use normal mode for web-captured MHT data.

      Parameters:
      mhtString - the mhtString argument (not null)
      unpackDir - the unpackDir argument (not null)
      htmlFilename - the htmlFilename argument (not null)
      partsSubDir - the partsSubDir argument (not null)
      Throws:
      ChilkatException - if the operation fails; ChilkatException.getLastErrorText() says why
    • setProgressListener

      public void setProgressListener​(ProgressListener listener)
      Installs the listener that receives this object's progress events (abortCheck, percentDone, progressInfo) during its long-running methods; replaces any listener or lambda installed before; null removes it.
      Parameters:
      listener - the listener, or null
      Throws:
      IllegalStateException - if called from inside one of this object's own callbacks
    • getProgressListener

      public ProgressListener getProgressListener()
      Returns the installed listener, or null.
      Returns:
      the listener installed with setProgressListener(ProgressListener) or one of the on... methods
    • onAbortCheck

      public void onAbortCheck​(BooleanSupplier callback)
      Installs a listener whose only callback is abortCheck: called every HeartbeatMs milliseconds during a long-running method; return true to abort it. Replaces any listener installed before.
      Parameters:
      callback - the callback, or null to remove the listener
    • onPercentDone

      public void onPercentDone​(IntPredicate callback)
      Installs a listener whose only callback is percentDone: called with the completion percentage (0..100) as a long-running method progresses; return true to abort it. Replaces any listener installed before.
      Parameters:
      callback - the callback, or null to remove the listener
    • onProgressInfo

      public void onProgressInfo​(BiConsumer<String,​String> callback)
      Installs a listener whose only callback is progressInfo: called with a name/value pair of progress information as a long-running method proceeds. Replaces any listener installed before.
      Parameters:
      callback - the callback, or null to remove the listener