java mail API转发邮件功能

时间:2017-03-30 05:20:14

标签: java email javamail

我正在开发一个独立的java实用程序,它将连接到任何组织的现有邮箱,并将读取/检查收件箱中的邮件,如果任何邮件的地址字段(“TO和CC”)超过2000个字符的字符数限制如果它超过限制,那么它将转发相同的邮件一个电子邮件ID,否则什么也不做......。我已经编写了转发下面给出的邮件功能的代码......它工作得很好...邮件是转发,但它显示异常.... 请说明我缺少的地方......

public class ForwardMail {

    public static void main(String[] args){
        Properties properties = new Properties();
          properties.put("mail.store.protocol", "pop3");
          properties.put("mail.pop3s.host", "mailcluster.mycompany.com");
          properties.put("mail.pop3s.port", "995");
          properties.put("mail.pop3.starttls.enable", "true");
          properties.put("mail.smtp.auth", "true"); /* may be commented later*/
          properties.put("smtp.starttls.enable", "true");
          properties.put("mail.smtp.host", "mailcluster.mycompany.com");
          properties.put("mail.smtp.port", "25");

        //  Session session = Session.getDefaultInstance(properties);
          Session session = Session.getInstance(properties,new javax.mail.Authenticator() {  
                protected PasswordAuthentication getPasswordAuthentication() {  
                    return new PasswordAuthentication("myname@mycompany.com","mypassword@123");  
                }  
              });
     try{
         // session.setDebug(true);
         // Get a Store object and connect to the current host
         Store store = session.getStore("pop3s");
         store.connect("mailcluster.mycompany.com", "myname@mycompany.com","mypassword@123");


         // Create a Folder object and open the folder
         Folder folder = store.getFolder("inbox");
         folder.open(Folder.READ_ONLY);
         BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
         Message[] messages = folder.getMessages();
         if (messages.length != 0) {

         for (int i = 0, n = messages.length; i < n; i++) {
            Message message = messages[i];
            // Get all the information from the message
           // String from = InternetAddress.toString(message.getFrom());
            String from = InternetAddress.toString(message.getRecipients(Message.RecipientType.TO));
            if (from != null) {
               System.out.println("From:"  + from);
            }
            /*String replyTo = InternetAddress.toString(message.getReplyTo());
            if (replyTo != null) {
               System.out.println("Reply-to: " + replyTo);
            }*/
            String to = InternetAddress.toString(message.getRecipients(Message.RecipientType.TO));
            if (to != null) {
               System.out.println("To: " + to);
            }

            String subject = message.getSubject();
            if (subject != null) {
               System.out.println("Subject: " + subject);
            }
            /*Date sent = message.getSentDate();
            if (sent != null) {
               System.out.println("Sent: " + sent);
            }*/
            System.out.print("Do you want to reply [y/n] : ");
            String ans = reader.readLine();
            if ("Y".equals(ans) || "y".equals(ans)) {
               Message forward = new MimeMessage(session);
               // Fill in header
               forward.setRecipients(Message.RecipientType.TO,InternetAddress.parse(from));
               forward.setSubject("Fwd: " + message.getSubject());
               forward.setFrom(new InternetAddress(to));

               // Create the message part
               MimeBodyPart messageBodyPart = new MimeBodyPart();
               // Create a multipart message
               Multipart multipart = new MimeMultipart();
               // set content
               messageBodyPart.setContent(message, "message/rfc822");
               // Add part to multi part
               multipart.addBodyPart(messageBodyPart);
               // Associate multi-part with message
               forward.setContent(multipart);
               forward.saveChanges();
               // Transport.send(forward);
               // Send the message by authenticating the SMTP server
               // Create a Transport instance and call the sendMessage
               Transport t = session.getTransport("smtp");
               try {
                  //connect to the smpt server using transport instance
                  t.connect("myname@mycompany.com", "mypassword@123");
                  t.sendMessage(forward, forward.getAllRecipients());

               } finally {
                  t.close();
               }

               System.out.println("message forwarded successfully....");

            // close the store and folder objects
            folder.close(false);
            store.close();
            }// end if

         }// end for
   }// end if
     }   catch(Exception e) {
          e.printStackTrace();  
    }
        }
    }

以下是我得到的例外......

java.lang.IllegalStateException: Folder is not Open
at com.sun.mail.pop3.POP3Folder.checkOpen(POP3Folder.java:551)
at com.sun.mail.pop3.POP3Folder.getProtocol(POP3Folder.java:581)
at com.sun.mail.pop3.POP3Message.loadHeaders(POP3Message.java:606)
at com.sun.mail.pop3.POP3Message.getHeader(POP3Message.java:383)
at javax.mail.internet.MimeMessage.getAddressHeader(MimeMessage.java:701)
at javax.mail.internet.MimeMessage.getRecipients(MimeMessage.java:534)
at servion.ForwardMail.main(ForwardMail.java:56)

如何删除此异常???

1 个答案:

答案 0 :(得分:0)

您在处理完一封邮件后关闭该文件夹,这意味着您在第二封邮件中访问Message对象时已关闭,因此JavaMail无法获取邮件数据来自服务器。

虽然您正在修复此问题,但请务必修复这些common JavaMail mistakes

最后,"smtp.starttls.enable"属性应为"mail.smtp.starttls.enable"