gpt4 book ai didi

java - 使用 imap 从 Gmail 接收附件

转载 作者:行者123 更新时间:2023-12-01 05:25:03 25 4
gpt4 key购买 nike

我正在制作一个小应用程序,用于访问 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com