Blame | Last modification | View Log | RSS feed
package in.shop2020.util;import java.io.File;import java.io.FileOutputStream;import java.io.IOException;import java.io.InputStream;import java.util.Calendar;import java.util.Date;import java.util.Properties;import java.io.*;import javax.activation.DataHandler;import javax.mail.BodyPart;import javax.mail.Folder;import javax.mail.Message;import javax.mail.MessagingException;import javax.mail.Multipart;import javax.mail.NoSuchProviderException;import javax.mail.Part;import javax.mail.Session;import javax.mail.Store;import javax.mail.search.ComparisonTerm;import javax.mail.search.ReceivedDateTerm;import javax.mail.internet.*;public class EmailUtils {private static final int DESCRIPTION_MAX_WIDTH = 10;private static void getAttachment(Part p) throws MessagingException, IOException {String listOfFiles = "";if (p.isMimeType("multipart/*")) {Multipart multipart = (Multipart) p.getContent();for (int x = 0; x < multipart.getCount(); x++) {BodyPart bodyPart = multipart.getBodyPart(x);if(!Part.ATTACHMENT.equalsIgnoreCase(bodyPart.getDisposition())) {continue; // we want attachments only}String fileName = bodyPart.getFileName();InputStream is = bodyPart.getInputStream();File f = new File("/var/crm/archive/" + fileName);FileOutputStream fos = new FileOutputStream(f);byte[] buf = new byte[4096];int bytesRead;while((bytesRead = is.read(buf))!=-1) {fos.write(buf, 0, bytesRead);}fos.close();listOfFiles += "/var/crm/archive/" + fileName + ";";if (listOfFiles.length() > DESCRIPTION_MAX_WIDTH) {listOfFiles = listOfFiles.substring(0, DESCRIPTION_MAX_WIDTH);listOfFiles += "\n\nTHIS TEXT IS TRUNCATED. PLEASE VISIT INBOX TO SEE COMPLETE DETAILS.";}//end of if}//end for loop}//end ifSystem.out.println("name of attachments: " + listOfFiles);}//end getAttachmentpublic static void main(String[] args) throws MessagingException, IOException {/* Store store = null;Properties props = System.getProperties();props.setProperty("mail.store.protocol", "imaps");try {Session session = Session.getDefaultInstance(props, null);store = session.getStore("imaps");store.connect("imap.gmail.com", "anupam.singh@shop2020.in", "M&&840aa");} catch (NoSuchProviderException e) {e.printStackTrace();} catch (MessagingException e) {e.printStackTrace();}Folder inbox = store.getFolder("inbox");inbox.open(Folder.READ_ONLY);Date lastReceivedEmailTimestamp = Calendar.getInstance().getTime();lastReceivedEmailTimestamp.setHours(10);for (Message message : inbox.search(new ReceivedDateTerm(ComparisonTerm.GE, lastReceivedEmailTimestamp))){EmailUtils.getAttachment(message);}*/}}