December 2002
Intermediate to advanced
288 pages
9h 46m
English
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.
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) { ...