📄 using the javamail api to send html email .txt
字号:
Using the JavaMail API to Send HTML Email
USING THE JAVAMAIL API TO SEND HTML EMAIL
In the old days of the Internet, when it was called Arpanet, you could send and receive any kind of email you liked -- as long as it was plain text. Today people have enormously more computing power at their disposal than in the days of Arpanet, yet for the most part, the primary type of email is still text.
Text email is excellent for interpersonal communication, but many organizations can benefit from being able to email other types of content. For example, a magazine publisher might want to email the electronic content of a magazine in HTML. However there are problems sending email content in HTML. Some Web-based email systems show email in text-only mode, and for the large number of recipients who still read email using text-only clients, receiving HTML email can be annoying.
The first tip in this Tech Tips issue explains how to use the JavaMail API to send email that can be displayed as text or as HTML, depending on the recipient's email client. The tip does not discuss the many, valuable, and important arguments for and against HTML email. Instead, it assumes you've decided to use HTML email, and want also to support text email readers.
MIME and the Multipart Content Type
The old Arpanet email standard, RFC 822, was designed specifically for text messages. That's because in those days, text email was the only type of email available. By the early 1990's, the state of the art had advanced to the point where RFC 822's limitations were becoming apparent. There was a growing need to support non-textual and multi-part email. To provide this and other types of support, Internet engineers created MIME RFC 1341, the Multipurpose Internet Mail Extensions mechanism. Among other things it covers, MIME defines how to structure an email message body to deliver more than one item in a single message. Interestingly, much of how Web technology handles media types is based on MIME, even though MIME was originally designed for email. The original RFC 1341 MIME specification has itself been supplanted by RFCs 2045-2049.
MIME distinguishes emails that contain more than one item by indicating the email's Content-type as multipart. This tells the email client that the message body contains multiple parts, and describes how to split those parts. Each part also has its own Content-type.
The Multipart Alternative Content Type
Multipart emails let you send both an HTML version and a text version in the same email. In other words, multipart supports both HTML and text (and even audio) email users. But who wants to have to deal with several versions of email? Fortunately, the authors of MIME foresaw this problem, so they created the MIME Content-type multipart/alternative.
A multipart/alternative content type tells the user's email client that the parts of the message are alternative versions of the same thing. This lets the email client decide which version to display, based on its capabilities or on user preferences.
Is it expensive and slow to send multiple versions of everything, when only one is ever seen? The answer to that question depends on several factors that are specific to your particular environment. It's certainly important to keep in mind factors such as system load, message size, and user connection speed when designing an email communication system. But remember, this tip assumes that you already considered those things, and have decided to use HTML email.
You have at least two choices if you want to use MIME to send emails. First, you can read RFC 1341, and implement the protocols yourself. Or, you can use the JavaMail APIs, and allow the Java platform to do all of that work for you.
Using JavaMail to Send Multipart Emails
The sample application for this tip sends a multipart/alternative email message to a specified email address. The application transmits email using configuration information that is defined in a java.util.Properties file. The JavaMail interface is so feature-rich, that putting every option directly in the interfaces would result in a huge API. Also, setting up emails by calling a lot of set methods results in a great deal of tedious coding. The resulting program would have to be recompiled every time you wanted to change something. So the JavaMail designers let you configure JavaMail using a Properties object, which can be read from a file (as is done here), or created in any other way.
The section "Running the Sample Code" for instructions on how to get and unpack the JAR for the sample (ttapr2004.jar). The information that follows concentrates on explaining the code.
First, let's examine the contents of the Properties file (apr2004.props), which structures the input to the program. The comments are self-explanatory.
# The hostname or IP address of your SMTP server
mail.smtp.host=smtp.duke.java.sun.com
# You get lots of debugging information if
# this is turned on. Comment this line to turn
# it off.
mail.debug=true
# The To email address
ttapr2004.to=duke@duke.java.sun.com
# The From email address
ttapr2004.from=duke@j2ee_fanclub.java.sun.com
# The subject of the email
ttapr2004.subject=Declaration of Independence
# The name of the TEXT file to send
# This file is included in the distribution
ttapr2004.txtfile=declaration.txt
# The name of the HTML file to send
# This file is included in the distribution
ttapr2004.htmlfile=declaration.html
Change the hostname and IP address of the SMTP server in the Properties file as appropriate for your environment. Also change the debug and to lines as needed.
To run the program, be sure that the sample code JAR file is in the CLASSPATH, as well as the libraries mail.jar (JavaMail) and activation.jar (the Java Activation Framework). You can download these JAR files from http://java.sun.com/products/javamail/ and http://java.sun.com/products/javabeans/glasgow/jaf.html, respectively. Then, execute the class TwoKindsOfEmail, with the props file as its argument:
$ # Set classpath...
$ java TwoKindsOfEmail apr2004.props
The program creates an email containing both files, and sends it to the "to" address. Check that email with one reader that supports HTML, and you'll see a formatted message. Check with a text-only email client, and you'll see text.
Here, for example, is the message presented by an email client that supports HTML (only part of the message is shown).
Here is how the sample code works. In class TwoKindsOfEmail, method sendmail() does virtually all of the work. The first part of the code loads the properties file, and creates and initializes a new MimeMessage:
Properties props = new Properties();
props.load(new FileInputStream(propfile));
Session session = Session.getInstance(props, null);
MimeMessage msg = new MimeMessage(session);
InternetAddress from =
new InternetAddress((String)props.get
("ttapr2004.from"));
InternetAddress to =
new InternetAddress((String)props.get
("ttapr2004.to"));
msg.setFrom(from);
msg.addRecipient(Message.RecipientType.TO, to);
msg.setSubject((String)props.get
("ttapr2004.subject"));
The next line creates a multipart message. Note that the multipart message is explicitly marked as "alternative". Without this string, you would see both the HTML and text emails in your email browser:
// Create an "Alternative" Multipart message
Multipart mp = new MimeMultipart("alternative");
The next section of code loads the text file into memory. It creates a java.mail.BodyPart object with the text file content, and a Content-type of "text/plain". (It uses method getFileBodyPart(), which simply reads a file's contents, constructs a BodyPart object, and sets its content and content-type.)
// Read text file, load it into a BodyPart, and add it to the
// message.
String textfile = (String)props.get
("ttapr2004.txtfile");
BodyPart bp1 = getFileBodyPart
(textfile, "text/plain");
mp.addBodyPart(bp1);
The following code does the same thing for the HTML body part:
// Do the same with the HTML part
String htmlfile = (String)props.get
("ttapr2004.htmlfile");
BodyPart bp2 = getFileBodyPart
(htmlfile, "text/html");
mp.addBodyPart(bp2);
Finally, the method sets the message content to the multipart object, and tells the Transport object to send it:
// Set the content for the message and transmit
msg.setContent(mp);
Transport.send(msg);
Note that the text part is set first. The MIME definition for multipart/alternative recommends ordering the alternatives from the least sophisticated to the most sophisticated. This convention allows each type of client to look through the list of alternative message types, and to display the most sophisticated one it understands. Many text email readers simply show the first part of a multipart/alternative message and hope for the best. Putting simpler content first makes it more likely that the email recipient gets something appropriate.
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -