List of usage examples for javax.mail Session getInstance
public static Session getInstance(Properties props)
From source file:common.email.MailServiceImpl.java
/** * this method sends email using a given template * @param subject subject of a mail/*from ww w . j av a 2 s.c o m*/ * @param recipientEmail email receiver adress * @param mail mail text to send * @param from will be set * @return true if send succeed * @throws java.io.FileNotFoundException * @throws java.io.IOException */ protected boolean postMail(String subject, String recipientEmail, String from, String mail) throws IOException { try { Properties props = new Properties(); //props.put("mailHost", mailHost); Session session = Session.getInstance(props); // construct the message javax.mail.Message msg = new javax.mail.internet.MimeMessage(session); if (from == null) { msg.setFrom(); } else { try { msg.setFrom(new InternetAddress(from)); } catch (MessagingException ex) { logger.error(ex); } } msg.setRecipients(Message.RecipientType.TO, InternetAddress.parse(recipientEmail, false)); msg.setSubject(subject); msg.setSentDate(new Date()); //msg.setHeader("", user) msg.setDataHandler(new DataHandler(new ByteArrayDataSource(mail, "text/html; charset=UTF-8"))); SMTPTransport t = (SMTPTransport) session.getTransport("smtp"); t.connect(mailHost, user, password); Address[] a = msg.getAllRecipients(); t.sendMessage(msg, a); t.close(); return true; } catch (MessagingException ex) { logger.error(ex); ex.printStackTrace(); return false; } }
From source file:org.seedstack.seed.mail.internal.JavaMailPluginTest.java
@Test public void test_get_plugin_configuration() { configureMocks();/*w w w. j av a 2 s . c o m*/ when(applicationPlugin.getApplication().getConfiguration()) .thenReturn(new MapConfiguration(new HashMap<String, Object>() { { put("smtp", Session.getInstance(new Properties())); } })); final Configuration pluginConfiguration = mailPlugin.getPluginConfiguration(applicationPlugin); assertThat(pluginConfiguration).isNotNull(); }
From source file:lt.bsprendimai.ddesk.servlets.LocaleContextListener.java
/** * ### Method from ServletContextListener ### * * Called when a Web application is first ready to process requests * (i.e. on Web server startup and when a context is added or reloaded). * * For example, here might be database connections established * and added to the servlet context attributes. *//*from w w w. j a va 2s . c om*/ public void contextInitialized(ServletContextEvent evt) { try { Configuration.setPreferences(new Properties()); File f = new File(evt.getServletContext().getRealPath("/") + "/WEB-INF/configuration.properties") .getAbsoluteFile(); Configuration.setPropertiesFile(f); if (f.exists()) { InputStream ins = new FileInputStream(f); Configuration.getPreferences().load(ins); ins.close(); } f = new File(evt.getServletContext().getRealPath("/")); Configuration.setRootFile(f); Configuration.setMailSession(Session.getInstance(Configuration.getPreferences())); } catch (Exception excv) { excv.printStackTrace(); LogFactory.getLog(Configuration.class).error("error loading configuration ", excv); } }
From source file:com.silverpeas.mailinglist.service.job.TestZimbraConnection.java
@Test public void testOpenImapConnection() { URL url = this.getClass().getClassLoader().getResource("truststore.jks"); String path = url.getPath();/*from www .j a va 2 s . c o m*/ System.setProperty("javax.net.ssl.trustStore", path); System.setProperty("javax.net.ssl.trustStorePassword", "changeit"); Store mailAccount = null; Folder inbox = null; Session mailSession = Session.getInstance(System.getProperties()); try { mailSession.setDebug(true); mailAccount = mailSession.getStore(props.getProperty("mail.server.protocol")); mailAccount.connect(props.getProperty("mail.server.host"), Integer.parseInt(props.getProperty("mail.server.port")), props.getProperty("mail.server.login"), props.getProperty("mail.server.password")); inbox = mailAccount.getFolder("INBOX"); if (inbox == null) { throw new MessagingException("No POP3 INBOX"); } // -- Open the folder for read write -- inbox.open(Folder.READ_WRITE); // -- Get the message wrappers and process them -- Message[] msgs = inbox.getMessages(); FetchProfile profile = new FetchProfile(); profile.add(FetchProfile.Item.FLAGS); inbox.fetch(msgs, profile); } catch (MessagingException mex) { SilverTrace.error("mailingList", "MessageChecker.checkNewMessages", "mail.processing.error", mex); } catch (Exception mex) { SilverTrace.error("mailingList", "MessageChecker.checkNewMessages", "mail.processing.error", mex); } finally { // -- Close down nicely -- try { if (inbox != null) { inbox.close(false); } if (mailAccount != null) { mailAccount.close(); } } catch (Exception ex2) { SilverTrace.error("mailingList", "MessageChecker.checkNewMessages", "mail.processing.error", ex2); } } }
From source file:gsn.utils.services.EmailService.java
/** * This method send a user configured email {@link org.apache.commons.mail.Email} after having updated the * email session from the property file. * * @param email//from ww w . j a va2s. c om * @return true if the email has been sent successfully, false otherwise. * @throws org.apache.commons.mail.EmailException * */ public static void sendCustomEmail(org.apache.commons.mail.Email email) throws EmailException { email.setMailSession(Session.getInstance(Utils.loadProperties(SMTP_FILE))); email.setDebug(true); email.send(); }
From source file:com.silverpeas.mailinglist.service.job.TestYahooMailConnection.java
@Test public void testOpenImapConnection() throws Exception { Store mailAccount = null;/*w ww .ja v a 2s.c o m*/ Folder inbox = null; Session mailSession = Session.getInstance(System.getProperties()); try { mailSession.setDebug(true); mailAccount = mailSession.getStore(props.getProperty("mail.server.protocol")); mailAccount.connect(props.getProperty("mail.server.host"), Integer.parseInt(props.getProperty("mail.server.port")), props.getProperty("mail.server.login"), props.getProperty("mail.server.password")); inbox = mailAccount.getFolder("INBOX"); if (inbox == null) { throw new MessagingException("No POP3 INBOX"); } // -- Open the folder for read write -- inbox.open(Folder.READ_WRITE); // -- Get the message wrappers and process them -- javax.mail.Message[] msgs = inbox.getMessages(); FetchProfile profile = new FetchProfile(); profile.add(FetchProfile.Item.FLAGS); inbox.fetch(msgs, profile); MailProcessor processor = new MailProcessor(); MessageListener mailingList = mock(MessageListener.class); when(mailingList.checkSender(anyString())).thenReturn(Boolean.TRUE); when(mailingList.getComponentId()).thenReturn("mailingList38"); MessageEvent event = new MessageEvent(); for (javax.mail.Message message : msgs) { processor.prepareMessage((MimeMessage) message, mailingList, event); } assertThat(event.getMessages(), is(notNullValue())); assertThat(event.getMessages().size(), is(msgs.length)); for (com.silverpeas.mailinglist.service.model.beans.Message message : event.getMessages()) { assertThat(message, is(notNullValue())); assertThat(message.getMessageId(), is(notNullValue())); } } finally { // -- Close down nicely -- if (inbox != null) { inbox.close(false); } if (mailAccount != null) { mailAccount.close(); } } }
From source file:org.wso2.esb.integration.common.utils.servers.GreenMailServer.java
/** * Get the connection to a mail store/*from w w w. j av a 2 s .c o m*/ * * @param user whose mail store should be connected * @param protocol protocol used to connect * @return * @throws MessagingException when unable to connect to the store */ private static Store getConnection(GreenMailUser user, String protocol) throws MessagingException { Properties props = new Properties(); Session session = Session.getInstance(props); int port; if (PROTOCOL_POP3.equals(protocol)) { port = 3110; } else if (PROTOCOL_IMAP.equals(protocol)) { port = 3143; } else { port = 3025; props.put("mail.smtp.auth", "true"); props.put("mail.transport.protocol", "smtp"); props.put("mail.smtp.host", "localhost"); props.put("mail.smtp.port", "3025"); } URLName urlName = new URLName(protocol, BIND_ADDRESS, port, null, user.getLogin(), user.getPassword()); Store store = session.getStore(urlName); store.connect(); return store; }
From source file:org.jevis.emaildatasource.EmailForTest.java
public void testMail() throws MessagingException { List<InputStream> answerList = new ArrayList<InputStream>(); _userName = "artur.iablokov@envidatec.com"; _password = "na733aya"; _host = "imap.1und1.de"; Properties props = new Properties(); props.put("mail.debug", "true"); props.put("mail.store.protocol", "imaps"); _session = Session.getInstance(props); _store = _session.getStore();/*from w w w .j ava 2s.c o m*/ _store.connect(_host, _userName, _password); if (!_store.isConnected()) { System.out.println("Connected not possible"); } _folderName = "INBOX"; // TODO _folder = _store.getFolder(_folderName); _folder.open(Folder.READ_ONLY); System.out.println("//////////Folder open!/////"); InputStream answer = null; //channel parameter bekommen String sender = "support@jevis.de"; String subject = "testinfo"; Date lastReadout = new Date(1459658993827L); System.out.println("channel parameters: " + sender + " " + subject + " " + lastReadout); //richtige E-Mail(-s) finden SearchTerm newerThan = new ReceivedDateTerm(ComparisonTerm.GT, lastReadout); SearchTerm senderTerm = null; try { senderTerm = new FromTerm(new InternetAddress(sender)); } catch (AddressException e) { // TODO Auto-generated catch block e.printStackTrace(); } SearchTerm subjectTerm = new SubjectTerm(subject); SearchTerm andTerm = new AndTerm(newerThan, new AndTerm(senderTerm, subjectTerm)); System.out.println(andTerm.toString()); List<Message> messageList = null; try { messageList = Arrays.asList(_folder.search(andTerm)); } catch (MessagingException e) { // TODO Auto-generated catch block e.printStackTrace(); } // _folder.close(false); System.out.println("Folder closed"); _store.close(); System.out.println("Store closed"); /** * List<File> attachments = new ArrayList<File>(); for (Message message * : messageList) { try { Multipart multipart = (Multipart) * message.getContent(); for (int i = 0; i < multipart.getCount(); i++) * { BodyPart bodyPart = multipart.getBodyPart(i); if * (!Part.ATTACHMENT.equalsIgnoreCase(bodyPart.getDisposition()) && * !StringUtils.isNotBlank(bodyPart.getFileName())) { // !Checks if a * String is not empty (""), not null and not whitespace only. continue; * // dealing with attachments only } InputStream is = * bodyPart.getInputStream(); File file = new File("/tmp/" + * bodyPart.getFileName()); FileOutputStream fos = new * FileOutputStream(file); byte[] buf = new byte[4096]; int bytesRead; * while ((bytesRead = is.read(buf)) != -1) { fos.write(buf, 0, * bytesRead); } fos.close(); attachments.add(file); }* */ /*for (int i = 0; i < answerList.size(); i++) { System.out.print(answerList.get(i).toString()); }*/ }
From source file:org.modelibra.util.Emailer.java
/** * Sets an outgoing server./*from w w w. j a v a 2s . com*/ * * @param outServer * outgoing server */ public void setOutServer(String outServer) { try { this.outServer = outServer; emailProperties.put("mail.smtp.host", outServer); emailSession = Session.getInstance(emailProperties); emailStore = emailSession.getStore("pop3"); } catch (NoSuchProviderException e) { log.error("Email error : " + e.getMessage()); } }
From source file:com.adaptris.mail.MailSenderImp.java
@Override public void startSession() throws MailException { session = Session.getInstance(sessionProperties); newMessage(); }