Sending HTML and ASCII Formatted E-mails

To do this, you need the javax.mail package. It’s a part of J2EE and available from java.sun.com.

Sending a simple e-mail is pretty easy:

 import java.util.Properties;import javax.mail.*;import javax.mail.internet.*;public class Mail {static public void main(String[] args) {String to = "[email protected]";String subj = "Testing Email";String body = "This is a test of thegood times broadcasting system";Properties props = new Properties();// supply the location of aprops.put("mail.smtp.host", "10.10.10.119");try {Session session = Session.getDefaultInstance(props, null);Message msg = new MimeMessage(session);session.setDebug(true);msg.setFrom(new InternetAddress("[email protected]"));msg.addRecipient( Message.RecipientType.TO, new InternetAddress(to));msg.setSubject(subj);msg.setType("plain/text");msg.setContent(mp);Transport.send(msg);} catch(Throwable t) {t.printStackTrace();}}}

To send multiple formats in a single e-mail, use Parts. An e-mail has a Content; that Content can be a simple String or it can be a Multipart. A Multipart is made up of many BodyParts. A BodyPart may contain a String or a Multipart.

This example sends e-mails that contain Multipart, with two BodyParts–plaintext and HTML.

Note that there are different types of Multipart. The two most common are multipart/mixed and multipart/alternative. One shows both on the same page, while the other selects the best format for the user. Here’s the example code:

 import java.util.Properties;import javax.mail.*;import javax.mail.internet.*;public class Mail {static public void main(String[] args) {String to = "[email protected]";String subj = "Testing";String body ="This is a test of the good times broadcasting system";String htmlbody ="

This is a test of the good times broadcasting system

";Properties props = new Properties();// supply the location of aprops.put("mail.smtp.host", "10.10.10.119");try {Session session = Session.getDefaultInstance(props, null);Message msg = new MimeMessage(session);session.setDebug(true);msg.setFrom(new InternetAddress("[email protected]"));msg.addRecipient( Message.RecipientType.TO, new InternetAddress(to));msg.setSubject(subj);MimeMultipart mp = new MimeMultipart();BodyPart tp = new MimeBodyPart();tp.setText(body);mp.addBodyPart(tp);tp = new MimeBodyPart();tp.setContent(htmlbody, "text/html");mp.addBodyPart(tp);mp.setSubType("alternative");msg.setContent(mp);Transport.send(msg);} catch(Throwable t) {t.printStackTrace();}}}
Share the Post:
Share on facebook
Share on twitter
Share on linkedin

Overview

Recent Articles: