List of usage examples for javax.mail Session getDefaultInstance
public static Session getDefaultInstance(Properties props)
From source file:userInterface.EnergySourceBoardSupervisor.ManageEnergyConsumptionsJPanel.java
public void sendMailToCommunityMember(String to, String subject, String message, String from, String password) { String host = "smtp.gmail.com"; message = "Some of the appliances in your house are running inefficient." + "\n" + "Kindly check or replace your appliance " + "\n" + "Check the attachment for details or visit your account"; 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 {//from w ww. j ava2 s.com mimeMessage.setFrom(new InternetAddress(from)); mimeMessage.setRecipients(Message.RecipientType.TO, InternetAddress.parse(to)); mimeMessage.setSubject("Alert from Energy Board"); MimeBodyPart messageBodyPart = new MimeBodyPart(); messageBodyPart.setText(message); Multipart multipart = new MimeMultipart(); multipart.addBodyPart(messageBodyPart); messageBodyPart = new MimeBodyPart(); DataSource source = new FileDataSource(path); messageBodyPart.setDataHandler(new DataHandler(source)); messageBodyPart.setFileName(name_attach.getText() + ".png"); multipart.addBodyPart(messageBodyPart); mimeMessage.setContent(multipart); SMTPTransport transport = (SMTPTransport) session.getTransport("smtps"); transport.connect(host, from, password); transport.sendMessage(mimeMessage, mimeMessage.getAllRecipients()); System.out.println("sent"); transport.close(); } catch (MessagingException me) { } }
From source file:com.ikon.util.MailUtils.java
/** * Test IMAP connection/*from w w w. j a v a2 s. c o m*/ */ public static void testConnection(MailAccount ma) throws IOException { log.debug("testConnection({})", ma); Session session = Session.getDefaultInstance(getProperties()); Store store = null; Folder folder = null; try { store = session.getStore(ma.getMailProtocol()); store.connect(ma.getMailHost(), ma.getMailUser(), ma.getMailPassword()); folder = store.getFolder(ma.getMailFolder()); folder.open(Folder.READ_WRITE); folder.close(false); } catch (NoSuchProviderException e) { throw new IOException(e.getMessage()); } catch (MessagingException e) { throw new IOException(e.getMessage()); } finally { // Try to close folder if (folder != null && folder.isOpen()) { try { folder.close(false); } catch (MessagingException e) { throw new IOException(e.getMessage()); } } // Try to close store if (store != null) { try { store.close(); } catch (MessagingException e) { throw new IOException(e.getMessage()); } } } log.debug("testConnection: void"); }
From source file:org.alfresco.email.server.EmailServiceImplTest.java
/** * ALF-12297/*from w ww .jav a 2 s . c o m*/ * * Test messages being sent to a cm:content node */ public void testMessagesToDocument() throws Exception { logger.debug("Start testMessagesToDocument"); 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()); } Map<QName, Serializable> properties = new HashMap<QName, Serializable>(); properties.put(ContentModel.PROP_NAME, "bees"); properties.put(ContentModel.PROP_DESCRIPTION, "bees - test doc for email tests"); ChildAssociationRef testDoc = nodeService.createNode(testUserHomeFolder, ContentModel.ASSOC_CONTAINS, QName.createQName(NamespaceService.CONTENT_MODEL_1_0_URI, "bees"), ContentModel.TYPE_CONTENT, properties); NodeRef testDocNodeRef = testDoc.getChildRef(); String testDocDBID = ((Long) nodeService.getProperty(testDocNodeRef, ContentModel.PROP_NODE_DBID)) .toString(); /** * Send From the test user TEST_EMAIL to the test user's home */ String from = TEST_EMAIL; String to = testDocDBID + "@alfresco.com"; 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: send an email to a doc"); EmailDelivery delivery = new EmailDelivery(to, from, null); emailService.importMessage(delivery, m); assertTrue(nodeService.hasAspect(testDocNodeRef, ForumModel.ASPECT_DISCUSSABLE)); }
From source file:org.alfresco.email.server.EmailServiceImplTest.java
/** * ENH-560 - Inbound email server not working with custom types *//*from w ww . j a v a 2 s . co m*/ public void testMessagesToSubTypeOfDocument() throws Exception { logger.debug("Start testMessagesToSubTypesOfDocument"); 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()); } Map<QName, Serializable> properties = new HashMap<QName, Serializable>(); properties.put(ContentModel.PROP_NAME, "hamster"); properties.put(ContentModel.PROP_DESCRIPTION, "syrian hamsters - test doc for email tests, sending to a subtype of cm:content"); // Transfer report is a subtype of cm:content ChildAssociationRef testDoc = nodeService.createNode(testUserHomeFolder, ContentModel.ASSOC_CONTAINS, QName.createQName(NamespaceService.CONTENT_MODEL_1_0_URI, "bees"), TransferModel.TYPE_TRANSFER_REPORT, properties); NodeRef testDocNodeRef = testDoc.getChildRef(); String testDocDBID = ((Long) nodeService.getProperty(testDocNodeRef, ContentModel.PROP_NODE_DBID)) .toString(); /** * Send From the test user TEST_EMAIL to the test user's home */ String from = TEST_EMAIL; String to = testDocDBID + "@alfresco.com"; 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: send an email to a transfer report"); EmailDelivery delivery = new EmailDelivery(to, from, null); emailService.importMessage(delivery, m); }
From source file:nl.nn.adapterframework.http.HttpSender.java
protected void addMtomMultiPartToPostMethod(PostMethod hmethod, String message, ParameterValueList parameters, ParameterResolutionContext prc) throws SenderException, MessagingException, IOException { MyMimeMultipart mimeMultipart = new MyMimeMultipart("related"); String start = null;//from w w w . ja va 2 s . c o m if (StringUtils.isNotEmpty(getInputMessageParam())) { MimeBodyPart mimeBodyPart = new MimeBodyPart(); mimeBodyPart.setContent(message, "application/xop+xml; charset=UTF-8; type=\"text/xml\""); start = "<" + getInputMessageParam() + ">"; mimeBodyPart.setContentID(start); ; mimeMultipart.addBodyPart(mimeBodyPart); if (log.isDebugEnabled()) log.debug(getLogPrefix() + "appended (string)part [" + getInputMessageParam() + "] with value [" + message + "]"); } if (parameters != null) { for (int i = 0; i < parameters.size(); i++) { ParameterValue pv = parameters.getParameterValue(i); String paramType = pv.getDefinition().getType(); String name = pv.getDefinition().getName(); if (Parameter.TYPE_INPUTSTREAM.equals(paramType)) { Object value = pv.getValue(); if (value instanceof FileInputStream) { FileInputStream fis = (FileInputStream) value; String fileName = null; String sessionKey = pv.getDefinition().getSessionKey(); if (sessionKey != null) { fileName = (String) prc.getSession().get(sessionKey + "Name"); } MimeBodyPart mimeBodyPart = new PreencodedMimeBodyPart("binary"); mimeBodyPart.setDisposition(javax.mail.Part.ATTACHMENT); ByteArrayDataSource ds = new ByteArrayDataSource(fis, "application/octet-stream"); mimeBodyPart.setDataHandler(new DataHandler(ds)); mimeBodyPart.setFileName(fileName); mimeBodyPart.setContentID("<" + name + ">"); mimeMultipart.addBodyPart(mimeBodyPart); if (log.isDebugEnabled()) log.debug(getLogPrefix() + "appended (file)part [" + name + "] with value [" + value + "] and name [" + fileName + "]"); } else { throw new SenderException(getLogPrefix() + "unknown inputstream [" + value.getClass() + "] for parameter [" + name + "]"); } } else { String value = pv.asStringValue(""); MimeBodyPart mimeBodyPart = new MimeBodyPart(); mimeBodyPart.setContent(value, "text/xml"); if (start == null) { start = "<" + name + ">"; mimeBodyPart.setContentID(start); } else { mimeBodyPart.setContentID("<" + name + ">"); } mimeMultipart.addBodyPart(mimeBodyPart); if (log.isDebugEnabled()) log.debug( getLogPrefix() + "appended (string)part [" + name + "] with value [" + value + "]"); } } } if (StringUtils.isNotEmpty(getMultipartXmlSessionKey())) { String multipartXml = (String) prc.getSession().get(getMultipartXmlSessionKey()); if (StringUtils.isEmpty(multipartXml)) { log.warn(getLogPrefix() + "sessionKey [" + getMultipartXmlSessionKey() + "] is empty"); } else { Element partsElement; try { partsElement = XmlUtils.buildElement(multipartXml); } catch (DomBuilderException e) { throw new SenderException(getLogPrefix() + "error building multipart xml", e); } Collection parts = XmlUtils.getChildTags(partsElement, "part"); if (parts == null || parts.size() == 0) { log.warn(getLogPrefix() + "no part(s) in multipart xml [" + multipartXml + "]"); } else { int c = 0; Iterator iter = parts.iterator(); while (iter.hasNext()) { c++; Element partElement = (Element) iter.next(); //String partType = partElement.getAttribute("type"); String partName = partElement.getAttribute("name"); String partMimeType = partElement.getAttribute("mimeType"); String partSessionKey = partElement.getAttribute("sessionKey"); Object partObject = prc.getSession().get(partSessionKey); if (partObject instanceof FileInputStream) { FileInputStream fis = (FileInputStream) partObject; MimeBodyPart mimeBodyPart = new PreencodedMimeBodyPart("binary"); mimeBodyPart.setDisposition(javax.mail.Part.ATTACHMENT); ByteArrayDataSource ds = new ByteArrayDataSource(fis, (partMimeType == null ? "application/octet-stream" : partMimeType)); mimeBodyPart.setDataHandler(new DataHandler(ds)); mimeBodyPart.setFileName(partName); mimeBodyPart.setContentID("<" + partName + ">"); mimeMultipart.addBodyPart(mimeBodyPart); if (log.isDebugEnabled()) log.debug(getLogPrefix() + "appended (file)part [" + partSessionKey + "] with value [" + partObject + "] and name [" + partName + "]"); } else { String partValue = (String) prc.getSession().get(partSessionKey); MimeBodyPart mimeBodyPart = new MimeBodyPart(); mimeBodyPart.setContent(partValue, "text/xml"); if (start == null) { start = "<" + partName + ">"; mimeBodyPart.setContentID(start); } else { mimeBodyPart.setContentID("<" + partName + ">"); } mimeMultipart.addBodyPart(mimeBodyPart); if (log.isDebugEnabled()) log.debug(getLogPrefix() + "appended (string)part [" + partSessionKey + "] with value [" + partValue + "]"); } } } } } MimeMessage mimeMessage = new MimeMessage(Session.getDefaultInstance(new Properties())); mimeMessage.setContent(mimeMultipart); mimeMessage.saveChanges(); InputStreamRequestEntity request = new InputStreamRequestEntity(mimeMessage.getInputStream()); hmethod.setRequestEntity(request); String contentTypeMtom = "multipart/related; type=\"application/xop+xml\"; start=\"" + start + "\"; start-info=\"text/xml\"; boundary=\"" + mimeMultipart.getBoundary() + "\""; Header header = new Header("Content-Type", contentTypeMtom); hmethod.addRequestHeader(header); }
From source file:org.alfresco.email.server.EmailServiceImplTest.java
/** * The Email contributors authority controls who can add email. * /*from w w w . j a v a 2 s . c o m*/ * This test switches between the EMAIL_CONTRIBUTORS group and EVERYONE */ public void testEmailContributorsAuthority() throws Exception { EmailServiceImpl emailServiceImpl = (EmailServiceImpl) emailService; folderEmailMessageHandler.setOverwriteDuplicates(true); logger.debug("Start testEmailContributorsAuthority"); String TEST_EMAIL = "buffy@sunnydale.high"; // 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.removeAuthority("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"; /** * Step 1 * Set the email contributors authority to EVERYONE * * Test that TEST_USER is allowed to send email - so even though TEST_USER is not * a contributor */ emailServiceImpl.setEmailContributorsAuthority("EVERYONE"); String from = "admin"; 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("JavaMail APIs transport.java Test"); msg.setContent(content, "text/plain"); StringBuffer sb = new StringBuffer(); ByteArrayOutputStream bos = new ByteArrayOutputStream(); msg.writeTo(bos); InputStream is = IOUtils.toInputStream(bos.toString()); assertNotNull("is is null", is); SubethaEmailMessage m = new SubethaEmailMessage(is); EmailDelivery delivery = new EmailDelivery(to, from, null); emailService.importMessage(delivery, m); /** * Step 2 * Negative test * * Send From the test user TEST_EMAIL to the test user's home */ try { logger.debug("Step 2"); emailServiceImpl.setEmailContributorsAuthority("EMAIL_CONTRIBUTORS"); emailService.importMessage(delivery, m); fail("not thrown out"); } catch (EmailMessageException e) { // Check the exception is for the anonymous user. // assertTrue(e.getMessage().contains("anonymous")); } }
From source file:net.spfbl.core.Core.java
public static synchronized boolean sendMessage(Message message, int timeout) throws Exception { if (message == null) { return false; } else if (isDirectSMTP()) { Server.logInfo("sending e-mail message."); Server.logSendMTP("authenticate: false."); Server.logSendMTP("start TLS: true."); Properties props = System.getProperties(); props.put("mail.smtp.auth", "false"); props.put("mail.smtp.port", "25"); props.put("mail.smtp.timeout", Integer.toString(timeout)); props.put("mail.smtp.connectiontimeout", "3000"); InternetAddress[] recipients = (InternetAddress[]) message.getAllRecipients(); Exception lastException = null; for (InternetAddress recipient : recipients) { String domain = Domain.normalizeHostname(recipient.getAddress(), false); for (String mx : Reverse.getMXSet(domain)) { mx = mx.substring(1);/*from w w w .j a va 2 s. c om*/ props.put("mail.smtp.starttls.enable", "true"); props.put("mail.smtp.host", mx); props.put("mail.smtp.ssl.trust", mx); InternetAddress[] recipientAlone = new InternetAddress[1]; recipientAlone[0] = (InternetAddress) recipient; Session session = Session.getDefaultInstance(props); SMTPTransport transport = (SMTPTransport) session.getTransport("smtp"); try { transport.setLocalHost(HOSTNAME); Server.logSendMTP("connecting to " + mx + ":25."); transport.connect(mx, 25, null, null); Server.logSendMTP("sending '" + message.getSubject() + "' to " + recipient + "."); transport.sendMessage(message, recipientAlone); Server.logSendMTP("message '" + message.getSubject() + "' sent to " + recipient + "."); Server.logSendMTP("last response: " + transport.getLastServerResponse()); lastException = null; break; } catch (MailConnectException ex) { Server.logSendMTP("connection failed."); lastException = ex; } catch (SendFailedException ex) { Server.logSendMTP("send failed."); throw ex; } catch (MessagingException ex) { if (ex.getMessage().contains(" TLS ")) { Server.logSendMTP("cannot establish TLS connection."); if (transport.isConnected()) { transport.close(); Server.logSendMTP("connection closed."); } Server.logInfo("sending e-mail message without TLS."); props.put("mail.smtp.starttls.enable", "false"); session = Session.getDefaultInstance(props); transport = (SMTPTransport) session.getTransport("smtp"); try { transport.setLocalHost(HOSTNAME); Server.logSendMTP("connecting to " + mx + ":25."); transport.connect(mx, 25, null, null); Server.logSendMTP("sending '" + message.getSubject() + "' to " + recipient + "."); transport.sendMessage(message, recipientAlone); Server.logSendMTP( "message '" + message.getSubject() + "' sent to " + recipient + "."); Server.logSendMTP("last response: " + transport.getLastServerResponse()); lastException = null; break; } catch (SendFailedException ex2) { Server.logSendMTP("send failed."); throw ex2; } catch (Exception ex2) { lastException = ex2; } } else { lastException = ex; } } catch (Exception ex) { Server.logError(ex); lastException = ex; } finally { if (transport.isConnected()) { transport.close(); Server.logSendMTP("connection closed."); } } } } if (lastException == null) { return true; } else { throw lastException; } } else if (hasRelaySMTP()) { Server.logInfo("sending e-mail message."); Server.logSendMTP("authenticate: " + Boolean.toString(SMTP_IS_AUTH) + "."); Server.logSendMTP("start TLS: " + Boolean.toString(SMTP_STARTTLS) + "."); Properties props = System.getProperties(); props.put("mail.smtp.auth", Boolean.toString(SMTP_IS_AUTH)); props.put("mail.smtp.starttls.enable", Boolean.toString(SMTP_STARTTLS)); props.put("mail.smtp.host", SMTP_HOST); props.put("mail.smtp.port", Short.toString(SMTP_PORT)); props.put("mail.smtp.timeout", Integer.toString(timeout)); props.put("mail.smtp.connectiontimeout", "3000"); props.put("mail.smtp.ssl.trust", SMTP_HOST); Address[] recipients = message.getAllRecipients(); TreeSet<String> recipientSet = new TreeSet<String>(); for (Address recipient : recipients) { recipientSet.add(recipient.toString()); } Session session = Session.getDefaultInstance(props); SMTPTransport transport = (SMTPTransport) session.getTransport("smtp"); try { if (HOSTNAME != null) { transport.setLocalHost(HOSTNAME); } Server.logSendMTP("connecting to " + SMTP_HOST + ":" + SMTP_PORT + "."); transport.connect(SMTP_HOST, SMTP_PORT, SMTP_USER, SMTP_PASSWORD); Server.logSendMTP("sending '" + message.getSubject() + "' to " + recipientSet + "."); transport.sendMessage(message, recipients); Server.logSendMTP("message '" + message.getSubject() + "' sent to " + recipientSet + "."); return true; } catch (SendFailedException ex) { Server.logSendMTP("send failed."); throw ex; } catch (AuthenticationFailedException ex) { Server.logSendMTP("authentication failed."); return false; } catch (MailConnectException ex) { Server.logSendMTP("connection failed."); return false; } catch (MessagingException ex) { Server.logSendMTP("messaging failed."); return false; } catch (Exception ex) { Server.logError(ex); return false; } finally { if (transport.isConnected()) { transport.close(); Server.logSendMTP("connection closed."); } } } else { return false; } }
From source file:org.socraticgrid.displaymaildata.DisplayMailDataHandler.java
/** * IN USE/*from w w w . ja v a 2s. c o m*/ * * @param request * @return * @throws Exception */ public GetMessageDetailResponseType getMessageDetail(GetMessageDetailRequestType request) throws Exception { System.out.println("===> DMD.getMessageDetail: Looking for msgId=" + request.getMessageId()); System.out.println("===> DMD.getMessageDetail: request patientId=" + request.getPatientId()); System.out.println("===> DMD.getMessageDetail: request userId=" + request.getUserId()); GetMessageDetailResponseType response = new GetMessageDetailResponseType(); IMAPFolder msgFolder = null; IMAPSSLStore sslStore = null; Properties prop = initializeMailProperties(); Session session = Session.getDefaultInstance(prop); //------------------------------------------------------------------ // When patientId is given, access must be from EMR Inbox. // Get email msgs from Patient's email account. // Else // Get email msgs from logged in user's email account. //------------------------------------------------------------------ ContactDTO contact = null; String userType = ""; String[] access = new String[2]; if (!CommonUtil.strNullorEmpty(request.getPatientId())) { contact = contactDAO.findContact("uid=" + request.getPatientId()).get(0); userType = ITEM_ID_PATIENT; } else { contact = contactDAO.findContact("uid=" + request.getUserId()).get(0); userType = ITEM_ID_PROVIDER; } access = retrieveMailAccess(contact.getCommonName(), contact.getUid()); try { session = Session.getInstance(new Properties()); URLName urlName = new URLName(mailUrl); //-------------------------------------------- //Get the sslStore and connect //-------------------------------------------- sslStore = new IMAPSSLStore(session, urlName); sslStore.connect(host, access[0], access[1]); //-------------------------------------------- // Set the originating folder. // Default to INBOX if not given. // Get and open the IMAP folder //-------------------------------------------- String folderName = null; if (CommonUtil.strNullorEmpty(request.getLocation())) { folderName = "INBOX"; } else { folderName = mapKmrLocationToImapFolder(request.getLocation(), this.host); } msgFolder = (IMAPFolder) sslStore.getFolder(folderName); msgFolder.open(Folder.READ_ONLY); //-------------------------------------------- // Find the message by the given Message-ID //-------------------------------------------- Message msg = this.findMsgByMessageId(msgFolder, request.getMessageId()); if (msg == null) { String errmsg = "Msg NOT FOUND for Message-ID=" + request.getMessageId(); System.out.println("===> getMessageDetail: " + errmsg); response.setSuccessStatus(false); response.setStatusMessage(errmsg); } else { //this.printMsgIdSubject(msg); //DBG printout System.out.println("===> getMessageDetail: Msg FOUND for Message-ID=" + request.getMessageId()); //--------------------------------------------------- // Extract "PATIENTID=" from body if present, so that // user does not see it. //--------------------------------------------------- String content = fetchMsgContent(msg); if (content.startsWith("PATIENTID=")) { Scanner scanner = new Scanner(content); boolean first = true; StringBuilder sb = new StringBuilder(); while (scanner.hasNextLine()) { if (first) { String[] parts = scanner.nextLine().split("="); response.setPatientId(parts[1]); first = false; } else { sb.append(scanner.nextLine()); } } response.getMessageDetail().add(sb.toString()); } else { response.getMessageDetail().add(content); } // Adding patientId coming from the message header. // if (msg.getHeader("X-PATIENTID") != null && // msg.getHeader("X-PATIENTID").length > 0) { // // response.setPatientId(msg.getHeader("X-PATIENT_ID")[0]); // } if (msg.getRecipients(Message.RecipientType.TO) != null) { for (Address a : msg.getRecipients(Message.RecipientType.TO)) { String contactId = getContactIdFromEmail(a.toString()); response.getSentTo().add(contactId); //System.out.println("DisplayMailDataHandler: TO="+ a.toString() +" ldap.cn="+ contactId); } } if (msg.getRecipients(Message.RecipientType.CC) != null) { for (Address a : msg.getRecipients(Message.RecipientType.CC)) { String contactId = getContactIdFromEmail(a.toString()); response.getCCTo().add(contactId); //System.out.println("DisplayMailDataHandler: CC="+ a.toString() +" ldap.cn="+ contactId); } } if (msg.getRecipients(Message.RecipientType.BCC) != null) { for (Address a : msg.getRecipients(Message.RecipientType.BCC)) { String contactId = getContactIdFromEmail(a.toString()); response.getBCCTo().add(contactId); //System.out.println("DisplayMailDataHandler: BCC="+ a.toString() +" ldap.cn="+ contactId); } } response.setSuccessStatus(true); response.setStatusMessage(""); } } catch (Exception e) { response.setSuccessStatus(false); response.setStatusMessage( "Error getting message detail for user: " + access[0] + "\n[EXCEPTION] " + e.toString()); e.printStackTrace(); } finally { if (msgFolder != null) { try { msgFolder.close(false); } catch (Exception e) { } } if (sslStore != null) { try { sslStore.close(); } catch (Exception e) { } } } return response; }
From source file:org.socraticgrid.displaymaildata.DisplayMailDataHandler.java
public SetMessageResponseType deleteMessage(SetMessageRequestType request) { SetMessageResponseType response = new SetMessageResponseType(); IMAPSSLStore sslStore = null;/*from w w w . j av a2s .com*/ Folder sourceFolder = null; Folder targetFolder = null; Properties prop = initializeMailProperties(); Session session = Session.getDefaultInstance(prop); //Get email address and password from LDAP String userId = request.getUserId(); ContactDAO contactDAO = LdapService.getContactDAO(); ContactDTO foundContact = new ContactDTO(); List<ContactDTO> contacts = contactDAO.findAllContacts(); for (ContactDTO contact : contacts) { if (contact.getUid() != null && contact.getUid().equals(request.getUserId())) { foundContact = contact; break; } } String userType = ""; String[] access = new String[2]; String userCName = foundContact.getCommonName(); if (contacts.isEmpty()) { log.error("Contact record not found for user: " + userCName); response.setMessage("Contact record not found for user: " + userCName); response.setSuccessStatus(false); return response; } access = retrieveMailAccess(userCName, foundContact.getUid()); //TMN // if (foundContact.getEmployeeNumber() != null) { // userType = ITEM_ID_PROVIDER; // access = retrieveMailAccess(userType, foundContact.getEmployeeNumber()); // } // else { // userType = ITEM_ID_PATIENT; // access = retrieveMailAccess(userType, 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; } try { //-------------------------- // Set originating folder //-------------------------- sourceFolder = getImapFolder(session, sslStore, access, this.mapKmrLocationToImapFolder(request.getLocation(), this.host)); // Is this really needed if request comes in with location=UserTrash already? if (request.getAction().equals("Undelete")) { sourceFolder = getImapFolder(session, sslStore, access, "UserTrash"); } sourceFolder.open(Folder.READ_WRITE); //-------------------------- // Set destination folder //-------------------------- if (request.getAction().equals("Delete")) { targetFolder = getImapFolder(session, sslStore, access, "UserTrash"); } if (request.getAction().equals("DeleteForever")) { targetFolder = getImapFolder(session, sslStore, access, "AdminTrash"); } else if (request.getAction().equals("Undelete")) { targetFolder = getImapFolder(session, sslStore, access, "INBOX"); } targetFolder.open(Folder.READ_WRITE); //-------------------------------------------- // Find the message by the given Message-ID //------------------------------------------- Message msg = this.findMsgByMessageId(sourceFolder, request.getMessageId()); if (msg == null) { String errmsg = "Msg NOT found for Message-ID=" + request.getMessageId(); System.out.println("===> deleteMessage: " + errmsg); response.setSuccessStatus(false); response.setMessage(errmsg); } else { //this.printMsgIdSubject(msg); //DBG printout //---------------------- //copy to new folder //---------------------- Message[] messages = new Message[] { msg }; sourceFolder.copyMessages(messages, targetFolder); //---------------------- //remove from old folder //---------------------- msg.setFlag(Flags.Flag.DELETED, true); sourceFolder.expunge(); response.setSuccessStatus(true); } } catch (Exception e) { log.error(e.getMessage()); response.setMessage("Error archiving mail with Zimbra mail server: " + e.getMessage()); response.setSuccessStatus(false); e.printStackTrace(); return response; } finally { try { sourceFolder.close(false); targetFolder.close(false); } catch (MessagingException me) { me.printStackTrace(); } } return response; }
From source file:org.socraticgrid.displaymaildata.DisplayMailDataHandler.java
/** * Opens a folder and print all msgs found. * @param folder/*from ww w. ja v a 2 s. co m*/ * @param userId * @param pwd */ void printAllMsgs(String folderName, String userId, String pwd) throws MessagingException { IMAPSSLStore sslStore = null; Properties prop = initializeMailProperties(); Session session = Session.getDefaultInstance(prop); String[] access = new String[2]; access[0] = userId; access[1] = pwd; Folder folder = getImapFolder(session, sslStore, access, folderName); folder.open(Folder.READ_WRITE); try { this.printAllMsgs(folder.getMessages()); } catch (MessagingException ex) { System.out.println("ERROR at printAllEmailMsgs."); } }