public void getMessageById(
#PathParam("folderName") String folderName,
#PathParam("id") String id) {
MailMessage mailMessage = new MailMessage();
MimeMessage mimeMessage = null;
try {
Store store = mailSession.getStore();
store.connect("localhost", email, password);
Folder folder = store.getDefaultFolder();
folder = folder.getFolder(folderName.toUpperCase());
folder.open(Folder.READ_ONLY);
SearchTerm searchTerm = new MessageIDTerm(id);
Message[] messages = folder.search(searchTerm);
if (messages.length > 0) {
mimeMessage = (MimeMessage) messages[0];
}
if (mimeMessage != null) {
Object objRef = mimeMessage.getContent();
if (objRef != null) {
// if message content is not multipart
if (!(objRef instanceof Multipart)) {
//get message text here
System.out.println(mimeMessage.getContent().toString())
} else {
Multipart multipart = (Multipart) objRef;
for (int i = 0; i < multipart.getCount(); i++) {
BodyPart bodyPart = multipart.getBodyPart(i);
if (bodyPart.isMimeType("text/*")) {
//get message text here
System.out.println(bodyPart.getContent()
.toString())
}
if (!Part.ATTACHMENT.equalsIgnoreCase(bodyPart
.getDisposition())) {
continue; // dealing with attachments only
}
if (bodyPart.isMimeType("image/*")) {
}
}
}
}
}
folder.close(false);
store.close();
} catch (MessagingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
The problem is that it take long time to fetch message text .
Is Object objRef = mimeMessage.getContent(); fetching all the content , if so is there any way to avoid fetching all the contents
Thanks for help ...
Rather than calling getContent and switching on whether it's a Multipart or not, use mimeMessage.isMimeType("multipart/") and mimeMessage.isMimeType("text/"). See the msgshow.java sample program.
Instead of fetching the text content all at once, you can use bodyPart.getInputStream to read it incrementally, which might help depending on what you're doing with it once you read it.
And of course you can use the Folder.fetch method to prefetch message metadata to speed up other parts of processing the messages. See the msgshow.java program again for an example.
Related
I am sending variables from ajax to java! in my ajax method I am sending 2 variables: idtabPrest and idPolice!
I am getting an error exception because I am not passing the File ! how can I make this function work and read the variables even if i am not sending the File.
I commented the Try/catch of the file to pass the variables! but in some ajax methods I am using the file.
public String upload_via_ajax() {
try {
String property = "java.io.tmpdir";
String tempDir = System.getProperty(property);
String html = "inside upload via ajax";
// try {
// File destFile = new File(tempDir, myFileFileName.substring(0,
// myFileFileName.lastIndexOf(".")) + ".csv");
// FileUtils.copyFile(myFile, destFile);
//
// getRequest().getSession().setAttribute("filePath",
// destFile.getPath());
//POUR REFERENCE DECLARATION
if(annee != null) {
TableReferentielDto tableReferentielDto = new TableReferentielDto();
tableReferentielDto.setId(Long.parseLong(annee));
TableReferentielDto anneeLabel =(TableReferentielDto) tableReferentielGetByIdCmd
.execute(tableReferentielDto);
getRequest().getSession().setAttribute("annee",
anneeLabel.getLibelle());
}
//POUR DATE DEBUT DECLARATION
if(moisDebutDeclaration != null){
getRequest().getSession().setAttribute("moisDebutDeclaration",
moisDebutDeclaration);
}
//POUR DATE FIN DECLARATION
if(moisFinDeclaration != null){
getRequest().getSession().setAttribute("moisFinDeclaration",
moisFinDeclaration);
}
//ID POLICE
if(idPolice != null){
getRequest().getSession().setAttribute("idPolice",
idPolice);
}
if(idTabPrest != null) {
getRequest().getSession().setAttribute("idTabPrest",
idTabPrest);
}
if(idTabTarif != null){
getRequest().getSession().setAttribute("idTabTarif",
idTabTarif);
}
html = "file uploaded";
// } catch (IOException e) {
//
// html = "error in uploading file";
// e.printStackTrace();
// }
return SUCCESS;
} catch (Exception e) {
return SUCCESS;
}
}
I have written two methods one for attachments and one email body content. I need to extract the images from email body. These two methods are working fine but when images are coming in email body it is should be saved in database. So it can be used later.
For attachmnents:-
public static List getAttachments(MimeMultipart multipart, List existingAttachments) {
if (multipart != null) {
try {
if (existingAttachments == null) {
existingAttachments = new ArrayList<MimeBodyPart>();
}
for (int i = 0; i < multipart.getCount(); i++) {
if (multipart.getBodyPart(i) instanceof MimeBodyPart) {
MimeBodyPart currentPart = (MimeBodyPart) multipart.getBodyPart(i);
if (Part.ATTACHMENT.equalsIgnoreCase(currentPart.getDisposition())) {
if (!existingAttachments.contains(currentPart)) {
existingAttachments.add(currentPart);
System.out.println(currentPart.getFileName());
}
} else if (currentPart.getContent() instanceof MimeMultipart) {
existingAttachments = getAttachments((MimeMultipart) currentPart.getContent(), existingAttachments);
}
}
}
} catch (MessagingException ex) {
LoggerFactory.getLogger(EmailUtil.class.getName()).error(ex.getMessage());
} catch (IOException ex) {
LoggerFactory.getLogger(EmailUtil.class.getName()).error(ex.getMessage());
}
}
return existingAttachments;
}
for email Body ContentThis method is extracting email body content
public static String getContent(MimeMultipart multipart) {
String emailContent = null;
if (multipart != null) {
try {
for (int i = 0; i < multipart.getCount(); i++) {
if (multipart.getBodyPart(i) instanceof MimeBodyPart) {
MimeBodyPart currentPart = (MimeBodyPart) multipart.getBodyPart(i);
if (Part.INLINE.equalsIgnoreCase(currentPart.getDisposition())) {
LoggerFactory.getLogger(EmailUtil.class.getName()).info("Content dispo is inline");
emailContent = (String) currentPart.getContent();
} else if (currentPart.getDisposition() == null && currentPart.getContentType().toLowerCase().contains("text")) {
LoggerFactory.getLogger(EmailUtil.class.getName()).info("Content dispo is null and type is text/*");
try {
emailContent = (String) currentPart.getContent();
} catch (ClassCastException ex) {
LoggerFactory.getLogger(EmailUtil.class.getName()).warn("Classcast exception caught and managed");
try {
InputStream is = currentPart.getInputStream();
emailContent = IOUtils.toString(is, currentPart.getEncoding());
Document doc=Jsoup.parse(emailContent);
Elements elements =doc.getElementsByTag("img");
System.out.println(elements);
int htmlCloseIndex = emailContent.indexOf("</html>");
emailContent = emailContent.substring(0, htmlCloseIndex);
emailContent+="</html>";
} catch (Exception e) {
LoggerFactory.getLogger(EmailUtil.class.getName()).error("Exception rebound caught and managed, email content will not read");
//emailContent = "Unable to read email content";
e.printStackTrace();
}
}
}else if (currentPart.getDisposition() == null && currentPart.getContentType().contains("TEXT")) {
LoggerFactory.getLogger(EmailUtil.class.getName()).info("Content dispo is null and type is TEXT/*");
try {
emailContent = (String) currentPart.getContent();
} catch (ClassCastException ex) {
LoggerFactory.getLogger(EmailUtil.class.getName()).warn("Classcast exception caught and managed");
try {
InputStream is = currentPart.getInputStream();
emailContent = IOUtils.toString(is, currentPart.getEncoding());
int htmlCloseIndex = emailContent.indexOf("</html>");
emailContent = emailContent.substring(0, htmlCloseIndex);
emailContent+="</html>";
} catch (Exception e) {
LoggerFactory.getLogger(EmailUtil.class.getName()).error("Exception rebound caught and managed, email content will not read");
//emailContent = "Unable to read email content";
e.printStackTrace();
}
}
}
else if (currentPart.getContent() instanceof MimeMultipart) {
emailContent = getContent((MimeMultipart) currentPart.getContent());
}
}
}
} catch (MessagingException ex) {
LoggerFactory.getLogger(EmailUtil.class.getName()).error(ex.getMessage());
LoggerFactory.getLogger(EmailUtil.class.getName()).warn("email content will not read");
//emailContent = "Unable to read email content";
} catch (IOException ex) {
LoggerFactory.getLogger(EmailUtil.class.getName()).error(ex.getMessage());
LoggerFactory.getLogger(EmailUtil.class.getName()).warn("email content will not read");
// emailContent = "Unable to read email content";
} catch (ClassCastException ex) {
LoggerFactory.getLogger(EmailUtil.class.getName()).warn("Classcast exception caught and managed");
// emailContent = "Unable to read email content";
}
}
return emailContent;
}
Okay one starts with the <img src="..."> tags, you already took:
Elements elements = doc.getElementsByTag("img");
An img tag for an embedded image looks like:
<img src="data:image/jpeg;base64,..." ...>
So having the src attribute do:
String src = ...
if (src.startsWith("data:")) { // Embedded image data.
int p = src.indexOf(';'); // Or better ";base64,"
if (p == -1) {
throw new IllegalArgumentException();
}
String mimeType = src.substring(5, p);
String base64Data = src.substring(p + 1 + 6 + 1); // ";base64,"
byte[] data = Base64.getDecoder().decode(base64Data);
String file = "test." + mimeType.replaceFirst("^.*/(.*)$", "$1");
Path path = Paths.get(file);
Files.write(path, data);
}
I have a Java web application in which a page ReceiveMail.jsp shows a progress bar which indicates how many emails have been received. A Refresh button on the page makes an AJAX call to a servlet named EmailRecServlet.java.
Codes for both the files are as follows
ReceiveMail.jsp JavaScript function that gives an AJAX call to the servlet:
<head>
<script type="text/javascript">
var requestObj = false;
if (window.XMLHttpRequest) {
requestObj = new XMLHttpRequest();
} else if (window.ActiveXObject) {
requestObj = new ActiveXObject("Microsoft.XMLHTTP");
}
function getUpdates()
{
if (requestObj) {
requestObj.open("GET", "http://localhost:8084/AyreonDepartmentManager/EmailRecServlet/*");
requestObj.onreadystatechange = function ()
{
if (requestObj.readyState == 4 && requestObj.status == 200) {
document.getElementById("progressbar").value = requestObj.responseText;
if(document.getElementById("progressbar").value == 3) {
window.location.href = "abc.jsp";
}
}
}
requestObj.send(null);
}
}
EmailRecServlet.java is the Servlet file :
public class EmailRecServlet extends HttpServlet {
#Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException {
response.setContentType("text/html;charset=UTF-8");
try (PrintWriter out = response.getWriter()) {
HttpSession session = request.getSession();
ServletContext context = request.getServletContext();
final String user = context.getInitParameter("user");
final String password = context.getInitParameter("pass");
int oldinboxsize = Integer.parseInt(context.getAttribute("Old Inbox Size").toString());
//1) get the session object
Properties properties = new Properties();
properties.put("mail.store.protocol", "imaps");
Session emailSession = Session.getDefaultInstance(properties,
new javax.mail.Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(user, password);
}
});
//2) create the POP3 store object and connect with the pop server
Store emailStore = emailSession.getStore("imaps");
emailStore.connect("imap.gmail.com", user, password);
//3) create the folder object and open it
Folder emailFolder = emailStore.getFolder("INBOX");
emailFolder.open(Folder.READ_ONLY);
//4) retrieve the messages from the folder in an array and print it
Message[] messages = emailFolder.getMessages();
int msgindex = 0;
int newinboxsize = messages.length;
if (newinboxsize > oldinboxsize) {
for(int i = 1; i <= (newinboxsize-oldinboxsize); i++) {
msgindex = messages.length-i;
Message message = messages[msgindex];
BodyPart clearTextPart = null;
out.write("Forming Message");
if (message instanceof MimeMessage) {
MimeMessage m = (MimeMessage) message;
Object contentObject = m.getContent();
if (contentObject instanceof Multipart) {
clearTextPart = null;
Multipart content = (Multipart) contentObject;
int count = content.getCount();
for (int j = 0; j < count; j++) {
BodyPart part = content.getBodyPart(j);
if (part.isMimeType("text/plain")) {
clearTextPart = part;
out.println("clearText obtained");
out.println("clearText is : ");
out.println(clearTextPart.getContent().toString());
}
}
session.setAttribute((message.getFrom()[msgindex].toString()), (String) clearTextPart.getContent());
out.println("written into session");
}
}
}
String difference = Integer.toString(newinboxsize - oldinboxsize);
out.write(difference);
}
//5) close the store and folder objects
emailFolder.close(false);
emailStore.close();
}
catch(MessagingException e) { e.printStackTrace(); }
catch(IOException e) { e.printStackTrace(); }
catch(Exception e) { e.printStackTrace(); }
}
}
The error that I am getting is that the AJAX call is working properly, but when the control is inside the servlet it only executes till the line:
out.println(clearTextPart.getContent().toString());
and because of this, my progress bar also stays at 0 and does not progress to reflect the new emails I received.
The response body for that particular request shows blank strings when viewed in Network tab in IE debugger.
What could possibly cause the error? And how do I remove this error? How do I get the email content into my Session object so that I can access it on my JSP page?
Please help me out.
The error got resolved. What worked for me was:
session.setAttribute((message.getFrom()[0].toString()), (String) clearTextPart.getContent());
I want to get the body of a mail without its signature. This code is fetching all text type. How can I extract the text without mail signature?
public static void saveParts(Object content) throws MessagingException {
try {
if (content instanceof Multipart) {
Multipart multi = ((Multipart) content);
int parts = multi.getCount();
for (int j = 0; j < parts; ++j) {
MimeBodyPart part = (MimeBodyPart) multi.getBodyPart(j);
if (part.getContent() instanceof Multipart) {
saveParts(part.getContent());
} else {
if (part.isMimeType("text/plain")) {
System.out.println("message content : " + part.getContent());
}
}
}
}
} catch(MessagingException ex){
ex.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
Signature is considered as a part of the mail body content. There is no separate method to fetch the signature alone. You will have to fetch the body of the mail, parse and use it as per your requirement.
I am trying to get emails from Gmail using Java. I using the java-gmail-imap library. When I try to get message.getContent(), it is always giving Inputstream. It doesn't provide me enough information to parse through the Part. My code looks like this. Please let me know what I am missing?
IMAPStore imapStore = OAuth2Authenticator.connectToImap(
"imap.gmail.com", 993, email, token, false);
Folder folder = imapStore.getFolder("Inbox");
if (folder.isOpen()) {
if ((folder.getMode() & Folder.READ_WRITE) != 0) {
folder.close(false);
folder.open(Folder.READ_ONLY);
}
} else {
try {
folder.open(Folder.READ_ONLY);
} catch (Exception e) {
e.printStackTrace();
}
}
Message[] messages = null;
SearchTerm newerThan = new ReceivedDateTerm(ComparisonTerm.GT, lastDate);
messages = folder.search(newerThan);
FetchProfile fp = new FetchProfile();
fp.add("X-GM-MSGID");
fp.add(UIDFolder.FetchProfileItem.UID);
fp.add(IMAPFolder.FetchProfileItem.X_GM_MSGID);
//fp.add(FetchProfile.Item.ENVELOPE);
//fp.add(FetchProfileItem.FLAGS);
//fp.add(FetchProfileItem.CONTENT_INFO);
// fp.add("X-mailer");
folder.fetch(messages, fp);
for (Message message : messages) {
if (message != null) {
Object o = message.getContent();
if (o instanceof String) {
logger.info("Message content is string");
} else if (o instanceof Multipart) {
logger.info("Message content is multipart");
} else if (o instanceof Message) {
logger.info("Nested Message");
} else if (o instanceof InputStream) {
logger.info("Message content is inputstream");
}
}
}
Edit:
Issue is fixed by adding mailcap
CommandMap.setDefaultCommandMap(new com.google.code.javax.activation.MailcapCommandMap(this.getClass().getClassLoader().getResourceAsStream("mailcap")));