List of usage examples for javax.mail.internet MimeMessage getFrom
@Override public Address[] getFrom() throws MessagingException
From source file:com.zimbra.cs.mailclient.smtp.SmtpConnection.java
private String getSender(MimeMessage msg) throws MessagingException { String sender = null;// ww w . j ava 2s. c o m if (msg instanceof SMTPMessage) { sender = ((SMTPMessage) msg).getEnvelopeFrom(); if (sender != null && sender.length() >= 2 && sender.startsWith("<") && sender.endsWith(">")) { // Strip brackets. sender = sender.substring(1, sender.length() - 1); } } if (sender == null) { Address[] fromAddrs = msg.getFrom(); if (fromAddrs != null && fromAddrs.length > 0) { sender = getAddress(fromAddrs[0]); } } return sender; }
From source file:mitm.common.pdf.MessagePDFBuilder.java
public void buildPDF(MimeMessage message, String replyURL, OutputStream pdfStream) throws DocumentException, MessagingException, IOException { Document document = createDocument(); PdfWriter pdfWriter = createPdfWriter(document, pdfStream); document.open();// ww w . j a va 2 s . co m String[] froms = null; try { froms = EmailAddressUtils.addressesToStrings(message.getFrom(), true /* mime decode */); } catch (MessagingException e) { logger.warn("From address is not a valid email address."); } if (froms != null) { for (String from : froms) { document.addAuthor(from); } } String subject = null; try { subject = message.getSubject(); } catch (MessagingException e) { logger.error("Error getting subject.", e); } if (subject != null) { document.addSubject(subject); document.addTitle(subject); } String[] tos = null; try { tos = EmailAddressUtils.addressesToStrings(message.getRecipients(RecipientType.TO), true /* mime decode */); } catch (MessagingException e) { logger.warn("To is not a valid email address."); } String[] ccs = null; try { ccs = EmailAddressUtils.addressesToStrings(message.getRecipients(RecipientType.CC), true /* mime decode */); } catch (MessagingException e) { logger.warn("CC is not a valid email address."); } Date sentDate = null; try { sentDate = message.getSentDate(); } catch (MessagingException e) { logger.error("Error getting sent date.", e); } Collection<Part> attachments = new LinkedList<Part>(); String body = BodyPartUtils.getPlainBodyAndAttachments(message, attachments); attachments = preprocessAttachments(attachments); if (body == null) { body = MISSING_BODY; } /* * PDF does not have tab support so we convert tabs to spaces */ body = StringReplaceUtils.replaceTabsWithSpaces(body, tabWidth); PdfPTable headerTable = new PdfPTable(2); headerTable.setHorizontalAlignment(Element.ALIGN_LEFT); headerTable.setWidthPercentage(100); headerTable.setWidths(new int[] { 1, 6 }); headerTable.getDefaultCell().setBorder(Rectangle.NO_BORDER); Font headerFont = createHeaderFont(); FontSelector headerFontSelector = createHeaderFontSelector(); PdfPCell cell = new PdfPCell(new Paragraph("From:", headerFont)); cell.setBorder(Rectangle.NO_BORDER); cell.setHorizontalAlignment(Element.ALIGN_RIGHT); headerTable.addCell(cell); String decodedFroms = StringUtils.defaultString(StringUtils.join(froms, ", ")); headerTable.addCell(headerFontSelector.process(decodedFroms)); cell = new PdfPCell(new Paragraph("To:", headerFont)); cell.setBorder(Rectangle.NO_BORDER); cell.setHorizontalAlignment(Element.ALIGN_RIGHT); headerTable.addCell(cell); headerTable.addCell(headerFontSelector.process(StringUtils.defaultString(StringUtils.join(tos, ", ")))); cell = new PdfPCell(new Paragraph("CC:", headerFont)); cell.setBorder(Rectangle.NO_BORDER); cell.setHorizontalAlignment(Element.ALIGN_RIGHT); headerTable.addCell(cell); headerTable.addCell(headerFontSelector.process(StringUtils.defaultString(StringUtils.join(ccs, ", ")))); cell = new PdfPCell(new Paragraph("Subject:", headerFont)); cell.setBorder(Rectangle.NO_BORDER); cell.setHorizontalAlignment(Element.ALIGN_RIGHT); headerTable.addCell(cell); headerTable.addCell(headerFontSelector.process(StringUtils.defaultString(subject))); cell = new PdfPCell(new Paragraph("Date:", headerFont)); cell.setBorder(Rectangle.NO_BORDER); cell.setHorizontalAlignment(Element.ALIGN_RIGHT); headerTable.addCell(cell); headerTable.addCell(ObjectUtils.toString(sentDate)); cell = new PdfPCell(new Paragraph("Attachments:", headerFont)); cell.setBorder(Rectangle.NO_BORDER); cell.setHorizontalAlignment(Element.ALIGN_RIGHT); headerTable.addCell(cell); headerTable .addCell(headerFontSelector.process(StringUtils.defaultString(getAttachmentHeader(attachments)))); document.add(headerTable); if (replyURL != null) { addReplyLink(document, replyURL); } /* * Body table will contain the body of the message */ PdfPTable bodyTable = new PdfPTable(1); bodyTable.setWidthPercentage(100f); bodyTable.setSplitLate(false); bodyTable.setSpacingBefore(15f); bodyTable.setHorizontalAlignment(Element.ALIGN_LEFT); addBodyAndAttachments(pdfWriter, document, bodyTable, body, attachments); Phrase footer = new Phrase(FOOTER_TEXT); PdfContentByte cb = pdfWriter.getDirectContent(); ColumnText.showTextAligned(cb, Element.ALIGN_RIGHT, footer, document.right(), document.bottom(), 0); document.close(); }
From source file:mitm.application.djigzo.james.mailets.SMIMEEncryptTest.java
@Test public void testProtectedHeadersStatic() throws Exception { MockMailetConfig mailetConfig = new MockMailetConfig("test"); SMIMEEncrypt mailet = new SMIMEEncrypt(); mailetConfig.setInitParameter("retainMessageID", "false"); mailetConfig.setInitParameter("protectedHeader", "from, message-id"); mailet.init(mailetConfig);/* www .j a v a 2 s .c o m*/ Mail mail = new MockMail(); MimeMessage message = MailUtils.loadMessage(new File(testBase, "mail/simple-text-message-with-id.eml")); assertEquals("<123456>", message.getMessageID()); mail.setMessage(message); Set<MailAddress> recipients = new HashSet<MailAddress>(); recipients.add(new MailAddress("test@example.com")); mail.setRecipients(recipients); DjigzoMailAttributes mailAttributes = new DjigzoMailAttributesImpl(mail); mailAttributes.setCertificates(certificates); mailet.service(mail); MimeMessage encrypted = mail.getMessage(); /* * Change from to see whether it was protected */ encrypted.setFrom(new InternetAddress("changed@changed.example.com")); MailUtils.validateMessage(encrypted); assertFalse("<123456>".equals(encrypted.getMessageID())); assertEquals(SMIMEHeader.ENCRYPTED_CONTENT_TYPE, encrypted.getContentType()); KeyStoreKeyProvider keyStore = new KeyStoreKeyProvider( loadKeyStore(new File("test/resources/testdata/keys/testCertificates.p12"), "test"), "test"); SMIMEInspector inspector = new SMIMEInspectorImpl(encrypted, keyStore, "BC"); assertEquals(SMIMEType.ENCRYPTED, inspector.getSMIMEType()); /* * now decrypt and check whether message-id and from was protected */ MimeMessage decrypted = inspector.getContentAsMimeMessage(); inspector = new SMIMEInspectorImpl(decrypted, keyStore, "BC"); assertEquals(SMIMEType.NONE, inspector.getSMIMEType()); assertTrue("<123456>".equals(decrypted.getMessageID())); assertEquals("test@example.com", StringUtils.join(decrypted.getFrom())); }
From source file:mitm.application.djigzo.james.mailets.SMIMEEncryptTest.java
@Test public void testProtectedHeadersMailAttributes() throws Exception { MockMailetConfig mailetConfig = new MockMailetConfig("test"); SMIMEEncrypt mailet = new SMIMEEncrypt(); mailetConfig.setInitParameter("retainMessageID", "false"); mailet.init(mailetConfig);// w w w . j av a2s . c o m Mail mail = new MockMail(); DjigzoMailAttributes mailAttributes = new DjigzoMailAttributesImpl(mail); /* * set protected headers in the mail attributes */ mailAttributes.setProtectedHeaders(new String[] { "from", "message-id" }); MimeMessage message = MailUtils.loadMessage(new File(testBase, "mail/simple-text-message-with-id.eml")); assertEquals("<123456>", message.getMessageID()); mail.setMessage(message); Set<MailAddress> recipients = new HashSet<MailAddress>(); recipients.add(new MailAddress("test@example.com")); mail.setRecipients(recipients); mailAttributes.setCertificates(certificates); mailet.service(mail); MimeMessage encrypted = mail.getMessage(); /* * Change from to see whether it was protected */ encrypted.setFrom(new InternetAddress("changed@changed.example.com")); MailUtils.validateMessage(encrypted); assertFalse("<123456>".equals(encrypted.getMessageID())); assertEquals(SMIMEHeader.ENCRYPTED_CONTENT_TYPE, encrypted.getContentType()); KeyStoreKeyProvider keyStore = new KeyStoreKeyProvider( loadKeyStore(new File("test/resources/testdata/keys/testCertificates.p12"), "test"), "test"); SMIMEInspector inspector = new SMIMEInspectorImpl(encrypted, keyStore, "BC"); assertEquals(SMIMEType.ENCRYPTED, inspector.getSMIMEType()); /* * now decrypt and check whether message-id and from was protected */ MimeMessage decrypted = inspector.getContentAsMimeMessage(); inspector = new SMIMEInspectorImpl(decrypted, keyStore, "BC"); assertEquals(SMIMEType.NONE, inspector.getSMIMEType()); assertTrue("<123456>".equals(decrypted.getMessageID())); assertEquals("test@example.com", StringUtils.join(decrypted.getFrom())); }
From source file:com.duroty.service.Mailet.java
/** * DOCUMENT ME!/*from www . java 2 s.co m*/ * * @param message DOCUMENT ME! * @param exception DOCUMENT ME! */ private void sendError(MimeMessage message, Throwable exception) { if (true) { return; } StringWriter sw = null; PrintWriter writer = null; javax.mail.Session msession = null; try { msession = (javax.mail.Session) ctx.lookup(smtpSessionFactory); InternetAddress sender = new InternetAddress("postmaster@duroty.com", "Postmaster"); InternetAddress errorTo = new InternetAddress(message.getFrom()[0].toString()); sw = new StringWriter(); writer = new PrintWriter(sw); if (exception != null) { exception.printStackTrace(writer); } //Create the message to forward MimeMessage forward = MessageUtilities.createNewMessage(sender, new Address[] { errorTo }, "[ERROR: ", " ]", sw.toString(), message, msession); //MimeMessage newMessage = MessageUtilities.createForward(sender, forwardTo, message, this.mailSession); Thread thread = new Thread(new SendMessageThread(forward)); thread.start(); System.gc(); } catch (Exception e) { DLog.log(DLog.ERROR, this.getClass(), "Impossible sent error: " + e.getMessage()); } catch (java.lang.OutOfMemoryError ex) { System.gc(); DLog.log(DLog.ERROR, this.getClass(), "Impossible sent error: " + ex.getMessage()); } catch (Throwable e) { DLog.log(DLog.ERROR, this.getClass(), "Impossible sent error: " + e.getMessage()); } }
From source file:org.sakaiproject.james.SakaiMailet.java
/** * Process incoming mail./*from w ww. ja v a 2 s .co m*/ * * @param mail * ... */ public void service(Mail mail) throws MessagingException { // get the postmaster user User postmaster = null; try { postmaster = userDirectoryService.getUser(POSTMASTER); } catch (UserNotDefinedException e) { M_log.warn("service(): no postmaster, incoming mail will not be processed until a postmaster user (id=" + POSTMASTER + ") exists in this Sakai instance"); mail.setState(Mail.GHOST); return; } try { // set the current user to postmaster Session s = sessionManager.getCurrentSession(); if (s != null) { s.setUserId(postmaster.getId()); } else { M_log.warn( "service - no SessionManager.getCurrentSession, cannot set to postmaser user, attempting to use the current user (" + sessionManager.getCurrentSessionUserId() + ") and session (" + sessionManager.getCurrentSession().getId() + ")"); } MimeMessage msg = mail.getMessage(); String id = msg.getMessageID(); Address[] fromAddresses = msg.getFrom(); String from = null; String fromAddr = null; if ((fromAddresses != null) && (fromAddresses.length == 1)) { from = fromAddresses[0].toString(); if (fromAddresses[0] instanceof InternetAddress) { fromAddr = ((InternetAddress) (fromAddresses[0])).getAddress(); } } else { from = mail.getSender().toString(); fromAddr = mail.getSender().toInternetAddress().getAddress(); } Collection<MailAddress> to = mail.getRecipients(); Date sent = msg.getSentDate(); String subject = StringUtils.trimToNull(msg.getSubject()); Enumeration<String> headers = msg.getAllHeaderLines(); List<String> mailHeaders = new Vector<String>(); while (headers.hasMoreElements()) { String line = (String) headers.nextElement(); // check if string starts with "Content-Type", ignoring case if (line.regionMatches(true, 0, MailArchiveService.HEADER_CONTENT_TYPE, 0, MailArchiveService.HEADER_CONTENT_TYPE.length())) { String contentType = line.substring(0, MailArchiveService.HEADER_CONTENT_TYPE.length()); mailHeaders.add(line.replaceAll(contentType, MailArchiveService.HEADER_OUTER_CONTENT_TYPE)); } // don't copy null subject lines. we'll add a real one below if (!(line.regionMatches(true, 0, MailArchiveService.HEADER_SUBJECT, 0, MailArchiveService.HEADER_SUBJECT.length()) && subject == null)) mailHeaders.add(line); } //Add headers for a null subject, keep null in DB if (subject == null) { mailHeaders.add(MailArchiveService.HEADER_SUBJECT + ": <" + rb.getString("err_no_subject") + ">"); } if (M_log.isDebugEnabled()) { M_log.debug(id + " : mail: from:" + from + " sent: " + timeService.newTime(sent.getTime()).toStringLocalFull() + " subject: " + subject); } // process for each recipient Iterator<MailAddress> it = to.iterator(); while (it.hasNext()) { String mailId = null; try { MailAddress recipient = (MailAddress) it.next(); if (M_log.isDebugEnabled()) { M_log.debug(id + " : checking to: " + recipient); } // the recipient's mail id mailId = recipient.getUser(); // eat the no-reply if ("no-reply".equalsIgnoreCase(mailId)) { mail.setState(Mail.GHOST); if (M_log.isInfoEnabled()) { M_log.info("Incoming message mailId (" + mailId + ") set to no-reply, mail processing cancelled"); } /* NOTE: this doesn't make a lot of sense to me, once the mail is ghosted * then it won't be processed anymore so continuing is kind of a waste of time, * shouldn't this just break instead? */ continue; } // find the channel (mailbox) that this is addressed to // for now, check only for it being a site or alias to a site. // %%% - add user and other later -ggolden MailArchiveChannel channel = null; // first, assume the mailId is a site id String channelRef = MailArchiveService.channelReference(mailId, SiteService.MAIN_CONTAINER); try { channel = MailArchiveService.getMailArchiveChannel(channelRef); if (M_log.isDebugEnabled()) { M_log.debug( "Incoming message mailId (" + mailId + ") IS a valid site channel reference"); } } catch (IdUnusedException goOn) { // INDICATES the incoming message is NOT for a currently valid site if (M_log.isDebugEnabled()) { M_log.debug("Incoming message mailId (" + mailId + ") is NOT a valid site channel reference, will attempt more matches"); } } catch (PermissionException e) { // INDICATES the channel is valid but the user has no permission to access it // This generally should not happen because the current user should be the postmaster M_log.warn( "mailarchive failure: message processing cancelled: PermissionException with channelRef (" + channelRef + ") - user not allowed to get this mail archive channel: (id=" + id + ") (mailId=" + mailId + ") (user=" + sessionManager.getCurrentSessionUserId() + ") (session=" + sessionManager.getCurrentSession().getId() + "): " + e, e); // BOUNCE REPLY - send a message back to the user to let them know their email failed String errMsg = rb.getString("err_not_member") + "\n\n"; String mailSupport = StringUtils .trimToNull(serverConfigurationService.getString("mail.support")); if (mailSupport != null) { errMsg += (String) rb.getFormattedMessage("err_questions", new Object[] { mailSupport }) + "\n"; } mail.setErrorMessage(errMsg); mail.setState(userNotAllowedToPostProcessor); continue; } // next, if not a site, see if it's an alias to a site or channel if (channel == null) { // if not an alias, it will throw the IdUnusedException caught below Reference ref = entityManager.newReference(aliasService.getTarget(mailId)); if (ref.getType().equals(SiteService.APPLICATION_ID)) { // ref is a site // now we have a site reference, try for it's channel channelRef = MailArchiveService.channelReference(ref.getId(), SiteService.MAIN_CONTAINER); if (M_log.isDebugEnabled()) { M_log.debug("Incoming message mailId (" + mailId + ") IS a valid site reference (" + ref.getId() + ")"); } } else if (ref.getType().equals(MailArchiveService.APPLICATION_ID)) { // ref is a channel channelRef = ref.getReference(); if (M_log.isDebugEnabled()) { M_log.debug("Incoming message mailId (" + mailId + ") IS a valid channel reference (" + ref.getId() + ")"); } } else { // ref cannot be be matched if (M_log.isInfoEnabled()) { M_log.info(id + " : mail rejected: unknown address: " + mailId + " : mailId (" + mailId + ") does NOT match site, alias, or other current channel"); } if (M_log.isDebugEnabled()) { M_log.debug("Incoming message mailId (" + mailId + ") is NOT a valid does NOT match site, alias, or other current channel reference (" + ref.getId() + "), message rejected"); } throw new IdUnusedException(mailId); } // if there's no channel for this site, it will throw the IdUnusedException caught below try { channel = MailArchiveService.getMailArchiveChannel(channelRef); } catch (PermissionException e) { // INDICATES the channel is valid but the user has no permission to access it // This generally should not happen because the current user should be the postmaster M_log.warn( "mailarchive failure: message processing cancelled: PermissionException with channelRef (" + channelRef + ") - user not allowed to get this mail archive channel: (id=" + id + ") (mailId=" + mailId + ") (user=" + sessionManager.getCurrentSessionUserId() + ") (session=" + sessionManager.getCurrentSession().getId() + "): " + e, e); // BOUNCE REPLY - send a message back to the user to let them know their email failed String errMsg = rb.getString("err_not_member") + "\n\n"; String mailSupport = StringUtils .trimToNull(serverConfigurationService.getString("mail.support")); if (mailSupport != null) { errMsg += (String) rb.getFormattedMessage("err_questions", new Object[] { mailSupport }) + "\n"; } mail.setErrorMessage(errMsg); mail.setState(userNotAllowedToPostProcessor); continue; } if (M_log.isDebugEnabled()) { M_log.debug("Incoming message mailId (" + mailId + ") IS a valid channel (" + channelRef + "), found channel: " + channel); } } if (channel == null) { if (M_log.isDebugEnabled()) { M_log.debug("Incoming message mailId (" + mailId + "), channelRef (" + channelRef + ") could not be resolved and is null: " + channel); } // this should never happen but it is here just in case throw new IdUnusedException(mailId); } // skip disabled channels if (!channel.getEnabled()) { // INDICATES that the channel is NOT currently enabled so no messages can be received if (from.startsWith(POSTMASTER)) { mail.setState(Mail.GHOST); } else { // BOUNCE REPLY - send a message back to the user to let them know their email failed String errMsg = rb.getString("err_email_off") + "\n\n"; String mailSupport = StringUtils .trimToNull(serverConfigurationService.getString("mail.support")); if (mailSupport != null) { errMsg += (String) rb.getFormattedMessage("err_questions", new Object[] { mailSupport }) + "\n"; } mail.setErrorMessage(errMsg); mail.setState(courseMailArchiveDisabledProcessor); } if (M_log.isInfoEnabled()) { M_log.info( id + " : mail rejected: channel (" + channelRef + ") not enabled: " + mailId); } continue; } // for non-open channels, make sure the from is a member if (!channel.getOpen()) { // see if our fromAddr is the email address of any of the users who are permitted to add messages to the channel. if (!fromValidUser(fromAddr, channel)) { // INDICATES user is not allowed to send messages to this group if (M_log.isInfoEnabled()) { M_log.info(id + " : mail rejected: from: " + fromAddr + " not authorized for site: " + mailId + " and channel (" + channelRef + ")"); } // BOUNCE REPLY - send a message back to the user to let them know their email failed String errMsg = rb.getString("err_not_member") + "\n\n"; String mailSupport = StringUtils .trimToNull(serverConfigurationService.getString("mail.support")); if (mailSupport != null) { errMsg += (String) rb.getFormattedMessage("err_questions", new Object[] { mailSupport }) + "\n"; } mail.setErrorMessage(errMsg); mail.setState(userNotAllowedToPostProcessor); continue; } } // prepare the message StringBuilder bodyBuf[] = new StringBuilder[2]; bodyBuf[0] = new StringBuilder(); bodyBuf[1] = new StringBuilder(); List<Reference> attachments = entityManager.newReferenceList(); String siteId = null; if (siteService.siteExists(channel.getContext())) { siteId = channel.getContext(); } try { StringBuilder bodyContentType = new StringBuilder(); parseParts(siteId, msg, id, bodyBuf, bodyContentType, attachments, Integer.valueOf(-1)); if (bodyContentType.length() > 0) { // save the content type of the message body - which may be different from the // overall MIME type of the message (multipart, etc) mailHeaders.add(MailArchiveService.HEADER_INNER_CONTENT_TYPE + ": " + bodyContentType); } } catch (MessagingException e) { // NOTE: if this happens it just means we don't get the extra header, not the end of the world //e.printStackTrace(); M_log.warn("MessagingException: service(): msg.getContent() threw: " + e, e); } catch (IOException e) { // NOTE: if this happens it just means we don't get the extra header, not the end of the world //e.printStackTrace(); M_log.warn("IOException: service(): msg.getContent() threw: " + e, e); } mailHeaders.add("List-Id: <" + channel.getId() + "." + channel.getContext() + "." + serverConfigurationService.getServerName() + ">"); // post the message to the group's channel String body[] = new String[2]; body[0] = bodyBuf[0].toString(); // plain/text body[1] = bodyBuf[1].toString(); // html/text try { if (channel.getReplyToList()) { List<String> modifiedHeaders = new Vector<String>(); for (String header : (List<String>) mailHeaders) { if (header != null && !header.startsWith("Reply-To:")) { modifiedHeaders.add(header); } } // Note: can't use recipient, since it's host may be configured as mailId@myhost.james String mailHost = serverConfigurationService.getServerName(); if (mailHost == null || mailHost.trim().equals("")) mailHost = mail.getRemoteHost(); MailAddress replyTo = new MailAddress(mailId, mailHost); if (M_log.isDebugEnabled()) { M_log.debug("Set Reply-To address to " + replyTo.toString()); } modifiedHeaders.add("Reply-To: " + replyTo.toString()); // post the message to the group's channel channel.addMailArchiveMessage(subject, from.toString(), timeService.newTime(sent.getTime()), modifiedHeaders, attachments, body); } else { // post the message to the group's channel channel.addMailArchiveMessage(subject, from.toString(), timeService.newTime(sent.getTime()), mailHeaders, attachments, body); } } catch (PermissionException pe) { // INDICATES that the current user does not have permission to add or get the mail archive message from the current channel // This generally should not happen because the current user should be the postmaster M_log.warn("mailarchive PermissionException message service failure: (id=" + id + ") (mailId=" + mailId + ") : " + pe, pe); mail.setState(Mail.GHOST); // ghost out the message because this should not happen } if (M_log.isDebugEnabled()) { M_log.debug(id + " : delivered to:" + mailId); } // all is happy - ghost the message to stop further processing mail.setState(Mail.GHOST); } catch (IdUnusedException goOn) { // INDICATES that the channelReference found above was actually invalid OR that no channel reference could be identified // if this is to the postmaster, and there's no site, channel or alias for the postmaster, then quietly eat the message if (POSTMASTER.equals(mailId) || from.startsWith(POSTMASTER + "@")) { mail.setState(Mail.GHOST); continue; } // BOUNCE REPLY - send a message back to the user to let them know their email failed if (M_log.isInfoEnabled()) { M_log.info("mailarchive invalid or unusable channel reference (" + mailId + "): " + id + " : mail rejected: " + goOn.toString()); } String errMsg = rb.getString("err_addr_unknown") + "\n\n"; String mailSupport = StringUtils .trimToNull(serverConfigurationService.getString("mail.support")); if (mailSupport != null) { errMsg += (String) rb.getFormattedMessage("err_questions", new Object[] { mailSupport }) + "\n"; } mail.setErrorMessage(errMsg); mail.setState(courseMailArchiveNotExistsProcessor); } catch (Exception ex) { // INDICATES that some general exception has occurred which we did not expect // This definitely should NOT happen M_log.error("mailarchive General message service exception: (id=" + id + ") (mailId=" + mailId + ") : " + ex, ex); mail.setState(Mail.GHOST); // ghost the message to stop it from being further processed } } } finally { // clear out any current current bindings threadLocalManager.clear(); } }
From source file:com.duroty.service.Mailet.java
/** * DOCUMENT ME!//from w ww .j av a 2s . c o m * * @param hfactory DOCUMENT ME! * @param username DOCUMENT ME! * @param mime DOCUMENT ME! */ private void parseContacts(Session hsession, Users user, MimeMessage mime, String box) { try { Address[] addresses = null; Date sentDate = null; Date receivedDate = null; if (box.equals("SENT")) { addresses = mime.getAllRecipients(); sentDate = mime.getSentDate(); if (sentDate == null) { sentDate = new Date(); } } else { addresses = mime.getFrom(); receivedDate = mime.getReceivedDate(); if (receivedDate == null) { receivedDate = new Date(); } } if ((addresses != null) && (addresses.length > 0)) { String name = null; String email = null; for (int i = 0; i < addresses.length; i++) { if (addresses[i] instanceof InternetAddress) { InternetAddress xinet = (InternetAddress) addresses[i]; name = xinet.getPersonal(); if ((name != null) && (name.length() > 49)) { name = name.substring(0, 49); } email = xinet.getAddress(); } else { email = addresses[i].toString(); } Criteria crit1 = hsession.createCriteria(Contact.class); crit1.add(Restrictions.eq("users", user)); crit1.add(Restrictions.eq("conEmail", email)); Contact contact = (Contact) crit1.uniqueResult(); if (contact != null) { if (receivedDate != null) { contact.setConReceivedDate(receivedDate); } if (sentDate != null) { contact.setConSentDate(sentDate); } int freq = contact.getConCount(); contact.setConCount(freq + 1); if (!StringUtils.isBlank(name)) { name = name.replaceAll(",", " "); name = name.replaceAll(";", " "); contact.setConName(name); } hsession.update(contact); } else { contact = new Contact(); contact.setConEmail(email); contact.setConName(name); contact.setConReceivedDate(receivedDate); contact.setConSentDate(sentDate); contact.setConCount(new Integer(1)); contact.setUsers(user); hsession.save(contact); } hsession.flush(); try { if ((contact.getConSentDate() != null) && (contact.getConReceivedDate() != null)) { Criteria crit2 = hsession.createCriteria(Identity.class); crit2.add(Restrictions.eq("ideEmail", email)); crit2.add(Restrictions.eq("ideActive", new Boolean(true))); List list = crit2.list(); if (list != null) { Iterator scroll = list.iterator(); while (scroll.hasNext()) { Identity identity = (Identity) scroll.next(); Users buddy = identity.getUsers(); if ((buddy != null) && (user.getUseIdint() != buddy.getUseIdint())) { Criteria auxCrit = hsession.createCriteria(BuddyList.class); auxCrit.add(Restrictions.eq("usersByBuliOwnerIdint", user)); auxCrit.add(Restrictions.eq("usersByBuliBuddyIdint", buddy)); BuddyList buddyList = (BuddyList) auxCrit.uniqueResult(); if (buddyList != null) { buddyList.setBuliActive(true); buddyList.setBuliLastDate(new Date()); hsession.update(buddyList); } else { buddyList = new BuddyList(); buddyList.setBuliActive(true); buddyList.setBuliLastDate(new Date()); buddyList.setUsersByBuliBuddyIdint(buddy); buddyList.setUsersByBuliOwnerIdint(user); hsession.save(buddyList); } } } } hsession.flush(); } } catch (Exception e) { } } } } catch (Exception e) { } finally { } }
From source file:com.studiostorti.ZimbraFlowHandler.java
@Override public void handleRequest(ZimbraContext zimbraContext, SoapResponse soapResponse, ZimbraExceptionContainer zimbraExceptionContainer) { String requesterId = zimbraContext.getAuthenticatedAccontId(); Mailbox mailbox = mMailboxManager.getMailboxByAccountId(requesterId); Account account = mProvisioning.getAccountById(requesterId); Map<String, String> args = new HashMap<String, String>(); if (account == null) { soapResponse.setValue("reply", "KONon e' stato possibile trovare l'account : " + requesterId); return;/*from w w w. j a v a2s . c o m*/ } OperationContext octxt = new OperationContext(account); String msgId = zimbraContext.getParameter("id", ""); String namespace = zimbraContext.getParameter("namespace", ""); String url = zimbraContext.getParameter("url", ""); String user = account.getName(); ZimbraLog.extensions .info("Azione ZimbraFlow richiesta da '" + user + "' per il messaggio: '" + msgId + "'"); args.put("cUserEmail", user); Message item; if (!msgId.contains(":")) { try { item = mailbox.getMessageById(octxt, Integer.parseInt(msgId)); } catch (Exception e) { soapResponse.setValue("reply", "KONon e' stato possibile recuperare il messaggio (" + msgId + "): " + e.getMessage()); return; } ZimbraLog.mailbox.info("ZimbraFlow mail id : " + msgId); args.put("cEmailUniqueID", account.getId() + ":" + msgId); } else { ZimbraLog.mailbox.info("ZimbraFlow il messaggio e' una cartella condivisa"); String accountId = msgId.substring(0, msgId.indexOf(':')); String itemId = msgId.substring(msgId.indexOf(':') + 1); try { Mailbox ownerMailbox = mMailboxManager.getMailboxByAccountId(accountId); item = ownerMailbox.getMessageById(octxt, Integer.parseInt(itemId)); } catch (Exception e) { soapResponse.setValue("reply", "KONon e' stato possibile recuperare il messaggio (" + msgId + "): " + e.getMessage()); return; } args.put("cEmailUniqueID", msgId); } if (item == null) { soapResponse.setValue("reply", "KONon e' stato possibile recuperare il messaggio (" + msgId + "."); return; } MimeMessage mimeMessage = null; try { mimeMessage = item.getMimeMessage(); args.put("cEmailMessageID", mimeMessage.getMessageID()); } catch (MessagingException e) { ZimbraLog.mailbox.warn("ZimbraFlow errore cEmailMessageID: " + e.getMessage()); } byte[] mime = item.getContent(); args.put("StreamBase64", Base64.encodeBase64String(mime)); String subject; subject = item.getSubject(); args.put("cSubject", subject); String body; try { body = getText(mimeMessage); } catch (MessagingException e) { ZimbraLog.mailbox.warn("ZimbraFlow errore cBody: " + e.getMessage()); body = ""; } catch (IOException e) { ZimbraLog.mailbox.warn("ZimbraFlow errore cBody: " + e.getMessage()); body = ""; } args.put("cBody", body); try { Address from = mimeMessage.getFrom()[0]; args.put("cFrom", ((InternetAddress) from).getAddress()); } catch (NullPointerException ne) { ZimbraLog.mailbox.warn("ZimbraFlow errore cFrom: " + ne.getMessage()); args.put("cFrom", ""); } catch (MessagingException e) { ZimbraLog.mailbox.warn("ZimbraFlow errore cFrom: " + e.getMessage()); args.put("cFrom", ""); } try { Address[] toRecipients = mimeMessage.getRecipients(javax.mail.Message.RecipientType.TO); String toString = ""; for (Address to : toRecipients) { toString += ((InternetAddress) to).getAddress() + ","; } if (toString.length() > 0) args.put("cTO", toString.substring(0, toString.length() - 1)); else args.put("cTO", toString); } catch (MessagingException ignored) { } catch (NullPointerException ne) { ZimbraLog.mailbox.warn("ZimbraFlow errore cTo: " + ne.getMessage()); args.put("cTO", ""); } try { Address[] ccRecipients = mimeMessage.getRecipients(javax.mail.Message.RecipientType.CC); String ccString = ""; if (ccRecipients != null) { for (Address cc : ccRecipients) { ccString += ((InternetAddress) cc).getAddress() + ","; } } if (ccString.length() > 0) args.put("cCC", ccString.substring(0, ccString.length() - 1)); else args.put("cCC", ccString); } catch (MessagingException ignored) { } catch (NullPointerException ne) { ZimbraLog.mailbox.warn("ZimbraFlow errore cCC: " + ne.getMessage()); args.put("cCC", ""); } try { Address[] bccRecipients = mimeMessage.getRecipients(javax.mail.Message.RecipientType.BCC); String bccString = ""; if (bccRecipients != null) { for (Address bcc : bccRecipients) { bccString += ((InternetAddress) bcc).getAddress() + ","; } } if (bccString.length() > 0) args.put("cCCN", bccString.substring(0, bccString.length() - 1)); else args.put("cCCN", bccString); } catch (MessagingException ignored) { } catch (NullPointerException ne) { ZimbraLog.mailbox.warn("ZimbraFlow errore cCCN: " + ne.getMessage()); args.put("cCCN", ""); } SimpleDateFormat dateFormat = new SimpleDateFormat("YYYY-MM-dd hh:mm:ss"); long date = item.getDate(); args.put("cDateTime", dateFormat.format(new Date(date))); if (args.get("cDateTime") == null || args.get("cUserEmail") == null || args.get("StreamBase64") == null) { String message = "KONon sono stati trovati tutti i campi obbligatori:"; if (args.get("cDateTime") == null) message += "\nManca il campo cDateTime"; else if (args.get("cUserEmail") == null) message += "\nManca il campo cUserEmail"; else if (args.get("StreamBase64") == null) message += "\nManca il campo StreamBase64"; soapResponse.setValue("reply", message); return; } SOAPClient soapClient = new SOAPClient(url, namespace); try { String res = soapClient.sendRequest(args); soapResponse.setValue("reply", res); } catch (SOAPException e) { ZimbraLog.mailbox.error("ZimbraFlow SOAP call exception: " + e.getMessage()); soapResponse.setValue("reply", "KO" + e.getMessage()); } }
From source file:org.alfresco.repo.invitation.AbstractInvitationServiceImplTest.java
/** * Test nominated user - new user/*from ww w. j a v a2 s.c om*/ * * @throws Exception */ public void testNominatedInvitationNewUser() throws Exception { Calendar calendar = Calendar.getInstance(); calendar.add(Calendar.SECOND, -1); Date startDate = calendar.getTime(); String inviteeFirstName = PERSON_FIRSTNAME; String inviteeLastName = PERSON_LASTNAME; String inviteeEmail = "123@alfrescotesting.com"; String inviteeUserName = null; Invitation.ResourceType resourceType = Invitation.ResourceType.WEB_SITE; String resourceName = SITE_SHORT_NAME_INVITE; String inviteeRole = SiteModel.SITE_COLLABORATOR; String serverPath = "wibble"; String acceptUrl = "froob"; String rejectUrl = "marshmallow"; this.authenticationComponent.setCurrentUser(USER_MANAGER); NominatedInvitation nominatedInvitation = invitationService.inviteNominated(inviteeFirstName, inviteeLastName, inviteeEmail, resourceType, resourceName, inviteeRole, serverPath, acceptUrl, rejectUrl); assertNotNull("nominated invitation is null", nominatedInvitation); String inviteId = nominatedInvitation.getInviteId(); assertEquals("first name wrong", inviteeFirstName, nominatedInvitation.getInviteeFirstName()); assertEquals("last name wrong", inviteeLastName, nominatedInvitation.getInviteeLastName()); assertEquals("email name wrong", inviteeEmail, nominatedInvitation.getInviteeEmail()); // Generated User Name should be returned inviteeUserName = nominatedInvitation.getInviteeUserName(); assertNotNull("generated user name is null", inviteeUserName); // sentInviteDate should be set to today { Date sentDate = nominatedInvitation.getSentInviteDate(); assertTrue("sentDate wrong - too early. Start Date: " + startDate + "\nSent Date: " + sentDate, sentDate.after(startDate)); assertTrue("sentDate wrong - too lateStart Date: " + startDate + "\nSent Date: " + sentDate, sentDate.before(new Date(new Date().getTime() + 1))); } assertEquals("resource type name wrong", resourceType, nominatedInvitation.getResourceType()); assertEquals("resource name wrong", resourceName, nominatedInvitation.getResourceName()); assertEquals("role name wrong", inviteeRole, nominatedInvitation.getRoleName()); assertEquals("server path wrong", serverPath, nominatedInvitation.getServerPath()); assertEquals("accept URL wrong", acceptUrl, nominatedInvitation.getAcceptUrl()); assertEquals("reject URL wrong", rejectUrl, nominatedInvitation.getRejectUrl()); /** * Now we have an invitation get it and check the details have been * returned correctly. */ { NominatedInvitation invitation = (NominatedInvitation) invitationService.getInvitation(inviteId); assertNotNull("invitation is null", invitation); assertEquals("invite id wrong", inviteId, invitation.getInviteId()); assertEquals("first name wrong", inviteeFirstName, invitation.getInviteeFirstName()); assertEquals("last name wrong", inviteeLastName, invitation.getInviteeLastName()); assertEquals("user name wrong", inviteeUserName, invitation.getInviteeUserName()); assertEquals("resource type name wrong", resourceType, invitation.getResourceType()); assertEquals("resource name wrong", resourceName, invitation.getResourceName()); assertEquals("role name wrong", inviteeRole, invitation.getRoleName()); assertEquals("server path wrong", serverPath, invitation.getServerPath()); assertEquals("accept URL wrong", acceptUrl, invitation.getAcceptUrl()); assertEquals("reject URL wrong", rejectUrl, invitation.getRejectUrl()); Date sentDate = invitation.getSentInviteDate(); // sentInviteDate should be set to today assertTrue("sentDate wrong too early", sentDate.after(startDate)); assertTrue("sentDate wrong - too late", sentDate.before(new Date(new Date().getTime() + 1))); } /** * Check the email itself, and check it * is as we would expect it to be */ { MimeMessage msg = mailService.retrieveLastTestMessage(); assertEquals(1, msg.getAllRecipients().length); assertEquals(inviteeEmail, msg.getAllRecipients()[0].toString()); assertEquals(1, msg.getFrom().length); assertEquals(USER_MANAGER + "@alfrescotesting.com", msg.getFrom()[0].toString()); // Hasn't been sent, so no sent or received date assertNull("Not been sent yet", msg.getSentDate()); assertNull("Not been sent yet", msg.getReceivedDate()); // TODO - check some more details of the email assertTrue((msg.getSubject().indexOf("You have been invited to join the") != -1)); } /** * Search for the new invitation */ List<Invitation> invitations = invitationService.listPendingInvitationsForResource(resourceType, resourceName); assertTrue("invitations is empty", !invitations.isEmpty()); NominatedInvitation firstInvite = (NominatedInvitation) invitations.get(0); assertEquals("invite id wrong", inviteId, firstInvite.getInviteId()); assertEquals("first name wrong", inviteeFirstName, firstInvite.getInviteeFirstName()); assertEquals("last name wrong", inviteeLastName, firstInvite.getInviteeLastName()); assertEquals("user name wrong", inviteeUserName, firstInvite.getInviteeUserName()); /** * Now accept the invitation */ NominatedInvitation acceptedInvitation = (NominatedInvitation) invitationService .accept(firstInvite.getInviteId(), firstInvite.getTicket()); assertEquals("invite id wrong", firstInvite.getInviteId(), acceptedInvitation.getInviteId()); assertEquals("first name wrong", inviteeFirstName, acceptedInvitation.getInviteeFirstName()); assertEquals("last name wrong", inviteeLastName, acceptedInvitation.getInviteeLastName()); assertEquals("user name wrong", inviteeUserName, acceptedInvitation.getInviteeUserName()); List<Invitation> it4 = invitationService.listPendingInvitationsForResource(resourceType, resourceName); assertTrue("invitations is not empty", it4.isEmpty()); /** * Now get the invitation that we accepted */ NominatedInvitation acceptedInvitation2 = (NominatedInvitation) invitationService .getInvitation(firstInvite.getInviteId()); assertNotNull("get after accept does not return", acceptedInvitation2); /** * Now verify access control list */ String roleName = siteService.getMembersRole(resourceName, inviteeUserName); assertEquals("role name wrong", roleName, inviteeRole); siteService.removeMembership(resourceName, inviteeUserName); /** * Check that system generated invitations can work as well */ { Field faf = mailService.getClass().getDeclaredField("fromAddress"); faf.setAccessible(true); String defaultFromAddress = (String) ReflectionUtils.getField(faf, mailService); AuthenticationUtil.setFullyAuthenticatedUser(USER_NOEMAIL); // Check invitiation NominatedInvitation nominatedInvitation2 = invitationService.inviteNominated(inviteeFirstName, inviteeLastName, USER_TWO_EMAIL, resourceType, resourceName, inviteeRole, serverPath, acceptUrl, rejectUrl); assertNotNull("nominated invitation is null", nominatedInvitation2); inviteId = nominatedInvitation.getInviteId(); assertEquals("first name wrong", inviteeFirstName, nominatedInvitation2.getInviteeFirstName()); assertEquals("last name wrong", inviteeLastName, nominatedInvitation2.getInviteeLastName()); assertEquals("email name wrong", USER_TWO_EMAIL, nominatedInvitation2.getInviteeEmail()); // Check the email MimeMessage msg = mailService.retrieveLastTestMessage(); assertEquals(1, msg.getAllRecipients().length); assertEquals(USER_TWO_EMAIL, msg.getAllRecipients()[0].toString()); assertEquals(1, msg.getFrom().length); assertEquals(defaultFromAddress, msg.getFrom()[0].toString()); } }
From source file:org.apache.axis2.transport.mail.SimpleMailListener.java
private MessageContext createMessageContextToMailWorker(MimeMessage msg) throws Exception { Object content = msg.getContent(); if (!(content instanceof Multipart)) { return null; }//from w ww. java2 s . c o m MessageContext msgContext = null; TransportInDescription transportIn = configurationContext.getAxisConfiguration() .getTransportIn(org.apache.axis2.Constants.TRANSPORT_MAIL); TransportOutDescription transportOut = configurationContext.getAxisConfiguration() .getTransportOut(org.apache.axis2.Constants.TRANSPORT_MAIL); if ((transportIn != null) && (transportOut != null)) { // create Message Context msgContext = configurationContext.createMessageContext(); msgContext.setTransportIn(transportIn); msgContext.setTransportOut(transportOut); msgContext.setServerSide(true); msgContext.setProperty(org.apache.axis2.transport.mail.Constants.CONTENT_TYPE, msg.getContentType()); msgContext.setIncomingTransportName(org.apache.axis2.Constants.TRANSPORT_MAIL); MailBasedOutTransportInfo transportInfo = new MailBasedOutTransportInfo(); Address[] mimefroms = msg.getFrom(); if (mimefroms != null && mimefroms.length > 0) { EndpointReference fromEPR = new EndpointReference( org.apache.axis2.transport.mail.Constants.MAILTO + ":" + msg.getFrom()[0].toString()); transportInfo.setFrom(fromEPR); } else { String returnPath = getMailHeader(msg, org.apache.axis2.transport.mail.Constants.RETURN_PATH); returnPath = parseHeaderForLessThan(returnPath); if (returnPath != null) { EndpointReference fromEPR = new EndpointReference( org.apache.axis2.transport.mail.Constants.MAILTO + ":" + returnPath); transportInfo.setFrom(fromEPR); } } // Save Message-Id to set as In-Reply-To on reply String smtpMessageId = msg.getMessageID(); if (smtpMessageId != null) { transportInfo.setInReplyTo(smtpMessageId); } String inReplyTo = getMailHeader(msg, org.apache.axis2.transport.mail.Constants.IN_REPLY_TO); if (inReplyTo != null) { transportInfo.setInReplyTo(inReplyTo); } msgContext.setProperty(org.apache.axis2.Constants.OUT_TRANSPORT_INFO, transportInfo); buildSOAPEnvelope(msg, msgContext); if (!fillMessageContextFromAvaiableData(msgContext, inReplyTo)) { return null; } } return msgContext; }