Ignore:
Timestamp:
08/21/08 11:20:24 (16 years ago)
Author:
ra33
Message:
 
File:
1 edited

Legend:

Unmodified
Added
Removed
  • trunk/src/org/expeditee/agents/mail/MailSession.java

    r238 r242  
    11package org.expeditee.agents.mail;
    22
     3import java.io.BufferedReader;
     4import java.io.InputStream;
     5import java.io.InputStreamReader;
    36import java.util.Date;
    47import java.util.Properties;
    58
    69import javax.mail.Authenticator;
     10import javax.mail.Folder;
    711import javax.mail.Message;
     12import javax.mail.MessagingException;
     13import javax.mail.Multipart;
     14import javax.mail.Part;
    815import javax.mail.PasswordAuthentication;
    916import javax.mail.Session;
     17import javax.mail.Store;
    1018import javax.mail.Transport;
     19import javax.mail.Flags.Flag;
    1120import javax.mail.internet.InternetAddress;
    1221import javax.mail.internet.MimeMessage;
     
    1827
    1928public class MailSession {
     29        public static boolean _autoConnect = true;
     30
    2031        private static MailSession _theMailSession = null;
    2132
     
    2435        private Transport _transport;
    2536
     37        private Store _store;
     38
     39        private Folder _folder;
     40
    2641        private String _address;
    2742
     43        private String _username;
     44
     45        private String _password;
     46
     47        private String _popServer;
     48
     49        private Boolean _bConnecting;
     50
    2851        private MailSession(Frame settingsFrame) {
     52                _bConnecting = false;
     53
    2954                Properties props = System.getProperties();
    3055
    31                 String username = null;
    32                 String password = "";
     56                _username = null;
     57                _password = "";
     58                _popServer = null;
    3359
    3460                // Set the settings
     
    4167
    4268                        if (attribute.equals("user")) {
    43                                 username = avp.getValue();
    44                                 props.setProperty("mail.user", username);
     69                                _username = avp.getValue();
     70                                props.setProperty("mail.user", _username);
    4571                        } else if (attribute.equals("password")) {
    46                                 password = avp.getValue();
    47                                 props.setProperty("mail.password", password);
     72                                _password = avp.getValue();
     73                                props.setProperty("mail.password", _password);
    4874                        } else if (attribute.equals("address")) {
    4975                                _address = avp.getValue();
     
    5480                                props.setProperty("mail.smtp.host", avp.getValue());
    5581                                props.setProperty("mail.smtp.auth", "true");
     82                        } else if (attribute.equals("popserver")) {
     83                                _popServer = avp.getValue();
    5684                        }
    5785                }
     
    5987                // Create the authenticator
    6088                Authenticator auth = null;
    61                 if (username != null) {
    62                         auth = new SMTPAuthenticator(username, password);
     89                if (_username != null) {
     90                        auth = new SMTPAuthenticator(_username, _password);
    6391                }
    6492                java.security.Security
     
    6896                _session = Session.getDefaultInstance(props, auth);
    6997                try {
    70                         // -- Send the message --
     98                        // Set up the mail receiver
     99                        _store = _session.getStore("pop3s");
     100
     101                        // Connect the mail sender
    71102                        _transport = _session.getTransport();
    72                         _transport.connect();
     103                        if (_autoConnect) {
     104                                connectThreaded();
     105                        }
    73106                } catch (Exception e) {
    74107                        MessageBay.errorMessage("Error in ExpMail setup");
     
    76109        }
    77110
    78         public static boolean sendTextMessage(String to, String cc, String subject,
    79                         String body) {
     111        /**
     112         * Attempts to connect the mail transporter to the mail server.
     113         *
     114         */
     115        public static void connect() {
     116                if (_theMailSession._bConnecting) {
     117                        MessageBay.errorMessage("Already connecting to mail server");
     118                        return;
     119                } else if (_theMailSession != null) {
     120                        _theMailSession.connectThreaded();
     121                }
     122        }
     123
     124        private void connectThreaded() {
     125                Thread t = new ConnectThread(this);
     126                t.start();
     127        }
     128
     129        public synchronized void connectServers() {
     130                try {
     131                        if (!_transport.isConnected()) {
     132                                MessageBay.displayMessage("Connecting to SMTP server...");
     133                                _bConnecting = true;
     134                                _transport.connect();
     135                                MessageBay.overwriteMessage("SMTP server connected");
     136                        } else {
     137                                MessageBay.warningMessage("SMTP server already connected");
     138                        }
     139                } catch (MessagingException e) {
     140                        MessageBay.errorMessage("Error connecting to SMTP server");
     141                }
     142
     143                if (_popServer != null && !_store.isConnected()) {
     144                        try {
     145                                MessageBay.displayMessage("Connecting to POP3 server...");
     146                                _store.connect(_popServer, _username, _password);
     147
     148                                // -- Try to get hold of the default folder --
     149                                _folder = _store.getDefaultFolder();
     150                                if (_folder == null)
     151                                        throw new Exception("No default folder");
     152                                // -- ...and its INBOX --
     153                                _folder = _folder.getFolder("INBOX");
     154                                if (_folder == null)
     155                                        throw new Exception("No POP3 INBOX");
     156                                // -- Open the folder for read only --
     157                                _folder.open(Folder.READ_ONLY);
     158                                MessageBay.overwriteMessage("POP3 server connected");
     159                                MessageBay.warningMessage(getUnreadMessageCount() + " unread messages are in your inbox");
     160                        } catch (Exception e) {
     161                                // e.printStackTrace();
     162                                MessageBay.errorMessage("Error connecting to POP3 server");
     163                        }
     164                }
     165                _bConnecting = false;
     166        }
     167
     168        public static boolean sendTextMessage(String to, String cc, String bcc,
     169                        String subject, String body) {
     170
    80171                if (_theMailSession == null) {
    81172                        MessageBay.errorMessage("Add mail settings to profile frame");
    82173                        return false;
    83                 } else if (to == null) {
     174                }
     175
     176                if (_theMailSession._bConnecting) {
     177                        MessageBay.errorMessage("Busy connecting to mail server...");
     178                        return false;
     179                }
     180
     181                return _theMailSession.sendText(to, cc, bcc, subject, body);
     182        }
     183
     184        private synchronized boolean sendText(String to, String cc, String bcc,
     185                        String subject, String body) {
     186                if (!_transport.isConnected()) {
     187                        MessageBay
     188                                        .warningMessage("Not connected to server, attempting to reconnect...");
     189                        try {
     190                                _bConnecting = true;
     191                                _transport.connect();
     192                                _bConnecting = false;
     193                        } catch (Exception e) {
     194                                MessageBay.errorMessage("Could not connect to mail server");
     195                                _bConnecting = false;
     196                                return false;
     197                        }
     198                }
     199
     200                if (to == null) {
    84201                        MessageBay.errorMessage("Add tag @to:<sendToEmailAddress>");
    85202                        return false;
     
    88205                try {
    89206                        // -- Create a new message --
    90                         Message msg = new MimeMessage(_theMailSession._session);
     207                        Message msg = new MimeMessage(_session);
    91208
    92209                        // -- Set the FROM and TO fields --
    93                         msg.setFrom(new InternetAddress(_theMailSession._address));
     210                        msg.setFrom(new InternetAddress(_address));
    94211                        msg.setRecipients(Message.RecipientType.TO, InternetAddress.parse(
    95212                                        to, false));
     
    101218                        }
    102219
     220                        if (bcc != null) {
     221                                msg.setRecipients(Message.RecipientType.BCC, InternetAddress
     222                                                .parse(bcc, false));
     223                        }
     224
    103225                        // -- Set the subject and body text --
    104226                        msg.setSubject(subject);
     
    143265        }
    144266
    145         public static void finalise() {
    146                 try {
    147                         if (_theMailSession._transport != null)
    148                                 _theMailSession._transport.close();
     267        public static MailSession getInstance() {
     268                return _theMailSession;
     269        }
     270
     271        public synchronized void finalise() {
     272                try {
     273                        if (_transport != null && _transport.isConnected()) {
     274                                _transport.close();
     275                        }
     276
     277                        if (_folder != null) {
     278                                _folder.close(false);
     279                        }
     280
     281                        if (_store != null) {
     282                                _store.close();
     283                        }
    149284                } catch (Exception e) {
    150285
    151286                }
    152287        }
     288
     289        public int getUnreadMessageCount() {
     290                // -- Get the message wrappers and process them --
     291                Message[] msgs;
     292                int count = 0;
     293                try {
     294                        msgs = _folder.getMessages();
     295                        for (int msgNum = 0; msgNum < msgs.length; msgNum++) {
     296                                if (msgs[msgNum].getFlags().contains(Flag.SEEN))
     297                                        continue;
     298                                count++;
     299                        }
     300                } catch (MessagingException e) {
     301                        // TODO Auto-generated catch block
     302                        e.printStackTrace();
     303                }
     304                return count;
     305        }
     306
     307        public String getMail() {
     308                StringBuffer sb = new StringBuffer();
     309                // -- Get the message wrappers and process them --
     310                Message[] msgs;
     311                try {
     312                        msgs = _folder.getMessages();
     313                        for (int msgNum = 0; msgNum < msgs.length; msgNum++) {
     314                                if (msgs[msgNum].getFlags().contains(Flag.SEEN))
     315                                        continue;
     316                                // Only get messages that have not been read
     317                                sb.append(getTextMessage(msgs[msgNum]));
     318                                sb.append('\n');
     319                        }
     320                } catch (MessagingException e) {
     321                        e.printStackTrace();
     322                }
     323                sb.deleteCharAt(sb.length() - 1);
     324                return sb.toString();
     325        }
     326
     327        /**
     328         * "getTextMessage()" method to print a message.
     329         */
     330        public String getTextMessage(Message message) {
     331                StringBuffer sb = new StringBuffer();
     332               
     333                try {
     334                        // Get the header information
     335                        String from = ((InternetAddress) message.getFrom()[0])
     336                                        .getPersonal();
     337                        if (from == null)
     338                                from = ((InternetAddress) message.getFrom()[0]).getAddress();
     339                        sb.append("FROM: " + from);
     340                        String subject = message.getSubject();
     341                        sb.append("SUBJECT: " + subject);
     342                        // -- Get the message part (i.e. the message itself) --
     343                        Part messagePart = message;
     344                        Object content = messagePart.getContent();
     345                        // -- or its first body part if it is a multipart message --
     346                        if (content instanceof Multipart) {
     347                                messagePart = ((Multipart) content).getBodyPart(0);
     348                                System.out.println("[ Multipart Message ]");
     349                        }
     350                        // -- Get the content type --
     351                        String contentType = messagePart.getContentType();
     352                        // -- If the content is plain text, we can print it --
     353                        //System.out.println("CONTENT:" + contentType);
     354                        if (contentType.startsWith("text/plain")
     355                                        || contentType.startsWith("text/html")) {
     356                                InputStream is = messagePart.getInputStream();
     357                                BufferedReader reader = new BufferedReader(
     358                                                new InputStreamReader(is));
     359                                String thisLine = reader.readLine();
     360                                while (thisLine != null) {
     361                                        sb.append(thisLine);
     362                                        thisLine = reader.readLine();
     363                                }
     364                        }
     365                        sb.append("-----------------------------");
     366                } catch (Exception ex) {
     367                        ex.printStackTrace();
     368                }
     369                return sb.toString();
     370        }
    153371}
Note: See TracChangeset for help on using the changeset viewer.