Skip to Main Content
Java Enterprise Best Practices
book

Java Enterprise Best Practices

by O'Reilly Java Authors
December 2002
Intermediate to advanced content levelIntermediate to advanced
288 pages
9h 46m
English
O'Reilly Media, Inc.
Content preview from Java Enterprise Best Practices

Sending Email

JavaMail’s mechanism for creating new outgoing email messages is quite simple: instantiate a MimeMessage object, add content, and send via a transport. Adding file attachments is only a little more complex: simply create a message part for each component (body text, file attachments, etc.), add them to a multipart container, and add the container to the message. Example 10-1 should act as a quick refresher.

Example 10-1. Multipart mail send
import javax.mail.*; import javax.mail.internet.*; import javax.activation.*; import java.io.File; import java.util.Properties; . . . public class MimeAttach { . . . public static void main(String[ ] args) { try { Properties props = System.getProperties( ); props.put("mail.smtp.host", "mail.company.com"); Session session = Session.getDefaultInstance(props, null); . . . Message msg = new MimeMessage(session); msg.setFrom(new InternetAddress("logs@company.com")); msg.setRecipient(Message.RecipientType.TO, new InternetAddress("root@company.com")); msg.setSubject("Today's Logs"); . . . Multipart mp = new MimeMultipart( ); MimeBodyPart mbp1 = new MimeBodyPart( ); mbp1.setContent("Log file for today is attached.", "text/plain"); . . . mp.addBodyPart(mbp1); . . . File f = new File("/var/logs/today.log"); MimeBodyPart mbp = new MimeBodyPart( ); mbp.setFileName(f.getName( )); mbp.setDataHandler(new DataHandler(new FileDataSource(f))); mp.addBodyPart(mbp); . . . msg.setContent(mp); Transport.send(msg); } catch (MessagingException me) { ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

Moving to Java 9: Better Design and Simpler Code

Moving to Java 9: Better Design and Simpler Code

Trisha Gee
Java EE 8 High Performance

Java EE 8 High Performance

Romain Manni-Bucau

Publisher Resources

ISBN: 0596003846Supplemental ContentErrata Page