java - 使用 imap 从 Gmail 接收附件

标签 java email gmail imap jakarta-mail

我正在制作一个小应用程序,用于访问 gmail 并获取带有附件的消息。

    Properties props = System.getProperties();
        props.put("mail.user", login);
        props.put("mail.host", pop3Host);
        props.put("mail.debug", "false");
        props.setProperty("mail.store.protocol", "imaps");
        // set this session up to use SSL for IMAP connections
        props.setProperty("mail.imap.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
        // don't fallback to normal IMAP connections on failure.
        props.setProperty("mail.imap.socketFactory.fallback", "false");
        // use the simap port for imap/ssl connections.
        props.setProperty("mail.imap.socketFactory.port", settings.getPop3Port().toString());
                props.setProperty("mail.imap.partialfetch", "false");
                props.setProperty("mail.imaps.partialfetch", "false");
        props.put("mail.transport.protocol", "smtp");
        props.put("mail.smtp.auth", settings.getSmtpAuth().toString());
        Session session=null;

        session = Session.getInstance(props, new GMailAuthenticator(login, password));

        Store store = null;
            store = session.getStore("imaps");
            store.connect();

        Folder inbox = store.getFolder("Inbox");
        inbox.open(Folder.READ_WRITE);
        Flags seen = new Flags(Flags.Flag.SEEN);
        FlagTerm unseenFlagTerm = new FlagTerm(seen, false);
        SearchTerm st = new AndTerm(new SubjectTerm(subjectSubstringToSearch), unseenFlagTerm);

            // Get some message references

            Message [] messages = inbox.search(st);

            System.out.println(messages.length + " -- Messages amount");

        //Message[] messages = inbox.search(new FlagTerm(new Flags(Flags.Flag.SEEN), false));
        ArrayList<String> attachments = new ArrayList<String>();

        LinkedList<MessageBean> listMessages = getPart(messages, attachments);
        for(String s :attachments) {
            System.out.println(s);
        }
        inbox.setFlags(messages, new Flags(Flags.Flag.SEEN), true);

        BufferedReader reader = new BufferedReader (
            new InputStreamReader(System.in));
        for (int i=0, j=messages.length; i<j; i++) {
            messages[i].setFlag(Flags.Flag.SEEN, true);
        }
        inbox.close(true);
        store.close();
        return listMessages;
    }

    private static LinkedList<MessageBean> getPart(Message[] messages, ArrayList<String> attachments) throws MessagingException, IOException {
        LinkedList<MessageBean> listMessages = new LinkedList<MessageBean>();
        SimpleDateFormat f = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        for (Message inMessage : messages) {

            attachments.clear();
            if (inMessage.isMimeType("text/plain")) {
                MessageBean message = new MessageBean(inMessage.getMessageNumber(), MimeUtility.decodeText(inMessage.getSubject()), inMessage.getFrom()[0].toString(), null, inMessage.getSentDate(), (String) inMessage.getContent(), false, null);
                listMessages.add(message);
                System.out.println("text/plain");
            } else if (inMessage.isMimeType("multipart/*")) {
                System.out.println("multipart");
                Multipart mp = (Multipart) inMessage.getContent();
                MessageBean message = null;
                System.out.println(mp.getCount());
                for (int i = 0; i < mp.getCount(); i++) {
                    Part part = mp.getBodyPart(i);
                    if ((part.getFileName() == null || part.getFileName() == "") && part.isMimeType("text/plain")) {
                        System.out.println(inMessage.getSentDate());
                        message = new MessageBean(inMessage.getMessageNumber(), inMessage.getSubject(), inMessage.getFrom()[0].toString(), null, inMessage.getSentDate(), (String) part.getContent(), false, null);
                    } else if (part.getFileName() != null || part.getFileName() != "") {
                        if ((part.getDisposition() != null) && (part.getDisposition().equals(Part.ATTACHMENT))) {
                            System.out.println(part.getFileName());
                            attachments.add(saveFile(MimeUtility.decodeText(part.getFileName()), part.getInputStream()));
                            if (message != null) {
                                message.setAttachments(attachments);
                            }
                        }
                    }
                }
                listMessages.add(message);
            }
        }
        return listMessages;
    }
