List of usage examples for javax.mail Message getSubject
public abstract String getSubject() throws MessagingException;
From source file:com.cubusmail.mail.util.MessageUtils.java
/** * @param mailFolder//from w w w. ja v a2 s . c o m * @param msgs * @param extendedSearchFields * @param params * @return */ public static Message[] filterMessages(IMailFolder mailFolder, Message[] msgs, String extendedSearchFields, String[][] params) { if (!StringUtils.isEmpty(extendedSearchFields)) { String[] fields = StringUtils.split(extendedSearchFields, ','); List<Message> filteredMsgs = new ArrayList<Message>(); String fromValue = getParamValue(params, SearchFields.FROM.name()); String toValue = getParamValue(params, SearchFields.TO.name()); String ccValue = getParamValue(params, SearchFields.CC.name()); String subjectValue = getParamValue(params, SearchFields.SUBJECT.name()); String contentValue = getParamValue(params, SearchFields.CONTENT.name()); String dateFromValue = getParamValue(params, SearchFields.DATE_FROM.name()); String dateToValue = getParamValue(params, SearchFields.DATE_TO.name()); try { // Body search if (StringUtils.contains(extendedSearchFields, SearchFields.CONTENT.name())) { BodyTerm term = new BodyTerm(contentValue); msgs = mailFolder.search(term, msgs); if (msgs == null) { msgs = new Message[0]; } } for (Message message : msgs) { boolean contains = true; for (String searchField : fields) { if (SearchFields.FROM.name().equals(searchField)) { String from = MessageUtils.getMailAdressString(message.getFrom(), AddressStringType.COMPLETE); contains = StringUtils.containsIgnoreCase(from, fromValue); } if (contains && SearchFields.TO.name().equals(searchField)) { String to = MessageUtils.getMailAdressString( message.getRecipients(Message.RecipientType.TO), AddressStringType.COMPLETE); if (!StringUtils.isEmpty(to)) { contains = StringUtils.containsIgnoreCase(to, toValue); } else { contains = false; } } if (contains && SearchFields.CC.name().equals(searchField)) { String cc = MessageUtils.getMailAdressString( message.getRecipients(Message.RecipientType.CC), AddressStringType.COMPLETE); if (!StringUtils.isEmpty(cc)) { contains = StringUtils.containsIgnoreCase(cc, ccValue); } else { contains = false; } } if (contains && SearchFields.SUBJECT.name().equals(searchField)) { if (!StringUtils.isEmpty(message.getSubject())) { contains = StringUtils.containsIgnoreCase(message.getSubject(), subjectValue); } else { contains = false; } } if (contains && SearchFields.DATE_FROM.name().equals(searchField)) { Date dateFrom = new Date(Long.parseLong(dateFromValue)); if (message.getSentDate() != null) { contains = !message.getSentDate().before(dateFrom); } else { contains = false; } } if (contains && SearchFields.DATE_TO.name().equals(searchField)) { Date dateTo = new Date(Long.parseLong(dateToValue)); if (message.getSentDate() != null) { contains = !message.getSentDate().after(dateTo); } else { contains = false; } } } if (contains) { filteredMsgs.add(message); } } } catch (MessagingException ex) { log.warn(ex.getMessage()); } return filteredMsgs.toArray(new Message[0]); } return msgs; }
From source file:org.xwiki.contrib.mailarchive.internal.DefaultMailArchive.java
private List<String> loadAttachedMails(final List<Message> attachedMails, final String parentFullName, final boolean create) { final List<String> attachedMailsPages = new ArrayList<String>(); if (attachedMails.size() > 0) { logger.debug("Loading attached mails ..."); for (Message message : attachedMails) { try { MailLoadingResult result = loadMail(message, create, true, parentFullName); if (result.isSuccess()) { attachedMailsPages.add(result.getCreatedMailDocumentName()); } else { logger.warn("Could not create attached mail " + message.getSubject()); }/* w w w. ja v a 2s . c o m*/ } catch (Exception e) { logger.warn("Could not create attached mail because of " + e.getMessage()); if (logger.isDebugEnabled()) { logger.debug("Could not create attached mail ", e); } } } } return attachedMailsPages; }
From source file:com.ikon.util.MailUtils.java
/** * Convert Outlook Message to Mail/* ww w. j ava2s. c o m*/ */ public static Mail messageToMail(com.auxilii.msgparser.Message msg) throws MessagingException, IOException { com.ikon.bean.Mail mail = new com.ikon.bean.Mail(); Calendar receivedDate = Calendar.getInstance(); Calendar sentDate = Calendar.getInstance(); // Can be void if (msg.getDate() != null) { receivedDate.setTime(msg.getDate()); } // Can be void if (msg.getCreationDate() != null) { sentDate.setTime(msg.getCreationDate()); } if (msg.getBodyRTF() != null) { SimpleRTF2HTMLConverter converter = new SimpleRTF2HTMLConverter(); mail.setMimeType(MimeTypeConfig.MIME_HTML); mail.setContent(converter.rtf2html(msg.getBodyRTF())); } else if (msg.getBodyHTML() != null) { mail.setMimeType(MimeTypeConfig.MIME_HTML); mail.setContent(msg.getBodyHTML()); } else if (msg.getBodyText() != null) { mail.setMimeType(MimeTypeConfig.MIME_TEXT); mail.setContent(msg.getBodyText()); } else { mail.setMimeType(MimeTypeConfig.MIME_UNDEFINED); } if (msg.getToRecipient() != null) { mail.setTo(new String[] { msg.getToRecipient().getToName() + " <" + msg.getToRecipient().getToEmail() + ">" }); } mail.setSize(mail.getContent().length()); mail.setSubject((msg.getSubject() == null || msg.getSubject().isEmpty()) ? NO_SUBJECT : msg.getSubject()); mail.setFrom(msg.getFromName() + " <" + msg.getFromEmail() + ">"); mail.setCc(recipientToString(msg.getCcRecipients())); mail.setBcc(recipientToString(msg.getBccRecipients())); mail.setReceivedDate(receivedDate); mail.setSentDate(sentDate); return mail; }
From source file:com.ikon.util.MailUtils.java
/** * Convert Mime Message to Mail/*from w w w.j a v a2 s . c om*/ */ public static Mail messageToMail(Message msg) throws MessagingException, IOException { com.ikon.bean.Mail mail = new com.ikon.bean.Mail(); Calendar receivedDate = Calendar.getInstance(); Calendar sentDate = Calendar.getInstance(); // Can be void if (msg.getReceivedDate() != null) { receivedDate.setTime(msg.getReceivedDate()); } // Can be void if (msg.getSentDate() != null) { sentDate.setTime(msg.getSentDate()); } String body = getText(msg); // log.info("getText: "+body); if (body.charAt(0) == 'H') { mail.setMimeType(MimeTypeConfig.MIME_HTML); } else if (body.charAt(0) == 'T') { mail.setMimeType(MimeTypeConfig.MIME_TEXT); } else { mail.setMimeType(MimeTypeConfig.MIME_UNDEFINED); } String content = body.substring(1); // Need to replace 0x00 because PostgreSQL does not accept string containing 0x00 content = FormatUtil.fixUTF8(content); // Need to remove Unicode surrogate because of MySQL => SQL Error: 1366, SQLState: HY000 content = FormatUtil.trimUnicodeSurrogates(content); mail.setContent(content); if (msg.getFrom().length > 0) { mail.setFrom(MimeUtility.decodeText(msg.getFrom()[0].toString())); } mail.setSize(msg.getSize()); mail.setSubject((msg.getSubject() == null || msg.getSubject().isEmpty()) ? NO_SUBJECT : msg.getSubject()); mail.setTo(addressToString(msg.getRecipients(Message.RecipientType.TO))); mail.setCc(addressToString(msg.getRecipients(Message.RecipientType.CC))); mail.setBcc(addressToString(msg.getRecipients(Message.RecipientType.BCC))); mail.setReceivedDate(receivedDate); mail.setSentDate(sentDate); return mail; }
From source file:org.apache.jmeter.protocol.mail.sampler.MailReaderSampler.java
private void appendMessageData(SampleResult child, Message message) throws MessagingException, IOException { StringBuilder cdata = new StringBuilder(); cdata.append("Date: "); // $NON-NLS-1$ cdata.append(message.getSentDate());// TODO - use a different format here? cdata.append(NEW_LINE);/*from w w w . j a v a 2 s.co m*/ cdata.append("To: "); // $NON-NLS-1$ Address[] recips = message.getAllRecipients(); // may be null for (int j = 0; recips != null && j < recips.length; j++) { cdata.append(recips[j].toString()); if (j < recips.length - 1) { cdata.append("; "); // $NON-NLS-1$ } } cdata.append(NEW_LINE); cdata.append("From: "); // $NON-NLS-1$ Address[] from = message.getFrom(); // may be null for (int j = 0; from != null && j < from.length; j++) { cdata.append(from[j].toString()); if (j < from.length - 1) { cdata.append("; "); // $NON-NLS-1$ } } cdata.append(NEW_LINE); cdata.append("Subject: "); // $NON-NLS-1$ cdata.append(message.getSubject()); cdata.append(NEW_LINE); cdata.append(NEW_LINE); Object content = message.getContent(); if (content instanceof MimeMultipart) { appendMultiPart(child, cdata, (MimeMultipart) content); } else if (content instanceof InputStream) { child.setResponseData(IOUtils.toByteArray((InputStream) content)); } else { cdata.append(content); child.setResponseData(cdata.toString(), child.getDataEncodingNoDefault()); } }
From source file:org.openiam.idm.srvc.msg.service.MailSenderClient.java
public void send(Message msg) { Properties properties = System.getProperties(); properties.setProperty("mail.smtp.host", host); properties.setProperty("mail.transport.protocol", "smtp"); if (username != null && !username.isEmpty()) { properties.setProperty("mail.user", username); properties.setProperty("mail.password", password); }/*from w ww.j a v a 2 s . com*/ if (port != null && !port.isEmpty()) { properties.setProperty("mail.smtp.port", port); } Session session = Session.getDefaultInstance(properties); MimeMessage message = new MimeMessage(session); try { message.setFrom(msg.getFrom()); if (msg.getTo().size() > 1) { List<InternetAddress> addresses = msg.getTo(); message.addRecipients(TO, addresses.toArray(new Address[addresses.size()])); } else { message.addRecipient(TO, msg.getTo().get(0)); } if (msg.getBcc() != null && msg.getBcc().size() != 0) { if (msg.getTo().size() > 1) { List<InternetAddress> addresses = msg.getBcc(); message.addRecipients(BCC, addresses.toArray(new Address[addresses.size()])); } else { message.addRecipient(TO, msg.getBcc().get(0)); } } if (msg.getCc() != null && msg.getCc().size() > 0) { if (msg.getCc().size() > 1) { List<InternetAddress> addresses = msg.getCc(); message.addRecipients(CC, addresses.toArray(new Address[addresses.size()])); } else { message.addRecipient(CC, msg.getCc().get(0)); } } message.setSubject(msg.getSubject(), "UTF-8"); MimeBodyPart mbp1 = new MimeBodyPart(); // create the Multipart and add its parts to it Multipart mp = new MimeMultipart(); if (msg.getBodyType() == Message.BodyType.HTML_TEXT) { mbp1.setContent(msg.getBody(), "text/html"); } else { mbp1.setText(msg.getBody(), "UTF-8"); } if (port != null && !port.isEmpty()) { properties.setProperty("mail.smtp.port", port); } mp.addBodyPart(mbp1); if (msg.getAttachments().size() > 0) { for (String fileName : msg.getAttachments()) { // create the second message part MimeBodyPart mbpFile = new MimeBodyPart(); // attach the file to the message FileDataSource fds = new FileDataSource(fileName); mbpFile.setDataHandler(new DataHandler(fds)); mbpFile.setFileName(fds.getName()); mp.addBodyPart(mbpFile); } } // add the Multipart to the message message.setContent(mp); if (username != null && !username.isEmpty()) { properties.setProperty("mail.user", username); properties.setProperty("mail.password", password); properties.put("mail.smtp.auth", auth); properties.put("mail.smtp.starttls.enable", starttls); Transport mailTransport = session.getTransport(); mailTransport.connect(host, username, password); mailTransport.sendMessage(message, message.getAllRecipients()); } else { Transport.send(message); log.debug("Message successfully sent."); } } catch (Throwable e) { log.error("Exception while sending mail", e); } }
From source file:com.ephesoft.dcma.mail.service.MailServiceImpl.java
@Override public void mailOnError(final String subject, final Message previousMailMessage, final String batchClassName, final String userName, final String mailTemplatePath) throws DCMAApplicationException { LOGGER.debug("Creating mailMetaData odr mail or error."); if (null != subject && null != batchClassName && null != userName && null != previousMailMessage) { final MailMetaData metaData = new MailMetaData(); metaData.setFromAddress(fromMail); metaData.setFromName(fromMail);//from w ww .ja v a 2 s . c o m metaData.setSubject(subject); metaData.setToAddresses(new ArrayList<String>(StringUtils.commaDelimitedListToSet(toMail))); final MailContentModel model = new MailContentModel(); model.add(MailConstants.BATCH_CLASS, batchClassName); model.add(MailConstants.USER_ID, userName); try { String ccString = Arrays.toString(previousMailMessage.getHeader(MailConstants.CC)) .replace(MailConstants.OPENING_BRACKET, MailConstants.SPACE) .replace(MailConstants.CLOSING_BRACKET, MailConstants.EMPTY_STRING); String toString = Arrays.toString(previousMailMessage.getHeader(MailConstants.TO)) .replace(MailConstants.OPENING_BRACKET, MailConstants.SPACE) .replace(MailConstants.CLOSING_BRACKET, MailConstants.EMPTY_STRING); // below date format will be used to format date string received // from mail header. Mail header can provide a lot more // info. SimpleDateFormat simpleDateFormat = new SimpleDateFormat(MailConstants.DATE_FORMAT); model.add(MailConstants.SUBJECT, previousMailMessage.getSubject()); model.add(MailConstants.FROM, Arrays.toString(previousMailMessage.getHeader(MailConstants.FROM)) .replace(MailConstants.OPENING_BRACKET, MailConstants.SPACE) .replace(MailConstants.CLOSING_BRACKET, "")); model.add(MailConstants.TO, toString.equalsIgnoreCase(MailConstants.NULL_STRING) ? MailConstants.EMPTY_STRING : toString); model.add(MailConstants.CC, ccString.equalsIgnoreCase(MailConstants.NULL_STRING) ? MailConstants.EMPTY_STRING : ccString); model.add(MailConstants.RECEIVED_DATE, simpleDateFormat .parseObject(previousMailMessage.getHeader(MailConstants.DATE_STRING)[0].toString()) .toString()); } catch (javax.mail.MessagingException mailException) { LOGGER.error("Error encountered while extarcting info from previos mail object", mailException); throw new DCMAApplicationException( "Error encountered while extarcting infor from previos mail object", mailException); } catch (java.text.ParseException parseException) { LOGGER.error( "Error encountered while parsing date extracted from mail header of previos mail object", parseException); throw new DCMAApplicationException( "Error encountered while parsing received date from previos mail object", parseException); } LOGGER.debug( EphesoftStringUtil.concatenate("Batch Class Name: ", batchClassName, " UserName: ", userName)); sendTextMailWithClasspathTemplate(metaData, mailTemplatePath, model, previousMailMessage); } else { LOGGER.error( "Either or all of the following values are null. Error notification mail cann't be sent. \n Subject,BatchClassName, UserName"); } }
From source file:com.midori.confluence.plugin.mail2news.Mail2NewsJob.java
/** * Send an mail containing the error message back to the * user which sent the given message./* www .j a va 2s . c om*/ * * @param m The message which produced an error while handling it. * @param error The error string. */ private void sendErrorMessage(Message m, String error) throws Exception { /* get the SMTP mail server */ SMTPMailServer smtpMailServer = MailFactory.getServerManager().getDefaultSMTPMailServer(); if (smtpMailServer == null) { log.warn("Failed to send error message as no SMTP server is configured"); return; } /* get system properties */ Properties props = System.getProperties(); /* Setup mail server */ props.put("mail.smtp.host", smtpMailServer.getHostname()); /* get a session */ Session session = Session.getDefaultInstance(props, null); /* create the message */ MimeMessage message = new MimeMessage(session); message.setFrom(new InternetAddress(smtpMailServer.getDefaultFrom())); String senderEmail = getEmailAddressFromMessage(m); if (senderEmail == "") { throw new Exception("Unknown sender of email."); } message.addRecipient(Message.RecipientType.TO, new InternetAddress(senderEmail)); message.setSubject("[mail2news] Error while handling message (" + m.getSubject() + ")"); message.setText("An error occurred while handling your message:\n\n " + error + "\n\nPlease contact the administrator to solve the problem.\n"); /* send the message */ Transport tr = session.getTransport("smtp"); if (StringUtils.isBlank(smtpMailServer.getSmtpPort())) { tr.connect(smtpMailServer.getHostname(), smtpMailServer.getUsername(), smtpMailServer.getPassword()); } else { int smtpPort = Integer.parseInt(smtpMailServer.getSmtpPort()); tr.connect(smtpMailServer.getHostname(), smtpPort, smtpMailServer.getUsername(), smtpMailServer.getPassword()); } message.saveChanges(); tr.sendMessage(message, message.getAllRecipients()); tr.close(); }
From source file:com.midori.confluence.plugin.mail2news.Mail2NewsJob.java
/** * Create a blog post from the content and the attachments retrieved from a * mail message.//from www. j av a 2 s.co m * There are only two parameters, the other necessary parameters are global * variables. * * @param space The space where to publish the blog post. * @param m The message which to publish as a blog post. * @throws MessagingException Throws a MessagingException if something goes wrong when getting attributes from the message. */ private void createBlogPost(Space space, Message m) throws MessagingException { /* create the blogPost and add values */ BlogPost blogPost = new BlogPost(); /* set the creation date of the blog post to the current date */ blogPost.setCreationDate(new Date()); /* set the space where to save the blog post */ blogPost.setSpace(space); /* if the gallery macro is set and the post contains an image add the macro */ MailConfiguration config = configurationManager.getMailConfiguration(); if (config.getGallerymacro()) { /* gallery macro is set */ if (containsImage) { /* post contains an image */ /* add the macro */ blogEntryContent = blogEntryContent.concat("{gallery}"); } } /* set the blog post content */ if (blogEntryContent != null) { blogPost.setContent(blogEntryContent); } else { blogPost.setContent(""); } /* set the title of the blog post */ String title = m.getSubject(); /* check for illegal characters in the title and replace them with a space */ /* could be replaced with a regex */ /* Only needed for Confluence < 4.1 */ String version = GeneralUtil.getVersionNumber(); if (!Pattern.matches("^4\\.[1-9]+.*$", version)) { char[] illegalCharacters = { ':', '@', '/', '%', '\\', '&', '!', '|', '#', '$', '*', ';', '~', '[', ']', '(', ')', '{', '}', '<', '>', '.' }; for (int i = 0; i < illegalCharacters.length; i++) { if (title.indexOf(illegalCharacters[i]) != -1) { title = title.replace(illegalCharacters[i], ' '); } } } blogPost.setTitle(title); /* set creating user */ String creatorEmail = getEmailAddressFromMessage(m); String creatorName = "Anonymous"; User creator = null; if (creatorEmail != "") { SearchResult sr = userAccessor.getUsersByEmail(creatorEmail); Pager p = sr.pager(); List l = p.getCurrentPage(); if (l.size() == 1) { /* found a matching user for the email address of the sender */ creator = (User) l.get(0); creatorName = creator.getName(); } } //this.log.info("creatorName: " + creatorName); //this.log.info("creator: " + creator); blogPost.setCreatorName(creatorName); if (creator != null) { AuthenticatedUserThreadLocal.setUser(creator); } else { //this.log.info("Resetting authenticated user."); AuthenticatedUserThreadLocal.setUser(null); } /* save the blog post */ pageManager.saveContentEntity(blogPost, null); /* set attachments of this blog post */ /* we have to save the blog post before we can add the * attachments, because attachments need to be attached to * a content. */ Attachment[] a = new Attachment[attachments.size()]; a = (Attachment[]) attachments.toArray(a); for (int j = 0; j < a.length; j++) { InputStream is = (InputStream) attachmentsInputStreams.get(j); /* save the attachment */ try { /* set the creator of the attachment */ a[j].setCreatorName(creatorName); /* set the content of this attachment to the newly saved blog post */ a[j].setContent(blogPost); attachmentManager.saveAttachment(a[j], null, is); } catch (Exception e) { this.log.error("Could not save attachment: " + e.getMessage(), e); /* skip this attachment */ continue; } /* add the attachment to the blog post */ blogPost.addAttachment(a[j]); } }
From source file:com.seleniumtests.connectors.mails.ImapClient.java
/** * get list of all emails in folder//w w w. j a v a 2s.com * * @param folderName folder to read * @param firstMessageTime date from which we should get messages * @param firstMessageIndex index of the firste message to find * @throws MessagingException * @throws IOException */ @Override public List<Email> getEmails(String folderName, int firstMessageIndex, LocalDateTime firstMessageTime) throws MessagingException, IOException { if (folderName == null) { throw new MessagingException("folder ne doit pas tre vide"); } // Get folder Folder folder = store.getFolder(folderName); folder.open(Folder.READ_ONLY); // Get directory Message[] messages = folder.getMessages(); List<Message> preFilteredMessages = new ArrayList<>(); final LocalDateTime firstTime = firstMessageTime; // on filtre les message en fonction du mode de recherche if (searchMode == SearchMode.BY_INDEX || firstTime == null) { for (int i = firstMessageIndex, n = messages.length; i < n; i++) { preFilteredMessages.add(messages[i]); } } else { preFilteredMessages = Arrays.asList(folder.search(new SearchTerm() { private static final long serialVersionUID = 1L; @Override public boolean match(Message msg) { try { return !msg.getReceivedDate() .before(Date.from(firstTime.atZone(ZoneId.systemDefault()).toInstant())); } catch (MessagingException e) { return false; } } })); } List<Email> filteredEmails = new ArrayList<>(); lastMessageIndex = messages.length; for (Message message : preFilteredMessages) { String contentType = ""; try { contentType = message.getContentType(); } catch (MessagingException e) { MimeMessage msg = (MimeMessage) message; message = new MimeMessage(msg); contentType = message.getContentType(); } // decode content String messageContent = ""; List<String> attachments = new ArrayList<>(); if (contentType.toLowerCase().contains("text/html")) { messageContent += StringEscapeUtils.unescapeHtml4(message.getContent().toString()); } else if (contentType.toLowerCase().contains("multipart/")) { List<BodyPart> partList = getMessageParts((Multipart) message.getContent()); // store content in list for (BodyPart part : partList) { String partContentType = part.getContentType().toLowerCase(); if (partContentType.contains("text/html")) { messageContent = messageContent .concat(StringEscapeUtils.unescapeHtml4(part.getContent().toString())); } else if (partContentType.contains("text/") && !partContentType.contains("vcard")) { messageContent = messageContent.concat((String) part.getContent().toString()); } else if (partContentType.contains("image") || partContentType.contains("application/") || partContentType.contains("text/x-vcard")) { if (part.getFileName() != null) { attachments.add(part.getFileName()); } else { attachments.add(part.getDescription()); } } else { logger.debug("type: " + part.getContentType()); } } } // create a new email filteredEmails.add(new Email(message.getSubject(), messageContent, "", message.getReceivedDate().toInstant().atZone(ZoneId.systemDefault()).toLocalDateTime(), attachments)); } folder.close(false); return filteredEmails; }