List of usage examples for javax.mail Session getDefaultInstance
public static Session getDefaultInstance(Properties props)
From source file:org.alfresco.repo.imap.ImapMessageTest.java
public void testEightBitMessage() throws Exception { Store lstore = session.getStore(PROTOCOL); lstore.connect(imapServer.getHost(), imapServer.getPort(), ADMIN_USER_NAME, ADMIN_USER_PASSWORD); String folderName = "Alfresco IMAP/" + IMAP_FOLDER_NAME; IMAPFolder lfolder = (IMAPFolder) lstore.getFolder(folderName); lfolder.open(Folder.READ_WRITE);/*from w ww . ja v a 2 s .com*/ InputStream messageFileInputStream1 = null; InputStream messageFileInputStream2 = null; try { ClassPathResource fileResource = new ClassPathResource("imap/test-8bit-message.eml"); messageFileInputStream1 = new FileInputStream(fileResource.getFile()); Message message = new MimeMessage(Session.getDefaultInstance(new Properties()), messageFileInputStream1); String subject = message.getSubject(); // get original bytes for further comparation messageFileInputStream2 = new FileInputStream(fileResource.getFile()); byte[] original = ASCIIUtility.getBytes(messageFileInputStream2); Message[] messages = { message }; lfolder.appendMessages(messages); // The search is not implemented. // SearchTerm term = new HeaderTerm("X-Alfresco-Unique", "test8bit"); // messages = folder.search(term); // So wee need to get our test message's UID from the repo String messageXPath = companyHomePathInStore + "/" + NamespaceService.CONTENT_MODEL_PREFIX + ":" + IMAP_FOLDER_NAME + "/*[like(@cm:title, $cm:title, true)]"; QueryParameterDefinition[] params = new QueryParameterDefinition[1]; params[0] = new QueryParameterDefImpl(ContentModel.PROP_TITLE, serviceRegistry.getDictionaryService().getDataType(DataTypeDefinition.TEXT), true, subject); List<NodeRef> nodeRefs = searchService.selectNodes(storeRootNodeRef, messageXPath, params, namespaceService, true); // does the message exist assertEquals(1, nodeRefs.size()); NodeRef messageNodeRef = nodeRefs.get(0); // get message UID Long dbid = (Long) nodeService.getProperty(messageNodeRef, ContentModel.PROP_NODE_DBID); // fetch the massage RFC822DATA data = getRFC822Message(lfolder, dbid); assertNotNull("Can't fetch a message from the repositiry", data); byte[] processed = ASCIIUtility.getBytes(data.getByteArrayInputStream()); assertTrue("Original message doesn't coincide to the message processed by the repository", Arrays.equals(original, processed)); } finally { if (messageFileInputStream1 != null) messageFileInputStream1.close(); if (messageFileInputStream2 != null) messageFileInputStream2.close(); } // close connection lfolder.close(true); lstore.close(); }
From source file:com.ikon.util.MailUtils.java
/** * Import messages/*from w ww . j ava 2s . c om*/ * http://www.jguru.com/faq/view.jsp?EID=26898 * * == Using Unique Identifier (UIDL) == * Mail server assigns an unique identifier for every email in the same account. You can get as UIDL * for every email by MailInfo.UIDL property. To avoid receiving the same email twice, the best way is * storing the UIDL of email retrieved to a text file or database. Next time before you retrieve email, * compare your local uidl list with remote uidl. If this uidl exists in your local uidl list, don't * receive it; otherwise receive it. * * == Different property of UIDL in POP3 and IMAP4 == * UIDL is always unique in IMAP4 and it is always an incremental integer. UIDL in POP3 can be any valid * asc-ii characters, and an UIDL may be reused by POP3 server if email with this UIDL has been deleted * from the server. Hence you are advised to remove the uidl from your local uidl list if that uidl is * no longer exist on the POP3 server. * * == Remarks == * You should create different local uidl list for different email account, because the uidl is only * unique for the same account. */ public static String importMessages(String token, MailAccount ma) throws PathNotFoundException, ItemExistsException, VirusDetectedException, AccessDeniedException, RepositoryException, DatabaseException, UserQuotaExceededException, ExtensionException, AutomationException { log.debug("importMessages({}, {})", new Object[] { token, ma }); Session session = Session.getDefaultInstance(getProperties()); String exceptionMessage = null; try { // Open connection Store store = session.getStore(ma.getMailProtocol()); store.connect(ma.getMailHost(), ma.getMailUser(), ma.getMailPassword()); Folder folder = store.getFolder(ma.getMailFolder()); folder.open(Folder.READ_WRITE); Message messages[] = null; if (folder instanceof IMAPFolder) { // IMAP folder UIDs begins at 1 and are supposed to be sequential. // Each folder has its own UIDs sequence, not is a global one. messages = ((IMAPFolder) folder).getMessagesByUID(ma.getMailLastUid() + 1, UIDFolder.LASTUID); } else { messages = folder.search(new FlagTerm(new Flags(Flags.Flag.SEEN), false)); } for (int i = 0; i < messages.length; i++) { Message msg = messages[i]; log.info(i + ": " + msg.getFrom()[0] + " " + msg.getSubject() + " " + msg.getContentType()); log.info("Received: " + msg.getReceivedDate()); log.info("Sent: " + msg.getSentDate()); log.debug("{} -> {} - {}", new Object[] { i, msg.getSubject(), msg.getReceivedDate() }); com.ikon.bean.Mail mail = messageToMail(msg); if (ma.getMailFilters().isEmpty()) { log.debug("Import in compatibility mode"); String mailPath = getUserMailPath(ma.getUser()); importMail(token, mailPath, true, folder, msg, ma, mail); } else { for (MailFilter mf : ma.getMailFilters()) { log.debug("MailFilter: {}", mf); if (checkRules(mail, mf.getFilterRules())) { String mailPath = mf.getPath(); importMail(token, mailPath, mf.isGrouping(), folder, msg, ma, mail); } } } // Set message as seen if (ma.isMailMarkSeen()) { msg.setFlag(Flags.Flag.SEEN, true); } else { msg.setFlag(Flags.Flag.SEEN, false); } // Delete read mail if requested if (ma.isMailMarkDeleted()) { msg.setFlag(Flags.Flag.DELETED, true); } // Set lastUid if (folder instanceof IMAPFolder) { long msgUid = ((IMAPFolder) folder).getUID(msg); log.info("Message UID: {}", msgUid); ma.setMailLastUid(msgUid); MailAccountDAO.update(ma); } } // Close connection log.debug("Expunge: {}", ma.isMailMarkDeleted()); folder.close(ma.isMailMarkDeleted()); store.close(); } catch (NoSuchProviderException e) { log.error(e.getMessage(), e); exceptionMessage = e.getMessage(); } catch (MessagingException e) { log.error(e.getMessage(), e); exceptionMessage = e.getMessage(); } catch (IOException e) { log.error(e.getMessage(), e); exceptionMessage = e.getMessage(); } log.debug("importMessages: {}", exceptionMessage); return exceptionMessage; }
From source file:com.openkm.util.MailUtils.java
/** * Import messages/*w w w .ja v a 2 s. co m*/ * http://www.jguru.com/faq/view.jsp?EID=26898 * * == Using Unique Identifier (UIDL) == * Mail server assigns an unique identifier for every email in the same account. You can get as UIDL * for every email by MailInfo.UIDL property. To avoid receiving the same email twice, the best way is * storing the UIDL of email retrieved to a text file or database. Next time before you retrieve email, * compare your local uidl list with remote uidl. If this uidl exists in your local uidl list, don't * receive it; otherwise receive it. * * == Different property of UIDL in POP3 and IMAP4 == * UIDL is always unique in IMAP4 and it is always an incremental integer. UIDL in POP3 can be any valid * asc-ii characters, and an UIDL may be reused by POP3 server if email with this UIDL has been deleted * from the server. Hence you are advised to remove the uidl from your local uidl list if that uidl is * no longer exist on the POP3 server. * * == Remarks == * You should create different local uidl list for different email account, because the uidl is only * unique for the same account. */ public static String importMessages(String token, MailAccount ma) throws PathNotFoundException, ItemExistsException, VirusDetectedException, AccessDeniedException, RepositoryException, DatabaseException, UserQuotaExceededException, ExtensionException, AutomationException { log.debug("importMessages({}, {})", new Object[] { token, ma }); Session session = Session.getDefaultInstance(getProperties()); String exceptionMessage = null; try { // Open connection Store store = session.getStore(ma.getMailProtocol()); store.connect(ma.getMailHost(), ma.getMailUser(), ma.getMailPassword()); Folder folder = store.getFolder(ma.getMailFolder()); folder.open(Folder.READ_WRITE); Message messages[] = null; if (folder instanceof IMAPFolder) { // IMAP folder UIDs begins at 1 and are supposed to be sequential. // Each folder has its own UIDs sequence, not is a global one. messages = ((IMAPFolder) folder).getMessagesByUID(ma.getMailLastUid() + 1, UIDFolder.LASTUID); } else { messages = folder.search(new FlagTerm(new Flags(Flags.Flag.SEEN), false)); } for (int i = 0; i < messages.length; i++) { Message msg = messages[i]; log.info("======= ======= {} ======= =======", i); log.info("Subject: {}", msg.getSubject()); log.info("From: {}", msg.getFrom()); log.info("Received: {}", msg.getReceivedDate()); log.info("Sent: {}", msg.getSentDate()); com.openkm.bean.Mail mail = messageToMail(msg); if (ma.getMailFilters().isEmpty()) { log.debug("Import in compatibility mode"); String mailPath = getUserMailPath(ma.getUser()); importMail(token, mailPath, true, folder, msg, ma, mail); } else { for (MailFilter mf : ma.getMailFilters()) { log.debug("MailFilter: {}", mf); if (checkRules(mail, mf.getFilterRules())) { String mailPath = mf.getPath(); importMail(token, mailPath, mf.isGrouping(), folder, msg, ma, mail); } } } // Set message as seen if (ma.isMailMarkSeen()) { msg.setFlag(Flags.Flag.SEEN, true); } else { msg.setFlag(Flags.Flag.SEEN, false); } // Delete read mail if requested if (ma.isMailMarkDeleted()) { msg.setFlag(Flags.Flag.DELETED, true); } // Set lastUid if (folder instanceof IMAPFolder) { long msgUid = ((IMAPFolder) folder).getUID(msg); log.info("Message UID: {}", msgUid); ma.setMailLastUid(msgUid); MailAccountDAO.update(ma); } } // Close connection log.debug("Expunge: {}", ma.isMailMarkDeleted()); folder.close(ma.isMailMarkDeleted()); store.close(); } catch (NoSuchProviderException e) { log.error(e.getMessage(), e); exceptionMessage = e.getMessage(); } catch (MessagingException e) { log.error(e.getMessage(), e); exceptionMessage = e.getMessage(); } catch (IOException e) { log.error(e.getMessage(), e); exceptionMessage = e.getMessage(); } log.debug("importMessages: {}", exceptionMessage); return exceptionMessage; }
From source file:edu.ku.brc.helpers.EMailHelper.java
/** * Retrieves a list of all the available messages. For POP3 it checks the local mailbox and downloads any on the server. * For IMAP it returns any in the INBOX. * @param msgList the list to be filled//from w ww . ja v a 2 s. c o m * @return true if not erros, false if an error occurred. */ public static boolean getAvailableMsgs(java.util.List<javax.mail.Message> msgList) { boolean status = false; // assume it will fail msgList.clear(); try { String usernameStr = AppPreferences.getRemote().get("settings.email.username", null); //$NON-NLS-1$ String passwordStr = Encryption .decrypt(AppPreferences.getRemote().get("settings.email.password", null)); //$NON-NLS-1$ String emailStr = AppPreferences.getRemote().get("settings.email.email", null); //$NON-NLS-1$ String smtpStr = AppPreferences.getRemote().get("settings.email.smtp", null); //$NON-NLS-1$ String serverNameStr = AppPreferences.getRemote().get("settings.email.servername", null); //$NON-NLS-1$ String acctTypeStr = AppPreferences.getRemote().get("settings.email.accounttype", null); //$NON-NLS-1$ String localMailBoxStr = AppPreferences.getRemote().get("settings.email.localmailbox", null); //$NON-NLS-1$ EMailHelper.AccountType acctType = EMailHelper.getAccountType(acctTypeStr); if (!hasEMailSettings(usernameStr, passwordStr, emailStr, smtpStr, serverNameStr, acctTypeStr, localMailBoxStr)) { JOptionPane.showMessageDialog(UIRegistry.getMostRecentWindow(), getResourceString("EMailHelper.EMAIL_SET_NOT_VALID")); //$NON-NLS-1$ } // Open Local Box if POP if (acctTypeStr.equals(getResourceString("EMailHelper.POP3"))) //$NON-NLS-1$ { try { Properties props = new Properties(); Session session = Session.getDefaultInstance(props); Store store = session.getStore(new URLName("mstor:" + localMailBoxStr)); //$NON-NLS-1$ store.connect(); status = getMessagesFromInbox(store, msgList); // closes everything } catch (Exception ex) { edu.ku.brc.af.core.UsageTracker.incrHandledUsageCount(); edu.ku.brc.exceptions.ExceptionTracker.getInstance().capture(EMailHelper.class, ex); instance.lastErrorMsg = ex.toString(); ex.printStackTrace(); status = false; } } else { throw new RuntimeException("Unknown Account Type [" + acctTypeStr + "] must be POP3 or IMAP"); // XXX FIXME //$NON-NLS-1$ //$NON-NLS-2$ } // Try to download message from pop account try { Properties props = System.getProperties(); Session session = Session.getInstance(props, null); if (acctType == AccountType.POP3) { Store store = session.getStore("pop3"); //$NON-NLS-1$ store.connect(serverNameStr, usernameStr, passwordStr); status = getMessagesFromInbox(store, msgList); // closes everything } else if (acctType == AccountType.IMAP) { Store store = session.getStore("imap"); //$NON-NLS-1$ store.connect(serverNameStr, usernameStr, passwordStr); status = getMessagesFromInbox(store, msgList); // closes everything } else { String msgStr = getResourceString("EMailHelper.UNKNOWN_ACCT_TYPE")// //$NON-NLS-1$ + acctTypeStr + getResourceString("EMailHelper.ACCT_TYPE_MUST_BE"); // XXX// //$NON-NLS-2$ instance.lastErrorMsg = msgStr; throw new RuntimeException(msgStr); // XXX FIXME } } catch (Exception ex) { edu.ku.brc.af.core.UsageTracker.incrHandledUsageCount(); edu.ku.brc.exceptions.ExceptionTracker.getInstance().capture(EMailHelper.class, ex); instance.lastErrorMsg = ex.toString(); status = false; } } catch (Exception ex) { edu.ku.brc.af.core.UsageTracker.incrHandledUsageCount(); edu.ku.brc.exceptions.ExceptionTracker.getInstance().capture(EMailHelper.class, ex); instance.lastErrorMsg = ex.toString(); status = false; } return status; }
From source file:org.alfresco.email.server.EmailServiceImplTest.java
/** * ALF-1878/*w w w . j a v a 2 s .com*/ * * Duplicate incoming email Subjects over-write each other */ public void testMultipleMessagesToFolder() throws Exception { logger.debug("Start testFromName"); String TEST_EMAIL = "buffy@sunnydale.high"; String TEST_SUBJECT = "Practical Bee Keeping"; String TEST_LONG_SUBJECT = "This is a very very long name in particular it is greater than eitghty six characters which was a problem explored in ALF-9544"; // TODO Investigate why setting PROP_EMAIL on createPerson does not work. NodeRef person = personService.getPerson(TEST_USER); if (person == null) { logger.debug("new person created"); Map<QName, Serializable> props = new HashMap<QName, Serializable>(); props.put(ContentModel.PROP_USERNAME, TEST_USER); props.put(ContentModel.PROP_EMAIL, TEST_EMAIL); person = personService.createPerson(props); } nodeService.setProperty(person, ContentModel.PROP_EMAIL, TEST_EMAIL); Set<String> auths = authorityService.getContainedAuthorities(null, "GROUP_EMAIL_CONTRIBUTORS", true); if (!auths.contains(TEST_USER)) { authorityService.addAuthority("GROUP_EMAIL_CONTRIBUTORS", TEST_USER); } String companyHomePathInStore = "/app:company_home"; String storePath = "workspace://SpacesStore"; StoreRef storeRef = new StoreRef(storePath); NodeRef storeRootNodeRef = nodeService.getRootNode(storeRef); List<NodeRef> nodeRefs = searchService.selectNodes(storeRootNodeRef, companyHomePathInStore, null, namespaceService, false); NodeRef companyHomeNodeRef = nodeRefs.get(0); assertNotNull("company home is null", companyHomeNodeRef); String companyHomeDBID = ((Long) nodeService.getProperty(companyHomeNodeRef, ContentModel.PROP_NODE_DBID)) .toString() + "@Alfresco.com"; String testUserDBID = ((Long) nodeService.getProperty(person, ContentModel.PROP_NODE_DBID)).toString() + "@Alfresco.com"; NodeRef testUserHomeFolder = (NodeRef) nodeService.getProperty(person, ContentModel.PROP_HOMEFOLDER); assertNotNull("testUserHomeFolder is null", testUserHomeFolder); String testUserHomeDBID = ((Long) nodeService.getProperty(testUserHomeFolder, ContentModel.PROP_NODE_DBID)) .toString() + "@Alfresco.com"; // Clean up old messages in test folder List<ChildAssociationRef> assocs = nodeService.getChildAssocs(testUserHomeFolder, ContentModel.ASSOC_CONTAINS, RegexQNamePattern.MATCH_ALL); for (ChildAssociationRef assoc : assocs) { nodeService.deleteNode(assoc.getChildRef()); } /** * Send From the test user TEST_EMAIL to the test user's home */ String from = TEST_EMAIL; String to = testUserHomeDBID; String content = "hello world"; Session sess = Session.getDefaultInstance(new Properties()); assertNotNull("sess is null", sess); SMTPMessage msg = new SMTPMessage(sess); InternetAddress[] toa = { new InternetAddress(to) }; msg.setFrom(new InternetAddress(TEST_EMAIL)); msg.setRecipients(Message.RecipientType.TO, toa); msg.setSubject(TEST_SUBJECT); msg.setContent(content, "text/plain"); ByteArrayOutputStream bos = new ByteArrayOutputStream(); msg.writeTo(bos); InputStream is = IOUtils.toInputStream(bos.toString()); assertNotNull("is is null", is); SubethaEmailMessage m = new SubethaEmailMessage(is); /** * Turn on overwriteDuplicates */ logger.debug("Step 1: turn on Overwite Duplicates"); folderEmailMessageHandler.setOverwriteDuplicates(true); EmailDelivery delivery = new EmailDelivery(to, from, null); emailService.importMessage(delivery, m); assocs = nodeService.getChildAssocs(testUserHomeFolder, ContentModel.ASSOC_CONTAINS, RegexQNamePattern.MATCH_ALL); assertEquals("assocs not 1", 1, assocs.size()); assertEquals("name of link not as expected", assocs.get(0).getQName(), QName.createQName(NamespaceService.CONTENT_MODEL_1_0_URI, TEST_SUBJECT)); emailService.importMessage(delivery, m); assocs = nodeService.getChildAssocs(testUserHomeFolder, ContentModel.ASSOC_CONTAINS, RegexQNamePattern.MATCH_ALL); assertEquals("assocs not 1", 1, assocs.size()); /** * Turn off overwrite Duplicates */ logger.debug("Step 2: turn off Overwite Duplicates"); folderEmailMessageHandler.setOverwriteDuplicates(false); emailService.importMessage(delivery, m); assocs = nodeService.getChildAssocs(testUserHomeFolder, ContentModel.ASSOC_CONTAINS, RegexQNamePattern.MATCH_ALL); assertEquals("assocs not 2", 2, assocs.size()); emailService.importMessage(delivery, m); assocs = nodeService.getChildAssocs(testUserHomeFolder, ContentModel.ASSOC_CONTAINS, RegexQNamePattern.MATCH_ALL); assertEquals("assocs not 3", 3, assocs.size()); /** * Check assoc rename with long names. So truncation and rename need to work together. */ logger.debug("Step 3: turn off Overwite Duplicates with long subject name"); msg.setSubject(TEST_LONG_SUBJECT); ByteArrayOutputStream bos2 = new ByteArrayOutputStream(); msg.writeTo(bos2); is = IOUtils.toInputStream(bos2.toString()); assertNotNull("is is null", is); m = new SubethaEmailMessage(is); folderEmailMessageHandler.setOverwriteDuplicates(false); emailService.importMessage(delivery, m); assocs = nodeService.getChildAssocs(testUserHomeFolder, ContentModel.ASSOC_CONTAINS, RegexQNamePattern.MATCH_ALL); assertEquals("assocs not 4", 4, assocs.size()); emailService.importMessage(delivery, m); assocs = nodeService.getChildAssocs(testUserHomeFolder, ContentModel.ASSOC_CONTAINS, RegexQNamePattern.MATCH_ALL); assertEquals("assocs not 5", 5, assocs.size()); /** * Check assoc rename with long names and an extension. So truncation and rename need to * work together and not muck up a .extension. */ logger.debug("Step 4: turn off Overwite Duplicates with long subject name with extension"); String EXT_NAME = "Blob.xls"; msg.setSubject(EXT_NAME); ByteArrayOutputStream bos3 = new ByteArrayOutputStream(); msg.writeTo(bos3); is = IOUtils.toInputStream(bos3.toString()); assertNotNull("is is null", is); m = new SubethaEmailMessage(is); folderEmailMessageHandler.setOverwriteDuplicates(false); emailService.importMessage(delivery, m); emailService.importMessage(delivery, m); emailService.importMessage(delivery, m); assocs = nodeService.getChildAssocs(testUserHomeFolder, ContentModel.ASSOC_CONTAINS, RegexQNamePattern.MATCH_ALL); List<QName> assocNames = new Vector<QName>(); for (ChildAssociationRef assoc : assocs) { logger.debug("assocName: " + assoc.getQName()); System.out.println(assoc.getQName()); assocNames.add(assoc.getQName()); } assertTrue(EXT_NAME + "not found", assocNames.contains(QName.createQName(NamespaceService.CONTENT_MODEL_1_0_URI, "Blob.xls"))); assertTrue("Blob(1).xls not found", assocNames.contains(QName.createQName(NamespaceService.CONTENT_MODEL_1_0_URI, "Blob(1).xls"))); assertTrue("Blob(2).xls not found", assocNames.contains(QName.createQName(NamespaceService.CONTENT_MODEL_1_0_URI, "Blob(2).xls"))); assertTrue(TEST_SUBJECT + "not found", assocNames.contains(QName.createQName(NamespaceService.CONTENT_MODEL_1_0_URI, TEST_SUBJECT))); assertTrue(TEST_SUBJECT + "(1) not found", assocNames .contains(QName.createQName(NamespaceService.CONTENT_MODEL_1_0_URI, "Practical Bee Keeping(1)"))); /** * Check concurrent deliver of the same message. Reuse message from the previous test. */ logger.debug("Step 5: turn off Overwite Duplicates and check concurrent deliver of the same message"); folderEmailMessageHandler.setOverwriteDuplicates(false); assocs = nodeService.getChildAssocs(testUserHomeFolder, ContentModel.ASSOC_CONTAINS, RegexQNamePattern.MATCH_ALL); int numBeforeConcurrentDeliver = assocs.size(); deliverConcurrently(delivery, m); assocs = nodeService.getChildAssocs(testUserHomeFolder, ContentModel.ASSOC_CONTAINS, RegexQNamePattern.MATCH_ALL); int numAfterConcurrentDeliver = assocs.size(); assertEquals("Two messages must be added", numBeforeConcurrentDeliver + 2, numAfterConcurrentDeliver); }
From source file:fr.gouv.culture.vitam.eml.EmlExtract.java
private static final MimeMessage createOneMessageFromFile(File emlFile) throws FileNotFoundException, MessagingException { Properties props = System.getProperties(); Session session = Session.getDefaultInstance(props); /*props.put("mail.host", "smtp.vitamdomain.com"); props.put("mail.transport.protocol", "smtp"); Session session = Session.getDefaultInstance(props, null);*/ InputStream source = new FileInputStream(emlFile); return new MimeMessage(session, source); }
From source file:org.socraticgrid.displaymaildata.DisplayMailDataHandler.java
/** * * @param request/*from w w w . ja va 2 s.c om*/ * where request.action = [ "Send" , "Update" ,"Read" , "Save" ] * @return */ private SetMessageResponseType sendImapSSLMail(SetMessageRequestType request) { //System.out.println("===> sendImapSSLMail: Action= " + request.getAction()); SetMessageResponseType response = new SetMessageResponseType(); IMAPSSLStore sslStore = null; Folder folder = null; //the email server folder the msg is CURRENTLY in. String userType = ""; String[] access = new String[2]; Properties prop = initializeMailProperties(); Session session = Session.getDefaultInstance(prop); //Get email address and password from LDAP String userId = request.getUserId(); ContactDTO foundContact = null; try { foundContact = findContactByUserId(userId); } catch (Exception e) { log.error("Contact record not found for userid: " + request.getUserId()); response.setMessage("Contact record not found for userid: " + request.getUserId()); response.setSuccessStatus(false); return response; } access = retrieveMailAccess(foundContact.getCommonName(), foundContact.getUid()); if ((access[0] == null) || access[0].isEmpty()) { log.error("Contact record not found for user: " + userId); response.setMessage("Contact record not found for user: " + userId); response.setSuccessStatus(false); return response; } // Use the sslStore to send/change the message try { //action = Save if (request.getAction().equalsIgnoreCase("Save")) { response = saveDraft(request, access, sslStore, this.mapKmrLocationToImapFolder("Drafts", this.host), session); response.setSuccessStatus(true); //return response; } //action = Send else if (request.getAction().equalsIgnoreCase("Send")) { // create and send msg to recipient(s). Message[] msgArr = createMessage(session, access[0], request); sendMessagesTOCCBCC(msgArr, request, session); // Store a copy to sender's Sent folder folder = getImapFolder(session, sslStore, access, this.mapKmrLocationToImapFolder("Sent", this.host)); folder.appendMessages(msgArr); response.setSuccessStatus(true); } //action = ..any other.. else { folder = getImapFolder(session, sslStore, access, this.mapKmrLocationToImapFolder(request.getLocation(), this.host)); folder.open(Folder.READ_WRITE); //-------------------------------------------- // Find the message by the given Message-ID //-------------------------------------------- IMAPMessage imapMessage = (IMAPMessage) findMsgByMessageId(folder, request.getMessageId()); //-------------------------------------------- // Process the message //-------------------------------------------- if (imapMessage != null) { System.out.println("===> sendImapSSLMail:Updating: action=" + request.getAction()); System.out.println("===> sendImapSSLMail:Updating: folder=" + folder.getName()); System.out.println("===> sendImapSSLMail:Updating:ImapMsgID=" + imapMessage.getMessageID()); updateImapSSLMail(request, folder, imapMessage); System.out.println("===> sendImapSSLMail: Done Setting " + request.getAction() + " for msgId=" + request.getMessageId()); response.setSuccessStatus(true); } else { String statMsg = "Msg NOT found for Message-ID=" + request.getMessageId(); System.out.println("===> sendImapSSLMail: " + statMsg); response.setSuccessStatus(false); response.setMessage(statMsg); } } } catch (Exception e) { log.error(e.getMessage()); response.setMessage("Error sending mail with Zimbra mail server: " + e.getMessage()); response.setSuccessStatus(false); return response; } finally { if (folder != null && folder.isOpen()) { try { folder.close(false); } catch (MessagingException me) { log.error("Error closing folder"); } } if (sslStore != null) { try { sslStore.close(); } catch (MessagingException me) { log.error("Error closing SSLStore"); } } } return response; }
From source file:userInterface.HospitalAdminRole.ManagePatientsJPanel.java
public void sendMailToCommunityMember(String to, String subject, String message, String from, String password) { String host = "smtp.gmail.com"; Properties props = System.getProperties(); props.put("mail.smtp.auth", "true"); props.put("mail.smtp.starttls.enable", "true"); props.put("mail.smtp.host", host); props.put("mail.smtp.port", 587); props.put("mail.smtp.user", from); Session session = Session.getDefaultInstance(props); MimeMessage mimeMessage = new MimeMessage(session); try {/*w ww . j a v a 2 s . c o m*/ mimeMessage.setFrom(new InternetAddress(from)); mimeMessage.setRecipients(Message.RecipientType.TO, InternetAddress.parse(to)); mimeMessage.setSubject("Alert from Hospital Organization"); mimeMessage.setText(message); SMTPTransport transport = (SMTPTransport) session.getTransport("smtps"); transport.connect(host, from, password); transport.sendMessage(mimeMessage, mimeMessage.getAllRecipients()); transport.close(); } catch (MessagingException me) { } }
From source file:cz.incad.vdkcommon.solr.Indexer.java
private void sendDemandMail(SolrDocument resultDoc, String id) { try {/* w ww . java 2 s . c o m*/ String title = (String) resultDoc.getFieldValues("title").toArray()[0]; String pop = (String) resultDoc.getFieldValue("poptavka_ext"); JSONObject j = new JSONObject(pop); String from = opts.getString("admin.email"); Knihovna kn = new Knihovna(j.getString("knihovna")); String to = kn.getEmail(); String zaznam = j.optString("zaznam"); String code = j.optString("code"); String exemplar = j.optString("exemplar"); try { Properties properties = System.getProperties(); Session session = Session.getDefaultInstance(properties); MimeMessage message = new MimeMessage(session); message.setFrom(new InternetAddress(from)); message.addRecipient(Message.RecipientType.TO, new InternetAddress(to)); message.setSubject(opts.getString("admin.email.demand.subject")); String link = opts.getString("app.url") + "/original?id=" + id; String body = opts.getString("admin.email.demand.body").replace("${demand.title}", title) .replace("${demand.url}", link); message.setText(body); Transport.send(message); LOGGER.fine("Sent message successfully...."); } catch (MessagingException ex) { LOGGER.log(Level.SEVERE, "Error sending email to: {0}, from {1} ", new Object[] { to, from }); LOGGER.log(Level.SEVERE, null, ex); } } catch (NamingException | SQLException ex) { LOGGER.log(Level.SEVERE, null, ex); } }
From source file:org.alfresco.email.server.EmailServiceImplTest.java
/** * MNT-9289//from w w w . j a v a2 s.c o m * * Change in case in email Subject causes DuplicateChildNodeNameException */ public void testCaseSensitivity() throws Exception { NodeRef person = personService.getPerson(TEST_USER); String TEST_EMAIL = "buffy@sunnydale.high"; NodeRef testUserHomeFolder = (NodeRef) nodeService.getProperty(person, ContentModel.PROP_HOMEFOLDER); if (person == null) { logger.debug("new person created"); Map<QName, Serializable> props = new HashMap<QName, Serializable>(); props.put(ContentModel.PROP_USERNAME, TEST_USER); props.put(ContentModel.PROP_EMAIL, TEST_EMAIL); person = personService.createPerson(props); } nodeService.setProperty(person, ContentModel.PROP_EMAIL, TEST_EMAIL); Set<String> auths = authorityService.getContainedAuthorities(null, "GROUP_EMAIL_CONTRIBUTORS", true); if (!auths.contains(TEST_USER)) { authorityService.addAuthority("GROUP_EMAIL_CONTRIBUTORS", TEST_USER); } String companyHomePathInStore = "/app:company_home"; String storePath = "workspace://SpacesStore"; StoreRef storeRef = new StoreRef(storePath); NodeRef storeRootNodeRef = nodeService.getRootNode(storeRef); List<NodeRef> nodeRefs = searchService.selectNodes(storeRootNodeRef, companyHomePathInStore, null, namespaceService, false); NodeRef companyHomeNodeRef = nodeRefs.get(0); assertNotNull("company home is null", companyHomeNodeRef); String TEST_CASE_SENSITIVITY_SUBJECT = "Test (Mail)"; String testUserHomeDBID = ((Long) nodeService.getProperty(testUserHomeFolder, ContentModel.PROP_NODE_DBID)) .toString() + "@Alfresco.com"; String from = TEST_EMAIL; String to = testUserHomeDBID; String content = "hello world"; Session sess = Session.getDefaultInstance(new Properties()); assertNotNull("sess is null", sess); SMTPMessage msg = new SMTPMessage(sess); InternetAddress[] toa = { new InternetAddress(to) }; EmailDelivery delivery = new EmailDelivery(to, from, null); msg.setFrom(new InternetAddress(TEST_EMAIL)); msg.setRecipients(Message.RecipientType.TO, toa); msg.setContent(content, "text/plain"); msg.setSubject(TEST_CASE_SENSITIVITY_SUBJECT); ByteArrayOutputStream bos1 = new ByteArrayOutputStream(); msg.writeTo(bos1); InputStream is = IOUtils.toInputStream(bos1.toString()); assertNotNull("is is null", is); SubethaEmailMessage m = new SubethaEmailMessage(is); folderEmailMessageHandler.setOverwriteDuplicates(false); emailService.importMessage(delivery, m); QName safeQName = QName.createQNameWithValidLocalName(NamespaceService.CONTENT_MODEL_1_0_URI, TEST_CASE_SENSITIVITY_SUBJECT); List<ChildAssociationRef> assocs = nodeService.getChildAssocs(testUserHomeFolder, ContentModel.ASSOC_CONTAINS, safeQName); assertEquals(1, assocs.size()); msg.setSubject(TEST_CASE_SENSITIVITY_SUBJECT.toUpperCase()); ByteArrayOutputStream bos2 = new ByteArrayOutputStream(); msg.writeTo(bos2); is = IOUtils.toInputStream(bos2.toString()); assertNotNull("is is null", is); m = new SubethaEmailMessage(is); folderEmailMessageHandler.setOverwriteDuplicates(false); emailService.importMessage(delivery, m); safeQName = QName.createQNameWithValidLocalName(NamespaceService.CONTENT_MODEL_1_0_URI, TEST_CASE_SENSITIVITY_SUBJECT.toUpperCase() + "(1)"); assocs = nodeService.getChildAssocs(testUserHomeFolder, ContentModel.ASSOC_CONTAINS, safeQName); assertEquals(1, assocs.size()); }