Using javax.mail

From PeformIQ Upgrade
Revision as of 11:22, 4 December 2008 by PeterHarding (talk | contribs) (New page: <pre> import java.util.*; import javax.mail.*; import javax.mail.internet.*; import javax.activation.*; public class MailWithAttachment { public static void main(String[] args) { ...)
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
Jump to navigation Jump to search

import java.util.*;
import javax.mail.*;
import javax.mail.internet.*;
import javax.activation.*;

public class MailWithAttachment
{
   public static void main(String[] args)
   {
      try {
         java.util.Properties mailprop = new java.util.Properties();

         String host =  "smtp";
         String fromAddress = "test@enpysoft.com";
         String toAddress = "muthuselvan@adventnet.com";
         String filename = "C://docs//invitation.tiff";
         String subj = "Invitation";
         String content = "XXX,\n\txxxxxx\n\nRegards,\n";

         mailprop.put("mail.smtp.host",host);

         Session session = Session.getInstance(mailprop,null);

         MimeMessage message = new MimeMessage(session);

         message.setFrom(new InternetAddress(fromAddress));
         message.addRecipient(Message.RecipientType.TO,new InternetAddress(toAddress));
         message.setSubject(subj);

         MimeBodyPart mbp1 = new MimeBodyPart();

         mbp1.setText(content);

         MimeBodyPart mbp2 = new MimeBodyPart();

         FileDataSource fds = new FileDataSource(filename);

         mbp2.setDataHandler(new DataHandler(fds));
         mbp2.setFileName(fds.getName());

         Multipart mp = new MimeMultipart();

         mp.addBodyPart(mbp1);
         mp.addBodyPart(mbp2);

         message.setContent(mp);
         message.setSentDate(new java.util.Date());

         Transport.send(message);
      } catch(Exception e) {
         e.printStackTrace();
      }
   }
}  // class MailWithAttachment