1 package org.apache.axis2.transport.mail; 2 import javax.mail.*; 3 import javax.mail.internet.MimeMessage ; 4 import java.io.IOException ; 5 import java.util.Properties ; 6 7 public class MailClient 8 extends Authenticator 9 { 10 public static final int SHOW_MESSAGES = 1; 11 public static final int CLEAR_MESSAGES = 2; 12 public static final int SHOW_AND_CLEAR = 13 SHOW_MESSAGES + CLEAR_MESSAGES; 14 15 protected String from; 16 protected Session session; 17 protected PasswordAuthentication authentication; 18 19 public MailClient(String user, String host) 20 { 21 this(user, host, user, false); 22 } 23 24 public MailClient(String user, String host, String password) 25 { 26 this(user, host, password , false); 27 } 28 29 public MailClient(String user, String host, String password, boolean debug) 30 { 31 from = user + '@' + host; 32 authentication = new PasswordAuthentication(user, password); 33 Properties props = new Properties (); 34 props.put("mail.user", user); 35 props.put("mail.host", host); 36 props.put("mail.debug", debug ? "true" : "false"); 37 props.put("mail.store.protocol", "pop3"); 38 props.put("mail.transport.protocol", "smtp"); 39 session = Session.getInstance(props, this); 40 } 41 42 public PasswordAuthentication getPasswordAuthentication() 43 { 44 return authentication; 45 } 46 47 public void sendMessage( 48 String to, String subject, String content, String soapAction) 49 throws MessagingException 50 { 51 System.out.println("SENDING message from " + from + " to " + to); 52 System.out.println(); 53 MimeMessage msg = new MimeMessage (session); 54 msg.setHeader("transport.mail.soapaction",soapAction); 55 msg.addRecipients(Message.RecipientType.TO, to); 56 msg.setSubject(subject); 57 msg.setText(content); 58 Transport.send(msg); 59 } 60 61 public int checkInbox(int mode) 62 throws MessagingException, IOException 63 { 64 int numMessages = 0; 65 if (mode == 0) return 0; 66 boolean show = (mode & SHOW_MESSAGES) > 0; 67 boolean clear = (mode & CLEAR_MESSAGES) > 0; 68 String action = 69 (show ? "Show" : "") + 70 (show && clear ? " and " : "") + 71 (clear ? "Clear" : ""); 72 System.out.println(action + " INBOX for " + from); 73 Store store = session.getStore(); 74 store.connect(); 75 Folder root = store.getDefaultFolder(); 76 Folder inbox = root.getFolder("inbox"); 77 inbox.open(Folder.READ_WRITE); 78 Message [] msgs = inbox.getMessages(); 79 numMessages = msgs.length; 80 if (msgs.length == 0 && show) 81 { 82 System.out.println("No messages in inbox"); 83 } 84 for (int i = 0; i < msgs.length; i++) 85 { 86 MimeMessage msg = (MimeMessage )msgs[i]; 87 if (show) 88 { 89 System.out.println(" From: " + msg.getFrom()[0]); 90 System.out.println(" Subject: " + msg.getSubject()); 91 System.out.println(" Content: " + msg.getContent()); 92 } 93 if (clear) 94 { 95 msg.setFlag(Flags.Flag.DELETED, true); 96 } 97 } 98 inbox.close(true); 99 store.close(); 100 System.out.println(); 101 return numMessages; 102 } 103 } 104 | Popular Tags |