Send an HTML formatted message with a picture attachment in Java Mail

Source: Internet
Author: User
Tags contains integer mail tostring
Use Java mail to send a message with a picture in HTML format, there are generally two ways to display a picture.

1. The picture exists on the server, we only need to put the picture in the server's link.
This hairstyle is simpler, but there are some drawbacks to this approach:
Images do not support offline browsing;
Each time browsing the mail needs to visit the Web service, increases the server burden;
If the image is in binary form in the database or dynamically generated, it can not be effectively resolved.

2. Send pictures as attachments, which is very useful in situations where pictures exist in the database.
This article also mainly discusses this situation.

For a basic knowledge of Java mail, see http://www.yesky.com/SoftChannel/72348977504190464/20020713/1620276.shtml,
This article is not introduced.

When it comes to the attachment in the mail, I have to say the Minimultipart class, which provides an additional implementation method to add to the message.
A content-type is a message object that is set to Minimultipart for a content type.
The Minimultipart class is a container class that contains objects of type MimeBodyPart.
We can use a MimeBodyPart to contain the HTML source code, and the other mimebodypart contain binary picture attachments.

But here's an unexpected situation, let's look at the MimeBodyPart initialization code:

MimeBodyPart MDP = new MimeBodyPart (); Create a new bodypart to store attachments
DataHandler dh = new DataHandler (...);
Mdp.setdatahandler (DH); Set the content to DH for the BodyPart object
Where a 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 would provide a inputstream to access the data.
Parameters:ds-the DataSource

In JDK1.4, DataSource is a interface,datasource with only Mimepartdatasource, Urldatasource, Filedatasource three subclasses,
None of these three classes can create an instance directly from the binary stream (byte[). Of course, we can write the binary stream in memory to the file, and then let Filedatasource read in.
But this will bring the server to the external hard drive read and write, if the operation is frequent, will cause the server performance drop. Luckily, I found a class on the Internet that can directly create an instance directly with 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 a input stream * *
Public Bytearraydatasource (InputStream is,string type)
{
_type = type;
Try
{
Bytearrayoutputstream OS = new Bytearrayoutputstream ();
int ch;

Xxx:must be made more efficient by
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 ' string contains only ASCII
Characters! Else just pass in a charset to 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 above Bytearraydatasource class, we can send the picture attachment to the mail.
{
String SMTPHost = ...;
String to = ...;
String from = ...;
String name = ...;
String password = ...;
String subject = ...;
StringBuffer content = ...; HTML source code for a message
LinkedList attachlist = ...; The list of attachments, whose element is byte[], is the binary stream of the picture

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 (to)};

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 hold the BodyPart object (in fact, you can store multiple)
Mimemultipart mm = new Mimemultipart ();
Creates a new BodyPart object that holds the contents of a letter
BodyPart MDP = new MimeBodyPart ();
Set content and formatting/encoding for BodyPart objects
Mdp.setcontent (Content.tostring (), "TEXT/HTML;CHARSET=GBK");
It's important, don't forget it.
Mm.setsubtype ("related");

Mm.addbodypart (MDP);

Add the Attachments
for (int i=0; i<attachlist.size (); i++)
{
Create a new bodypart to store 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 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 content of the Message object
Message.setcontent (mm);

Message.savechanges ();
Javax.mail.Transport transport = Session.gettransport ("SMTP");
Transport.connect (smtphost, name, password);
Transport.sendmessage (Message, message.getallrecipients ());
Transport.close ();
}

This code should be noted in the above code:
Mdp.setheader ("Content-id", "IMG" + new Integer (i). toString ());
It describes the relative path of the attachment picture,
When I=1, the code is Mdp.setheader ("Content-id", "IMG1");

In our HTML source code, which is the content above, you need to include
&LT;TD align= ' center ' valign= ' Middle ' >
<div align= "center" >
<a href= "http://www.test.com" target= "_blank" >

</a>
</div>
</td>
You can display the picture in the message.




Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.