Java mail sends an HTML-format email with images. There are two methods for displaying images.
1. images exist on the server. We only need to put the image link on the server.
This method is relatively simple, but it has some drawbacks:
Images cannot be viewed offline;
The Web service needs to be accessed for each email browsing, increasing the burden on the server;
If an image exists in a database in binary mode or is dynamically generated, it cannot be effectively solved.
2. Send the image as an attachment. This method is very suitable for the situation where the image exists in the database.
This article also focuses on this situation.
For the basic knowledge of Java mail, see http://www.yesky.com/SoftChannel/72348977504190464/20020713/1620276.shtml,
This document does not describe.
When talking about attachments in emails, I have to talk about the minimultipart class and provide the implementation method to add attachments to emails.
A multi-part message is a message object set as minimultipart.
The minimultipart class is a container class that contains objects of the mimebodypart type.
We can use a mimebodypart to include HTMLSource codeAnd other mimebodyparts contain binary image attachments.
But here is an unexpected situation. Let's first look at mimebodypart initialization.Code:
Mimebodypart MDP = new mimebodypart (); // creates a bodypart for storing attachments.
Datahandler DH = new datahandler (...);
MDP. setdatahandler (DH); // set the bodypart object content to DH
The subclass of datasource is required when datahandler is initialized.
/** From JDK Doc */
Public datahandler (datasource DS)
Create a datahandler instance referencing the specified datasource.
The data exists in a byte stream form. The datasource will provide an inputstream to access the data.
Parameters: ds-The datasource
In jdk1.4, datasource is an interface, and datasource only has three sub-classes: mimepartdatasource, urldatasource, and filedatasource,
None of the three classes can directly use the binary stream (byte []) to create an instance. Of course, we can write the binary stream in the memory to the file and then let filedatasource read in.
However, this will bring external hard disk reads and writes to the server. If the operation is frequent, the server performance will decrease. Fortunately, I found such a class on the Internet and can directly create an instance using a binary stream.
Import java. Io .*;
Import javax. Activation .*;
Public class bytearraydatasource implements datasource
{
/*** Data to write .*/
Private byte [] _ data;
/*** Content-Type .*/
Private string _ type;
/* Create a datasource from an input stream */
Public bytearraydatasource (inputstream is, string type)
{
_ Type = type;
Try
{
Bytearrayoutputstream OS = new bytearrayoutputstream ();
Int ch;
// XXX: must be made more efficient
// Doing buffered reads, rather than one byte reads
While (CH = is. Read ())! =-1)
OS. Write (CH );
_ DATA = OS. tobytearray ();
}
Catch (ioexception IOE)
{
}
}
/* Create a datasource from a byte array */
Public bytearraydatasource (byte [] data, string type)
{
_ DATA = data;
_ Type = type;
}
/* Create a datasource from a string */
Public bytearraydatasource (string data, string type)
{
Try
{
// Assumption that the string contains only ASCII
// Characters! Else just pass in a charset into this
// Constructor and use it in getbytes ()
_ DATA = data. getbytes ("iso-8859-1 ");
}
Catch (unsupportedencodingexception UEE)
{
}
_ Type = type;
}
Public inputstream getinputstream ()
Throws ioexception
{
If (_ DATA = NULL)
Throw new ioexception ("no data ");
Return new bytearrayinputstream (_ data );
}
Public outputstream getoutputstream ()
Throws ioexception
{
Throw new ioexception ("cannot do this ");
}
Public String getcontenttype ()
{
Return _ type;
}
Public String getname ()
{
Return "Dummy ";
}
}
With the bytearraydatasource class above, we can send the email of the image attachment.
{
String smtphost = ...;
String to = ...;
String from = ...;
String name = ...;
String Password = ...;
String subject = ...;
Stringbuffer content =...; // The HTML source code of the email
Optional list attachlist =...; // list of attachments. Its elements are byte [], that is, the binary stream of the image.
Properties props = new properties ();
Props. Put ("mail. SMTP. Host", smtphost );
Props. Put ("mail. SMTP. Auth", "true ");
Session session = session. getdefaultinstance (props, null );
Mimemessage message;
Internetaddress [] address = {New internetaddress ()};
Message = new mimemessage (session );
Message. setfrom (New internetaddress (from ));
Message. setrecipients (message. recipienttype. To, address );
Message. setsubject (subject );
Message. setsentdate (new date ());
// Create a new mimemultipart object to store the bodypart object (in fact, multiple objects can be stored)
Mimemultipart Mm = new mimemultipart ();
// Create a bodypart object for storing the mail content
Bodypart MDP = new mimebodypart ();
// Set the content and format/encoding method for the bodypart object
MDP. setcontent (content. tostring (), "text/html; charset = GBK ");
// This sentence is very important. Never forget it.
Mm. setsubtype ("related ");
Mm. addbodypart (MDP );
// Add the attachments
For (INT I = 0; I <attachlist. Size (); I ++)
{
// Create a bodypart for storing attachments
MDP = new mimebodypart ();
Datahandler DH = new datahandler (New bytearraydatasource (byte []) attachlist. Get (I), "application/octet-stream "));
MDP. setdatahandler (DH );
// This sentence will be sent as an attachment; otherwise, it will be used as the text content of the letter.
MDP. setfilename (New INTEGER (I). tostring () + ". jpg ");
MDP. setheader ("content-ID", "IMG" + new INTEGER (I). tostring ());
// Add the bodypart containing the attachment to the mimemultipart object.
Mm. addbodypart (MDP );
}
// Use mm as the message object content
Message. setcontent (mm );
Message. savechanges ();
Javax. Mail. Transport transport = session. gettransport ("SMTP ");
Transport. Connect (smtphost, name, password );
Transport. sendmessage (message, message. getallrecipients ());
Transport. Close ();
}
Note the following code in the above Code:
MDP. setheader ("content-ID", "IMG" + new INTEGER (I). tostring ());
It describes the relative path of the attachment image,
When I = 1, the code is MDP. setheader ("content-ID", "img1 ");
in our HTML source code, that is, in the above content,
the image is displayed in the email.