//method for saving attachment on local disk
  private static String saveFile(String filename, InputStream input) {
  String strDirectory = "D:\\temp\\attachments";  
  try{
  // Create one directory
  boolean success = (new File(strDirectory)).mkdir();
  if (success) {
  System.out.println("Directory: " 
   + strDirectory + " created");
  }
  } catch (Exception e) {//Catch exception if any
    System.err.println("Error: " + e.getMessage());
  }
        String path = strDirectory+"\\" + filename;
        try {
            byte[] attachment = new byte[input.available()];
            input.read(attachment);
            File file = new File(path);
            FileOutputStream out = new FileOutputStream(file);
            out.write(attachment);
            input.close();
            out.close();
            return path;
        } catch (IOException e) {
            e.printStackTrace();
        }
        return path;
    }
}

MessageBean:

 public class MessageBean implements Serializable {
    private String subject;
    private String from;
    private String to;
    private Date dateSent;
    private String content;
    private boolean isNew;
    private int msgId;
    private ArrayList<String> attachments;

    public MessageBean(int msgId, String subject, String from, String to, Date dateSent, String content, boolean isNew, ArrayList<String> attachments) {
        this.subject = subject;
        this.from = from;
        this.to = to;
        this.dateSent = dateSent;
        this.content = content;
        this.isNew = isNew;
        this.msgId = msgId;
        this.attachments = attachments;
    }

    public String getSubject() {
        return subject;
    }

    public void setSubject(String subject) {
        this.subject = subject;
    }

    public String getFrom() {
        return from;
    }

    public void setFrom(String from) {
        this.from = from;
    }

    public Date getDateSent() {
        return dateSent;
    }

    public void setDateSent(Date dateSent) {
        this.dateSent = dateSent;
    }

    public String getContent() {
        return content;
    }

    public void setContent(String content) {
        this.content = content;
    }

    public String getTo() {
        return to;
    }

    public void setTo(String to) {
        this.to = to;
    }

    public boolean isNew() {
        return isNew;
    }

    public void setNew(boolean aNew) {
        isNew = aNew;
    }

    public int getMsgId() {
        return msgId;
    }

    public void setMsgId(int msgId) {
        this.msgId = msgId;
    }

    public ArrayList<String> getAttachments() {
        return attachments;
    }

    public void setAttachments(ArrayList<String> attachments) {
        this.attachments = new ArrayList<String>(attachments);
    }
}

我可以连接到我的邮件帐户并查看未见邮件的数量,但 MessageBean 似乎没有填充附件。

最大的问题是我在没有互联网连接的计算机上开发我的应用程序。所以我构建了 jar,转到具有 inet、java -jar 的计算机,然后盯着 NullPointer 异常。我无法调试这个废话。请有人指出我的错误在哪里。

编辑 此代码适用于 gmail pop,显然还有另一个连接。

最佳答案

因为当你从中获取元素时,你的列表是空的,所以你可以在MessageBean中创建新的ArrayList对象,然后复制元素

  private List<String> attachments= new ArrayList<String>();

  public MessageBean(int msgId, String subject, String from, String to, Date dateSent, String content, boolean isNew, ArrayList<String> attachments) {
        this.subject = subject;
        this.from = from;
        this.to = to;
        this.dateSent = dateSent;
        this.content = content;
        this.isNew = isNew;
        this.msgId = msgId;
        this.attachments.addAll(attachments);
    }

关于java - 使用 imap 从 Gmail 接收附件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9800805/

相关文章:

Android 的电子邮件和 GMail 应用程序从电子邮件中删除 HTML 格式

google-apps-script - 使用 Google Sheet 中的 GmailApp.sendEmail 时如何包含用户 Gmail 签名

java - 我该如何解决这些错误?

java - 实时 java - 如何应用多次运行

swift - 通过 sendgrid 通过电子邮件发送捕获的图像

python - 在 python 中解析多部分电子邮件并保存附件

javascript - 使用 Chrome 扩展检测 Gmail 收件箱中的电子邮件

java - JExcel : Losing Cell Precison On Cells Having Formula ROUNDUP in MS Excel

java - 无法将 GridView 内的 ImageView 设置为从 Drawable 转换的 Bitmap

java - Spring(Hibernate)更新问题