List of usage examples for javax.mail Session getInstance
public static Session getInstance(Properties props, Authenticator authenticator)
From source file:com.stimulus.archiva.incoming.IAPRunnable.java
public void establishConnection(String protocol, String server, int port, String username, String password, Properties props) throws ArchivaException { logger.debug("establishConnection() protocol='" + protocol + "',server='" + server + "',port='" + port + "',username='" + username + "',password='********'}"); Session session = Session.getInstance(props, null); if (System.getProperty("mailarchiva.mail.debug") != null) session.setDebug(true);/* w w w. jav a 2 s . co m*/ try { logger.debug("iap connect " + props); store = session.getStore(protocol); } catch (Throwable nspe) { logger.error("failed to retrieve iap store object:" + nspe, nspe); return; } if (logger.isDebugEnabled()) { logger.debug("mailbox connection properties " + props); } try { store.connect(server, port, username, password); } catch (AuthenticationFailedException e) { logger.error("cannot connect to mail server. authentication failed {" + props + "}"); throw new ArchivaException("unable to connect to mail server. could not authenticate. {" + props + "}", e, logger); } catch (IllegalStateException ise) { throw new ArchivaException("attempt to connect mail server when it already connected. {" + props + "}", ise, logger); } catch (MessagingException me) { if (me.getMessage().contains("sun.security.validator.ValidatorException")) { throw new ArchivaException( "failed to authenticate TLS certificate. You must install the mail server's certificate as per the administration guide.", me, logger); } else if (connection.getConnectionMode() == MailboxConnections.ConnectionMode.FALLBACK && me.getMessage().contains("javax.net.ssl.SSLHandshakeException")) { logger.debug("cannot establish SSL handshake with mail server. falling back to insecure. {" + props + "}"); connection.setConnectionMode(MailboxConnections.ConnectionMode.INSECURE); } else throw new ArchivaException( "failed to connect to mail server. " + me.getMessage() + ". {" + props + "}", me, logger); } catch (Throwable e) { throw new ArchivaException("unable to connect to mail server:" + e.getMessage(), e, logger); } try { inboxFolder = store.getDefaultFolder(); } catch (Throwable e) { throw new ArchivaException("unable to get default folder. ", e, logger); } if (inboxFolder == null) { throw new ArchivaException("there was no default POP inbox folder found.", logger); } try { inboxFolder = inboxFolder.getFolder("INBOX"); if (inboxFolder == null) { throw new ArchivaException("the inbox folder does not exist.", logger); } } catch (Throwable e) { throw new ArchivaException("unable to get INBOX folder. ", e, logger); } try { inboxFolder.open(Folder.READ_WRITE); } catch (Throwable e) { throw new ArchivaException("unable to open folder. ", e, logger); } return; }
From source file:com.waveerp.sendMail.java
public String sendMsgWithAttach(String strSource, String strSourceDesc, String strSubject, String strMsg, String strDestination, String strDestDesc, String strPath) throws Exception { String strResult = "OK"; // Call the registry management system registrySystem rs = new registrySystem(); // Call the encryption management system desEncryption de = new desEncryption(); de.Encrypter("", ""); String strHost = rs.readRegistry("NA", "NA", "NA", "EMAILHOST"); String strPort = rs.readRegistry("NA", "NA", "NA", "EMAILPORT"); final String strUser = rs.readRegistry("NA", "NA", "NA", "EMAILUSER"); String strPass = rs.readRegistry("NA", "NA", "NA", "EMAILPASSWORD"); //Decrypt the encrypted password. final String strPass01 = de.decrypt(strPass); Properties props = new Properties(); props.put("mail.smtp.auth", "true"); props.put("mail.smtp.starttls.enable", "true"); props.put("mail.smtp.host", strHost); props.put("mail.smtp.port", strPort); props.put("mail.user", strUser); props.put("mail.password", strPass01); // creates a new session with an authenticator Authenticator auth = new Authenticator() { public PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication(strUser, strPass01); }/*from w ww . j a v a2 s. c o m*/ }; Session session = Session.getInstance(props, auth); // creates a new e-mail message Message msg = new MimeMessage(session); msg.setFrom(new InternetAddress(strSource)); //InternetAddress[] toAddresses = { new InternetAddress(strDestination) }; msg.setRecipient(Message.RecipientType.TO, new InternetAddress(strDestination)); msg.setSubject(strSubject); msg.setSentDate(new Date()); // creates message part MimeBodyPart messageBodyPart = new MimeBodyPart(); messageBodyPart.setContent(strMsg, "text/html"); // creates multi-part Multipart multipart = new MimeMultipart(); multipart.addBodyPart(messageBodyPart); // adds attachments //if (attachFiles != null && attachFiles.length > 0) { // for (String filePath : attachFiles) { // MimeBodyPart attachPart = new MimeBodyPart(); // // try { // attachPart.attachFile(filePath); // } catch (IOException ex) { // ex.printStackTrace(); // } // // multipart.addBodyPart(attachPart); // } //} String fna; String fnb; URL fileUrl; fileUrl = null; fileUrl = this.getClass().getResource("sendMail.class"); fna = fileUrl.getPath(); fna = fna.substring(0, fna.indexOf("WEB-INF")); //fnb = URLDecoder.decode( fna + TEMP_DIR + strPath ); fnb = URLDecoder.decode(fna + strPath); MimeBodyPart attachPart = new MimeBodyPart(); try { attachPart.attachFile(fnb); } catch (IOException ex) { //ex.printStackTrace(); strResult = ex.getMessage(); } multipart.addBodyPart(attachPart); // sets the multi-part as e-mail's content msg.setContent(multipart); // sends the e-mail Transport.send(msg); return strResult; }
From source file:edu.stanford.muse.email.ImapPopEmailStore.java
public Store connect() throws MessagingException { if (Util.nullOrEmpty(connectOptions.protocol)) // should be at least imap or pop return null; // Get a Session object // can customize javamail properties here, see e.g. http://java.sun.com/products/javamail/javadocs/com/sun/mail/imap/package-summary.html // login form will prepend the magic string xoauth, if oauth is being used String oauthToken = ""; String OAUTH_MAGIC_STRING = "xoauth"; // defined in loginform if (connectOptions.password.startsWith(OAUTH_MAGIC_STRING)) { if ("xoauth".length() < connectOptions.password.length()) { oauthToken = connectOptions.password.substring(OAUTH_MAGIC_STRING.length()); mstoreProps.put("mail.imaps.sasl.enable", "true"); mstoreProps.put("mail.imaps.sasl.mechanisms", "XOAUTH2"); mstoreProps.put(OAuth2SaslClientFactory.OAUTH_TOKEN_PROP, oauthToken); log.info("Using oauth login for store " + this); }//from ww w . ja v a 2 s .c om } session = Session.getInstance(mstoreProps, null); // session.setDebug(DEBUG); Store st = session.getStore(connectOptions.protocol); st.connect(connectOptions.server, connectOptions.port, connectOptions.userName, Util.nullOrEmpty(oauthToken) ? connectOptions.password : ""); // no password if oauth this.store = st; return st; }
From source file:au.org.paperminer.main.UserFilter.java
/** * Sends an email to the user asking they follow a link to validate their email address * @param id DB key to be embedded in response link * @param email Address target// w ww . ja va 2 s. co m */ private void sendVerificationEmail(String id, String email, ServletRequest req) { m_logger.debug("sending mail"); String from = "admin@" + m_serverName; Properties props = new Properties(); props.put("mail.smpt.host", m_serverName); props.put("mail.from", from); Session session = Session.getInstance(props, null); try { MimeMessage msg = new MimeMessage(session); msg.setRecipients(Message.RecipientType.TO, email); msg.setSubject("Verify your PaperMiner email address"); msg.setSentDate(new Date()); // FIXME: the verify address needs to be more robust msg.setText("Dear " + email.substring(0, email.indexOf("@")) + ",\n\n" + "PaperMiner has sent you this message to validate that the email address which you " + "supplied is able to receive notifications from our server.\n" + "To complete the verification process, please click the link below.\n\n" + "http://" + m_serverName + ":8080/PaperMiner/pm/vfy?id=" + id + "\n\n" + "If you are unable to click the link above, verification can be completed by copying " + "and pasting it into the address bar of your web browser.\n\n" + "Your email address is " + email + ". Use this to log in when returning to the PaperMiner site.\n" + "You can update your email address, or change your TROVE API key at any time through the " + "\"Manage Your Details\" option of the User menu, but an email change will require re-validation.\n\n" + "Paper Miner Administrator"); Transport.send(msg); m_logger.info("Verifcation mail sent to " + email); } catch (MessagingException ex) { m_logger.error("Email verification to " + email + " failed", ex); req.setAttribute(PaperMinerConstants.ERROR_PAGE, "e109"); } }
From source file:org.apache.juddi.subscription.notify.USERFRIENDLYSMTPNotifier.java
public static void notifyAccountDeleted(TemporaryMailContainer container) { try {// www .ja va 2s . c o m Publisher publisher = container.getPublisher(); Publisher deletedBy = container.getDeletedBy(); String emailaddress = publisher.getEmailAddress(); if (emailaddress == null || emailaddress.trim().equals("")) return; Properties properties = new Properties(); Session session = null; String mailPrefix = AppConfig.getConfiguration().getString(Property.JUDDI_EMAIL_PREFIX, Property.DEFAULT_JUDDI_EMAIL_PREFIX); if (!mailPrefix.endsWith(".")) { mailPrefix = mailPrefix + "."; } for (String key : mailProps) { if (AppConfig.getConfiguration().containsKey(mailPrefix + key)) { properties.put(key, AppConfig.getConfiguration().getProperty(mailPrefix + key)); } else if (System.getProperty(mailPrefix + key) != null) { properties.put(key, System.getProperty(mailPrefix + key)); } } boolean auth = (properties.getProperty("mail.smtp.auth", "false")).equalsIgnoreCase("true"); if (auth) { final String username = properties.getProperty("mail.smtp.user"); String pwd = properties.getProperty("mail.smtp.password"); //decrypt if possible if (properties.getProperty("mail.smtp.password" + Property.ENCRYPTED_ATTRIBUTE, "false") .equalsIgnoreCase("true")) { try { pwd = CryptorFactory.getCryptor().decrypt(pwd); } catch (NoSuchPaddingException ex) { log.error("Unable to decrypt settings", ex); } catch (NoSuchAlgorithmException ex) { log.error("Unable to decrypt settings", ex); } catch (InvalidAlgorithmParameterException ex) { log.error("Unable to decrypt settings", ex); } catch (InvalidKeyException ex) { log.error("Unable to decrypt settings", ex); } catch (IllegalBlockSizeException ex) { log.error("Unable to decrypt settings", ex); } catch (BadPaddingException ex) { log.error("Unable to decrypt settings", ex); } } final String password = pwd; log.debug("SMTP username = " + username + " from address = " + emailaddress); Properties eMailProperties = properties; eMailProperties.remove("mail.smtp.user"); eMailProperties.remove("mail.smtp.password"); session = Session.getInstance(properties, new javax.mail.Authenticator() { protected PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication(username, password); } }); } else { Properties eMailProperties = properties; eMailProperties.remove("mail.smtp.user"); eMailProperties.remove("mail.smtp.password"); session = Session.getInstance(eMailProperties); } MimeMessage message = new MimeMessage(session); InternetAddress address = new InternetAddress(emailaddress); Address[] to = { address }; message.setRecipients(RecipientType.TO, to); message.setFrom(new InternetAddress(properties.getProperty("mail.smtp.from", "jUDDI"))); //Hello %s,<br><br>Your subscription UDDI subscription was deleted. Attached is what the subscription was. It was deleted by %s, %s at %s. This node is %s Multipart mp = new MimeMultipart(); MimeBodyPart content = new MimeBodyPart(); String msg_content = ResourceConfig.getGlobalMessage("notifications.smtp.accountDeleted"); SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd kk:mm:ssZ"); //Hello %s, %s,<br><br>Your account has been deleted by %s, %s at %s. This node is %s. msg_content = String.format(msg_content, StringEscapeUtils.escapeHtml(publisher.getPublisherName()), StringEscapeUtils.escapeHtml(publisher.getAuthorizedName()), StringEscapeUtils.escapeHtml(deletedBy.getPublisherName()), StringEscapeUtils.escapeHtml(deletedBy.getAuthorizedName()), StringEscapeUtils.escapeHtml(sdf.format(new Date())), StringEscapeUtils.escapeHtml( AppConfig.getConfiguration().getString(Property.JUDDI_NODE_ID, "(unknown node id!)")), AppConfig.getConfiguration().getString(Property.JUDDI_BASE_URL, "(unknown url)"), AppConfig.getConfiguration().getString(Property.JUDDI_BASE_URL_SECURE, "(unknown url)")); content.setContent(msg_content, "text/html; charset=UTF-8;"); mp.addBodyPart(content); message.setContent(mp); message.setSubject(ResourceConfig.getGlobalMessage("notifications.smtp.accountDeleted.subject")); Transport.send(message); } catch (Throwable t) { log.warn("Error sending email!" + t.getMessage()); log.debug("Error sending email!" + t.getMessage(), t); } }
From source file:org.sakaiproject.tool.assessment.util.SamigoEmailService.java
public String sendMail() { try {//from w w w. ja va 2s . c o m Properties props = new Properties(); // Server if (smtpServer == null || smtpServer.equals("")) { log.info("samigo.email.smtpServer is not set"); smtpServer = ServerConfigurationService.getString("smtp@org.sakaiproject.email.api.EmailService"); if (smtpServer == null || smtpServer.equals("")) { log.info("smtp@org.sakaiproject.email.api.EmailService is not set"); log.error( "Please set the value of samigo.email.smtpServer or smtp@org.sakaiproject.email.api.EmailService"); return "error"; } } props.setProperty("mail.smtp.host", smtpServer); // Port if (smtpPort == null || smtpPort.equals("")) { log.warn("samigo.email.smtpPort is not set. The default port 25 will be used."); } else { props.setProperty("mail.smtp.port", smtpPort); } props.put("mail.smtp.sendpartial", "true"); Session session = Session.getInstance(props, null); session.setDebug(true); MimeMessage msg = new MimeMessage(session); InternetAddress fromIA = new InternetAddress(fromEmailAddress, fromName); msg.setFrom(fromIA); //msg.addHeaderLine("Subject: " + subject); msg.setSubject(subject, "UTF-8"); String noReplyEmaillAddress = ServerConfigurationService.getString("setup.request", "no-reply@" + ServerConfigurationService.getServerName()); msg.addHeaderLine("To: " + noReplyEmaillAddress); msg.setText(message, "UTF-8"); msg.addHeaderLine("Content-Type: text/html"); ArrayList<InternetAddress> toIAList = new ArrayList<InternetAddress>(); String email = ""; Iterator iter = toEmailAddressList.iterator(); while (iter.hasNext()) { try { email = (String) iter.next(); toIAList.add(new InternetAddress(email)); } catch (AddressException ae) { log.error("invalid email address: " + email); } } InternetAddress[] toIA = new InternetAddress[toIAList.size()]; int count = 0; Iterator iter2 = toIAList.iterator(); while (iter2.hasNext()) { toIA[count++] = (InternetAddress) iter2.next(); } try { Transport transport = session.getTransport("smtp"); msg.saveChanges(); transport.connect(); try { transport.sendMessage(msg, toIA); } catch (SendFailedException e) { log.debug("SendFailedException: " + e); return "error"; } catch (MessagingException e) { log.warn("1st MessagingException: " + e); return "error"; } transport.close(); } catch (MessagingException e) { log.warn("2nd MessagingException:" + e); return "error"; } } catch (UnsupportedEncodingException ue) { log.warn("UnsupportedEncodingException:" + ue); ue.printStackTrace(); } catch (MessagingException me) { log.warn("3rd MessagingException:" + me); return "error"; } return "send"; }
From source file:com.youxifan.utils.EMail.java
/** * Send Mail direct//w ww.ja v a 2 s. c om * @return OK or error message */ public String send() { log.info("(" + m_smtpHost + ") " + m_from + " -> " + m_to); m_sentMsg = null; // if (!isValid(true)) { m_sentMsg = "Invalid Data"; return m_sentMsg; } // Properties props = System.getProperties(); props.put("mail.store.protocol", "smtp"); props.put("mail.transport.protocol", "smtp"); props.put("mail.host", m_smtpHost); // Bit-Florin David props.put("mail.smtp.port", String.valueOf(m_smtpPort)); // TLS settings if (m_isSmtpTLS) { props.put("mail.smtp.starttls.enable", "true"); props.put("mail.smtp.socketFactory.port", String.valueOf(m_smtpPort)); props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory"); props.put("mail.smtp.socketFactory.fallback", "false"); } // Session session = null; try { if (m_auth != null) // createAuthenticator was called props.put("mail.smtp.auth", "true"); // if (m_smtpHost.equalsIgnoreCase("smtp.gmail.com")) { // // TODO: make it configurable // // Enable gmail port and ttls - Hardcoded // props.put("mail.smtp.port", "587"); // props.put("mail.smtp.starttls.enable", "true"); // } session = Session.getInstance(props, m_auth); } catch (SecurityException se) { log.warn("Auth=" + m_auth + " - " + se.toString()); m_sentMsg = se.toString(); return se.toString(); } catch (Exception e) { log.warn("Auth=" + m_auth, e); m_sentMsg = e.toString(); return e.toString(); } try { // m_msg = new MimeMessage(session); m_msg = new SMTPMessage(session); // Addresses m_msg.setFrom(m_from); InternetAddress[] rec = getTos(); if (rec.length == 1) m_msg.setRecipient(Message.RecipientType.TO, rec[0]); else m_msg.setRecipients(Message.RecipientType.TO, rec); rec = getCcs(); if (rec != null && rec.length > 0) m_msg.setRecipients(Message.RecipientType.CC, rec); rec = getBccs(); if (rec != null && rec.length > 0) m_msg.setRecipients(Message.RecipientType.BCC, rec); if (m_replyTo != null) m_msg.setReplyTo(new Address[] { m_replyTo }); // m_msg.setSentDate(new java.util.Date()); m_msg.setHeader("Comments", "Becit Mail"); m_msg.setHeader("Comments", "Becit ERP Mail"); // m_msg.setDescription("Description"); // SMTP specifics m_msg.setAllow8bitMIME(true); // Send notification on Failure & Success - no way to set envid in Java yet // m_msg.setNotifyOptions (SMTPMessage.NOTIFY_FAILURE | SMTPMessage.NOTIFY_SUCCESS); // Bounce only header m_msg.setReturnOption(SMTPMessage.RETURN_HDRS); // m_msg.setHeader("X-Mailer", "msgsend"); // setContent(); m_msg.saveChanges(); // log.fine("message =" + m_msg); // // Transport.send(msg); Transport t = session.getTransport("smtp"); // log.fine("transport=" + t); t.connect(); // t.connect(m_smtpHost, user, password); // log.fine("transport connected"); Transport.send(m_msg); // t.sendMessage(msg, msg.getAllRecipients()); log.info("Success - MessageID=" + m_msg.getMessageID()); } catch (MessagingException me) { Exception ex = me; StringBuffer sb = new StringBuffer("(ME)"); boolean printed = false; do { if (ex instanceof SendFailedException) { SendFailedException sfex = (SendFailedException) ex; Address[] invalid = sfex.getInvalidAddresses(); if (!printed) { if (invalid != null && invalid.length > 0) { sb.append(" - Invalid:"); for (int i = 0; i < invalid.length; i++) sb.append(" ").append(invalid[i]); } Address[] validUnsent = sfex.getValidUnsentAddresses(); if (validUnsent != null && validUnsent.length > 0) { sb.append(" - ValidUnsent:"); for (int i = 0; i < validUnsent.length; i++) sb.append(" ").append(validUnsent[i]); } Address[] validSent = sfex.getValidSentAddresses(); if (validSent != null && validSent.length > 0) { sb.append(" - ValidSent:"); for (int i = 0; i < validSent.length; i++) sb.append(" ").append(validSent[i]); } printed = true; } if (sfex.getNextException() == null) sb.append(" ").append(sfex.getLocalizedMessage()); } else if (ex instanceof AuthenticationFailedException) { sb.append(" - Invalid Username/Password - " + m_auth); } else // other MessagingException { String msg = ex.getLocalizedMessage(); if (msg == null) sb.append(": ").append(ex.toString()); else { if (msg.indexOf("Could not connect to SMTP host:") != -1) { int index = msg.indexOf('\n'); if (index != -1) msg = msg.substring(0, index); String cc = "??"; msg += " - AD_Client_ID=" + cc; } String className = ex.getClass().getName(); if (className.indexOf("MessagingException") != -1) sb.append(": ").append(msg); else sb.append(" ").append(className).append(": ").append(msg); } } // Next Exception if (ex instanceof MessagingException) ex = ((MessagingException) ex).getNextException(); else ex = null; } while (ex != null); // error loop m_sentMsg = sb.toString(); return sb.toString(); } catch (Exception e) { log.warn("", e); m_sentMsg = e.getLocalizedMessage(); return e.getLocalizedMessage(); } // m_sentMsg = SENT_OK; return m_sentMsg; }
From source file:org.georchestra.console.ws.emails.EmailController.java
/** * Send an email based on json payload. Recipient should be present in LDAP directory or in configured whitelist. * * Json sent should have following keys : * * - to : json array of email to send email to ex: ["you@rm.fr", "another-guy@rm.fr"] * - cc : json array of email to 'CC' email ex: ["him@rm.fr"] * - bcc : json array of email to add recipient as blind CC ["secret@rm.fr"] * - subject : subject of email/*from ww w .ja v a 2 s . co m*/ * - body : Body of email * * Either 'to', 'cc' or 'bcc' parameter must be present in request. 'subject' and 'body' are mandatory. * * complete json example : * * { * "to": ["you@rm.fr", "another-guy@rm.fr"], * "cc": ["him@rm.fr"], * "bcc": ["secret@rm.fr"], * "subject": "test email", * "body": "Hi, this a test EMail, please do not reply." * } * */ @RequestMapping(value = "/emailProxy", method = RequestMethod.POST, produces = "application/json; charset=utf-8", consumes = "application/json") @ResponseBody public String emailProxy(@RequestBody String rawRequest, HttpServletRequest request) throws JSONException, MessagingException, UnsupportedEncodingException, DataServiceException { JSONObject payload = new JSONObject(rawRequest); InternetAddress[] to = this.populateRecipient("to", payload); InternetAddress[] cc = this.populateRecipient("cc", payload); InternetAddress[] bcc = this.populateRecipient("bcc", payload); this.checkSubject(payload); this.checkBody(payload); this.checkRecipient(to, cc, bcc); LOG.info("EMail request : user=" + request.getHeader("sec-username") + " to=" + this.extractAddress("to", payload) + " cc=" + this.extractAddress("cc", payload) + " bcc=" + this.extractAddress("bcc", payload) + " roles=" + request.getHeader("sec-roles")); LOG.debug("EMail request : " + payload.toString()); // Instanciate MimeMessage final Session session = Session.getInstance(System.getProperties(), null); session.getProperties().setProperty("mail.smtp.host", this.emailFactory.getSmtpHost()); session.getProperties().setProperty("mail.smtp.port", (new Integer(this.emailFactory.getSmtpPort())).toString()); MimeMessage message = new MimeMessage(session); // Generate From header InternetAddress from = new InternetAddress(); from.setAddress(this.georConfig.getProperty("emailProxyFromAddress")); from.setPersonal(request.getHeader("sec-firstname") + " " + request.getHeader("sec-lastname")); message.setFrom(from); // Generate Reply-to header InternetAddress replyTo = new InternetAddress(); replyTo.setAddress(request.getHeader("sec-email")); replyTo.setPersonal(request.getHeader("sec-firstname") + " " + request.getHeader("sec-lastname")); message.setReplyTo(new Address[] { replyTo }); // Generate to, cc and bcc headers if (to.length > 0) message.setRecipients(Message.RecipientType.TO, to); if (cc.length > 0) message.setRecipients(Message.RecipientType.CC, cc); if (bcc.length > 0) message.setRecipients(Message.RecipientType.BCC, bcc); // Add subject and body message.setSubject(payload.getString("subject"), "UTF-8"); message.setText(payload.getString("body"), "UTF-8", "plain"); message.setSentDate(new Date()); // finally send message Transport.send(message); JSONObject res = new JSONObject(); res.put("success", true); return res.toString(); }
From source file:be.ibridge.kettle.job.entry.getpop.JobEntryGetPOP.java
public Result execute(Result prev_result, int nr, Repository rep, Job parentJob) { LogWriter log = LogWriter.getInstance(); Result result = new Result(nr); result.setResult(false);//from w w w .j a v a 2s .c om result.setNrErrors(1); FileObject fileObject = null; //Get system properties //Properties prop = System.getProperties(); Properties prop = new Properties(); //Create session object //Session sess = Session.getDefaultInstance(prop,null); Session sess = Session.getInstance(prop, null); sess.setDebug(true); try { int nbrmailtoretrieve = Const.toInt(firstmails, 0); fileObject = KettleVFS.getFileObject(getRealOutputDirectory()); // Check if output folder exists if (!fileObject.exists()) { log.logError(toString(), Messages.getString("JobGetMailsFromPOP.FolderNotExists1.Label") + getRealOutputDirectory() + Messages.getString("JobGetMailsFromPOP.FolderNotExists2.Label")); } else { String host = getRealServername(); String user = getRealUsername(); String pwd = getRealPassword(); Store st = null; if (!getUseSSL()) { //Create POP3 object st = sess.getStore("pop3"); // Try to connect to the server st.connect(host, user, pwd); } else { // Ssupports POP3 connection with SSL, the connection is established via SSL. String SSL_FACTORY = "javax.net.ssl.SSLSocketFactory"; //Properties pop3Props = new Properties(); prop.setProperty("mail.pop3.socketFactory.class", SSL_FACTORY); prop.setProperty("mail.pop3.socketFactory.fallback", "false"); prop.setProperty("mail.pop3.port", getRealSSLPort()); prop.setProperty("mail.pop3.socketFactory.port", getRealSSLPort()); URLName url = new URLName("pop3", host, Const.toInt(getRealSSLPort(), 995), "", user, pwd); st = new POP3SSLStore(sess, url); st.connect(); } log.logDetailed(toString(), Messages.getString("JobGetMailsFromPOP.LoggedWithUser.Label") + user); //Open default folder INBOX Folder f = st.getFolder("INBOX"); f.open(Folder.READ_ONLY); if (f == null) { log.logError(toString(), Messages.getString("JobGetMailsFromPOP.InvalidFolder.Label")); } else { log.logDetailed(toString(), Messages.getString("JobGetMailsFromPOP.TotalMessagesFolder1.Label") + f.getName() + Messages.getString("JobGetMailsFromPOP.TotalMessagesFolder2.Label") + f.getMessageCount()); log.logDetailed(toString(), Messages.getString("JobGetMailsFromPOP.TotalNewMessagesFolder1.Label") + f.getName() + Messages.getString("JobGetMailsFromPOP.TotalNewMessagesFolder2.Label") + f.getNewMessageCount()); // Get emails Message msg_list[] = getPOPMessages(f, retrievemails); if (msg_list.length > 0) { List current_file_POP = new ArrayList(); List current_filepath_POP = new ArrayList(); int nb_email_POP = 1; DateFormat dateFormat = new SimpleDateFormat("hhmmss_mmddyyyy"); String startpattern = "name"; if (!Const.isEmpty(getRealFilenamePattern())) { startpattern = getRealFilenamePattern(); } for (int i = 0; i < msg_list.length; i++) { /*if(msg[i].isMimeType("text/plain")) { log.logDetailed(toString(), "Expediteur: "+msg[i].getFrom()[0]); log.logDetailed(toString(), "Sujet: "+msg[i].getSubject()); log.logDetailed(toString(), "Texte: "+(String)msg[i].getContent()); }*/ if ((nb_email_POP <= nbrmailtoretrieve && retrievemails == 2) || (retrievemails != 2)) { Message msg_POP = msg_list[i]; log.logDetailed(toString(), Messages.getString("JobGetMailsFromPOP.EmailFrom.Label") + msg_list[i].getFrom()[0]); log.logDetailed(toString(), Messages.getString("JobGetMailsFromPOP.EmailSubject.Label") + msg_list[i].getSubject()); String localfilename_message = startpattern + "_" + dateFormat.format(new Date()) + "_" + (i + 1) + ".mail"; log.logDetailed(toString(), Messages.getString("JobGetMailsFromPOP.LocalFilename1.Label") + localfilename_message + Messages.getString("JobGetMailsFromPOP.LocalFilename2.Label")); File filename_message = new File(getRealOutputDirectory(), localfilename_message); OutputStream os_filename = new FileOutputStream(filename_message); Enumeration enums_POP = msg_POP.getAllHeaders(); while (enums_POP.hasMoreElements()) { Header header_POP = (Header) enums_POP.nextElement(); os_filename.write(new StringBuffer(header_POP.getName()).append(": ") .append(header_POP.getValue()).append("\r\n").toString().getBytes()); } os_filename.write("\r\n".getBytes()); InputStream in_POP = msg_POP.getInputStream(); byte[] buffer_POP = new byte[1024]; int length_POP = 0; while ((length_POP = in_POP.read(buffer_POP, 0, 1024)) != -1) { os_filename.write(buffer_POP, 0, length_POP); } os_filename.close(); nb_email_POP++; current_file_POP.add(filename_message); current_filepath_POP.add(filename_message.getPath()); if (delete) { log.logDetailed(toString(), Messages.getString("JobGetMailsFromPOP.DeleteEmail.Label")); msg_POP.setFlag(javax.mail.Flags.Flag.DELETED, true); } } } } // Close and exit if (f != null) f.close(false); if (st != null) st.close(); f = null; st = null; sess = null; result.setNrErrors(0); result.setResult(true); } } } catch (NoSuchProviderException e) { log.logError(toString(), "provider error: " + e.getMessage()); } catch (MessagingException e) { log.logError(toString(), "Message error: " + e.getMessage()); } catch (Exception e) { log.logError(toString(), "Inexpected error: " + e.getMessage()); } finally { if (fileObject != null) { try { fileObject.close(); } catch (IOException ex) { } ; } sess = null; } return result; }
From source file:org.xwiki.contrib.mail.internal.DefaultMailReader.java
private Session createSession(final String protocol, final Properties additionalProperties, final boolean isGmail, final boolean autoTrustSsl) { // Get a session. Use a blank Properties object. Properties props = new Properties(additionalProperties); // necessary to work with Gmail if (isGmail && !props.containsKey("mail.imap.partialfetch") && !props.containsKey("mail.imaps.partialfetch")) { props.put("mail.imap.partialfetch", "false"); props.put("mail.imaps.partialfetch", "false"); }//w w w. j a v a 2 s . com props.put("mail.store.protocol", protocol); // TODO set this as an option (auto-trust certificates for SSL) props.put("mail.imap.ssl.checkserveridentity", "false"); props.put("mail.imaps.ssl.trust", "*"); /* * MailSSLSocketFactory socketFactory = new MailSSLSocketFactory(); socketFactory.setTrustAllHosts(true); * props.put("mail.imaps.ssl.socketFactory", socketFactory); */ Session session = Session.getInstance(props, null); session.setDebug(true); return session; }