Reply to comment
Example how to construct a MHT (AKA MHTML) file in Java using JavaMail API
Vložil/a petr, So, 08/03/2008 - 16:23[blockcode language="java5"]
import javax.mail.*;
import javax.mail.internet.*;
import javax.activation.*;
import java.io.*;
import java.util.*;
/**
* Example how to construct a MHT (AKA MHTML) file in Java using JavaMail API. Creates a
* simple HTML page (from a
String) with an image, which
* is pulled from a file.
*
* Requires mail.jar in the classpath (and also Java
* Activation Framework if JDK version is less than 1.6).
*/
public class MHTMLExample
{
public static void main(String argv[])
throws Exception
{
// get system properties
Properties props = new Properties(); // System.getProperties();
// create a new session
Session session = Session.getInstance(props, null);
// construct a MIME message message
MimeMessage message = new MimeMessage(session);
MimeMultipart mpart = new MimeMultipart("related");
String htmlPage = "ExampleExampleSome text...";
mpart.addBodyPart(bodyPart(new StringSource("text/html",
"index.html", htmlPage)));
mpart.addBodyPart(bodyPart(new FileDataSource("pooh.jpg")));
message.setContent(mpart);
// the subject is displayed as the window title in the browser
message.setSubject("MHTML example");
// one can set the URL of the original page:
// message.addHeader("Content-Location", "index.html");
message.writeTo(System.out);
}
static BodyPart bodyPart(DataSource ds)
throws MessagingException
{
MimeBodyPart body = new MimeBodyPart();
DataHandler dh = new DataHandler(ds);
body.setDisposition("inline");
body.setDataHandler(dh);
body.setFileName(dh.getName());
// the URL of the file; we set it simply to its name
body.addHeader("Content-Location", dh.getName());
return body;
}
static final class StringSource
implements DataSource
{
private final String contentType;
private final String name;
private final byte[] data;
public StringSource(String contentType, String name, String data)
{
this.contentType = contentType;
this.data = data.getBytes();
this.name = name;
}
public String getContentType()
{ return contentType; }
public OutputStream getOutputStream()
throws IOException
{ throw new IOException(); }
public InputStream getInputStream()
throws IOException
{
return new ByteArrayInputStream(data);
}
public String getName()
{ return name; }
}
}
[/blockcode]| Attachment | Size |
|---|---|
| MHTMLExample.java | 2.44 KB |
