Java Examples for javax.mail.AuthenticationFailedException

The following java examples will help you to understand the usage of javax.mail.AuthenticationFailedException. These source code samples are taken from different open source projects.

Example 1
Project: axelor-business-suite-master  File: MailAccountServiceImpl.java View source code
@Override
public void checkMailAccountConfiguration(MailAccount mailAccount) throws AxelorException, Exception {
    String port = mailAccount.getPort() <= 0 ? null : mailAccount.getPort().toString();
    SmtpAccount smtpAccount = new SmtpAccount(mailAccount.getHost(), port, mailAccount.getLogin(), mailAccount.getPassword(), getSmtpSecurity(mailAccount));
    smtpAccount.setConnectionTimeout(CHECK_CONF_TIMEOUT);
    Session session = smtpAccount.getSession();
    try {
        Transport transport = session.getTransport(getProtocol(mailAccount));
        transport.connect(mailAccount.getHost(), mailAccount.getPort(), mailAccount.getLogin(), mailAccount.getPassword());
        transport.close();
    } catch (AuthenticationFailedException e) {
        throw new AxelorException(I18n.get(IExceptionMessage.MAIL_ACCOUNT_1), e, IException.CONFIGURATION_ERROR);
    } catch (NoSuchProviderException e) {
        throw new AxelorException(I18n.get(IExceptionMessage.MAIL_ACCOUNT_2), e, IException.CONFIGURATION_ERROR);
    }
}
Example 2
Project: cyrille-leclerc-master  File: ImapTester.java View source code
public void testExternalMailbox(String user, String password) {
    try {
        Session s = openSession();
        Store store = s.getStore();
        store.connect(this.IMAP_SERVER_HOST, this.IMAP_SERVER_PORT, user, password);
        Folder defaultFolder = store.getDefaultFolder();
        Folder folder = defaultFolder.getFolder("INBOX");
        int messageCount = folder.getMessageCount();
        if (messageCount == 0) {
            log.error("No message in external mailbox INBOX for " + user);
            StressTestUtils.incrementProgressBarFailure();
        } else {
            // log.debug(user + " INBOX(" + messageCount + ")");
            StressTestUtils.incrementProgressBarSuccess();
        }
    } catch (AuthenticationFailedException afe) {
        log.error("Authentication failed with user=" + user + ", password=" + password);
    } catch (Exception e) {
        log.error("Exception with user=" + user + ", password=" + password + " : " + e.toString(), e);
    }
}
Example 3
Project: nuxeo-master  File: MailEventListener.java View source code
public void doHandleEvent(Event event) {
    try (CoreSession coreSession = CoreInstance.openCoreSession(null)) {
        StringBuilder query = new StringBuilder();
        query.append("SELECT * FROM MailFolder ");
        query.append(String.format(" WHERE ecm:currentLifeCycleState != '%s' ", LifeCycleConstants.DELETED_STATE));
        query.append(" AND ecm:isProxy = 0 ");
        DocumentModelList mailFolderList = coreSession.query(query.toString());
        for (DocumentModel currentMailFolder : mailFolderList) {
            try {
                MailCoreHelper.checkMail(currentMailFolder, coreSession);
            } catch (AuthenticationFailedException e) {
                log.warn("Error connecting to email account", e);
                continue;
            }
        }
    } catch (MessagingException e) {
        log.error("MailEventListener error...", e);
    }
}
Example 4
Project: openmonitor-android-agent-master  File: ServicePOP3.java View source code
/**
	 * Returns an POP3 Response String.
	 * 
	 *	 	                           	                          		             	            
	           
	@return      String	 
	 *
	 
	@see Session
	 *
	
	@see Store
	 */
@Override
public String connect() {
    if (Constants.DEBUG_MODE)
        System.out.println("Inside ServicePOP3.connect() ---------------------------");
    Properties properties = new Properties();
    properties.setProperty("mail.pop3.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
    properties.setProperty("mail.pop3.socketFactory.fallback", "false");
    properties.setProperty("mail.pop3.port", "995");
    properties.setProperty("mail.pop3.socketFactory.port", "995");
    URLName urlName = new URLName("pop3", this.getService().getIp(), this.getService().getPort(), "", "umiticmmobile", "umiticmmobile2011");
    Session session = Session.getInstance(properties, null);
    Store store = new POP3SSLStore(session, urlName);
    try {
        store.connect();
        if (store.isConnected()) {
            store.close();
            return "normal";
        }
    } catch (AuthenticationFailedException e) {
        return "normal";
    } catch (MessagingException e) {
        e.printStackTrace();
    }
    return "blocked";
}
Example 5
Project: wonder-master  File: ERMailSender.java View source code
/**
	 * <div class="en">
	 * Don't call this method, this is the thread run loop and is automatically called.
	 * </div>
	 * 
	 * <div class="ja">
	 * ã?“ã?®ãƒ¡ã‚½ãƒƒãƒ‰ã‚’コールã?—ã?ªã?„ã?§ã??ã? ã?•ã?„。
	 * �れ�スレッド実行ループ�自動的�処��れ��。
	 * </div>
	 */
public void run() {
    try {
        while (true) {
            synchronized (_messages) {
                while (_messages.empty()) {
                    _messages.wait(_milliSecondsWaitRunLoop);
                }
            }
            // If there are still messages pending ...
            if (!_messages.empty()) {
                Map<String, Transport> transports = new HashMap<>();
                try {
                    while (!_messages.empty()) {
                        ERMessage message = _messages.pop();
                        String contextString = message.contextString();
                        String smtpProtocol = ERJavaMail.sharedInstance().smtpProtocolForContext(contextString);
                        if (contextString == null) {
                            contextString = "___DEFAULT___";
                        }
                        Transport transport = transports.get(contextString);
                        if (transport == null) {
                            Session session = ERJavaMail.sharedInstance().newSessionForMessage(message);
                            try {
                                transport = _connectedTransportForSession(session, smtpProtocol, true);
                            } catch (MessagingException e) {
                                message._deliveryFailed(e);
                                throw e;
                            }
                            transports.put(contextString, transport);
                        }
                        try {
                            if (!transport.isConnected()) {
                                transport.connect();
                            }
                        } catch (MessagingException e) {
                            log.error("Unable to connect transport.", e);
                            message._deliveryFailed(e);
                            throw new RuntimeException("Unable to connect transport.", e);
                        }
                        try {
                            _sendMessageNow(message, transport);
                        } catch (SendFailedException ex) {
                            log.error("Can't send message: {}", message, ex);
                        }
                    // if (useSenderDelay) {
                    //     wait (senderDelayMillis);
                    // }
                    // Here we get all the exceptions that are
                    // not 'SendFailedException's.
                    // All we can do is warn the admin.
                    }
                } catch (AuthenticationFailedException e) {
                    log.error("Unable to connect to SMTP Transport. AuthenticationFailedException: {} waiting 20 seconds", e.getMessage(), e);
                    Thread.sleep(20000);
                } catch (MessagingException e) {
                    if (e.getNextException() instanceof ConnectException) {
                        log.error("Can't connect to mail server, waiting");
                        Thread.sleep(10000);
                    } else if (e.getNextException() instanceof UnknownHostException) {
                        log.error("Can't find to mail server, exiting");
                        return;
                    } else {
                        log.error("General mail error.", e);
                    }
                } finally {
                    for (Transport transport : transports.values()) {
                        try {
                            if (transport != null) {
                                transport.close();
                            }
                        } catch (/* once again ... */
                        MessagingException e) {
                            log.warn("Unable to close transport.  Perhaps it has already been closed?", e);
                        }
                    }
                }
            }
        }
    } catch (InterruptedException e) {
        log.warn("ERMailSender thread has been interrupted.");
    }
    // assures the thread will get restarted next time around.
    _senderThread = null;
}
Example 6
Project: zava-master  File: MailSender.java View source code
/**
	 * 
	 * @param mailBean
	 */
public int sendMail(MailBean mailBean) throws IOException, MessagingException {
    Properties props = System.getProperties();
    props.put("mail.smtp.host", mailBean.getSMTPHost());
    props.put("mail.smtp.port", mailBean.getSMTPPort() == null ? 25 : mailBean.getSMTPPort());
    if (mailBean.isNeedAuth()) {
        props.put("mail.smtp.auth", "true");
    } else {
        props.put("mail.smtp.auth", "false");
    }
    MailAuth auth = new MailAuth();
    Session session = Session.getInstance(props, auth);
    Transport transport = null;
    try {
        transport = session.getTransport("smtp");
    } catch (NoSuchProviderException e1) {
        e1.printStackTrace();
    }
    MimeMessage mime = new MimeMessage(session);
    Address[] addresses = new Address[1];
    Message msg = null;
    try {
        mime.setSubject(mailBean.getSubject());
        mime.setContent(mailBean.getMsgContent(), mailBean.getMessageContentMimeType());
        msg = new SMTPMessage(mime);
        addresses[0] = new InternetAddress(mailBean.getMailTo());
    } catch (MessagingException e1) {
        e1.printStackTrace();
    }
    try {
        if (mailBean.isNeedAuth()) {
            transport.connect(mailBean.getMailFrom(), mailBean.getMailPass());
        } else {
            transport.connect();
        }
        transport.sendMessage(msg, addresses);
        LOG.info("Send Mail To : " + mailBean.getMailTo() + " Successfully!");
    } catch (AuthenticationFailedException e) {
        LOG.error("Authentication failed for mail sender.");
        return -1;
    } catch (MessagingException e) {
        LOG.error(e.getMessage());
        return -1;
    } finally {
        transport.close();
    }
    return 0;
}
Example 7
Project: zen-project-master  File: SmtpSender.java View source code
public void sendMessage(MimeMessage mimeMessage) throws IOException {
    try {
        Transport transport = getSession().getTransport("smtp");
        transport.connect(host, port, username, password);
        try {
            if (mimeMessage.getSentDate() == null) {
                mimeMessage.setSentDate(new Date());
            }
            String messageId = mimeMessage.getMessageID();
            mimeMessage.saveChanges();
            if (messageId != null) {
                mimeMessage.setHeader("Message-ID", messageId);
            }
            transport.sendMessage(mimeMessage, mimeMessage.getAllRecipients());
        } finally {
            transport.close();
        }
    } catch (AuthenticationFailedException ex) {
        throw new IOException(ex);
    } catch (MessagingException ex) {
        throw new IOException(ex);
    }
}
Example 8
Project: ambari-master  File: EmailDispatcher.java View source code
/**
   * {@inheritDoc}
   */
@Override
public TargetConfigurationResult validateTargetConfig(Map<String, Object> properties) {
    try {
        Transport transport = getMailTransport(properties);
        transport.connect();
        transport.close();
    } catch (AuthenticationFailedException e) {
        LOG.debug("Invalid credentials. Authentication failure.", e);
        return TargetConfigurationResult.invalid("Invalid credentials. Authentication failure: " + e.getMessage());
    } catch (MessagingException e) {
        LOG.debug("Invalid config.", e);
        return TargetConfigurationResult.invalid("Invalid config: " + e.getMessage());
    }
    return TargetConfigurationResult.valid();
}
Example 9
Project: Auto-B-Day-master  File: GoogleMailManager.java View source code
/**
	 * send a mail with any credentials.
	 *
	 * @param username
	 * @param password
	 * @param subject
	 * @param message
	 * @param to
	 * @throws FailedToSendMailException
	 * @throws FailedToLoadPropertiesException
	 * @throws Exception
	 */
protected void sendUserMailInternal(String username, String password, String subject, String message, String to) throws FailedToSendMailException, FailedToLoadPropertiesException, Exception {
    Properties systemProps = null;
    try {
        //DONT CHANGE THIS PATH
        systemProps = propLoader.loadSystemProperty("/SystemMail.properties");
        //systemProps
        String host = systemProps.getProperty("mail.smtp.host");
        //Obtain the default mail session
        Session session = Session.getDefaultInstance(systemProps, null);
        session.setDebug(true);
        //Construct the mail message
        MimeMessage mail = new MimeMessage(session);
        mail.setText(message);
        mail.setSubject(subject);
        mail.setFrom(new InternetAddress(username));
        mail.addRecipient(RecipientType.TO, new InternetAddress(to));
        mail.saveChanges();
        //Use Transport to deliver the message
        Transport transport = session.getTransport("smtp");
        transport.connect(host, username, password);
        transport.sendMessage(mail, mail.getAllRecipients());
        transport.close();
    } catch (AuthenticationFailedException ex) {
        LOGGER.log(Level.SEVERE, null, ex);
        throw new FailedToSendMailException("Authentication-Error. Please check your credentials.");
    } catch (IOException ex) {
        LOGGER.log(Level.SEVERE, null, ex);
        throw new FailedToLoadPropertiesException("Failed to load mail properties.");
    } catch (Exception ex) {
        LOGGER.log(Level.SEVERE, null, ex);
        throw new FailedToSendMailException("Failed to send mail.");
    }
}
Example 10
Project: code.java-master  File: Mail.java View source code
private static void postMail(String[] recipients, String[] replyTo, String subject, String message, String fromEmail, boolean htmlMail) throws MessagingException, AuthenticationFailedException {
    boolean debug = false;
    Properties props = new Properties();
    // use this to prevent the [MessagingException: 501 Syntax: HELO hostname]
    props.put("mail.smtp.localhost", SMTP_HOST_NAME);
    props.put("mail.smtp.host", SMTP_HOST_NAME);
    props.put("mail.smtp.auth", "true");
    Authenticator auth = new SMTPAuthenticator(SMTP_AUTH_USER, SMTP_AUTH_PWD);
    // use Session.getInstance instead of Session.getDefaultInstance to 
    // get rid of [SecurityException: Access to default session denied]
    Session session = Session.getInstance(props, auth);
    session.setDebug(debug);
    // create a message
    Message msg = new MimeMessage(session);
    // check and set the from
    if (fromEmail == null)
        fromEmail = SMTP_SEND_FROM;
    InternetAddress addressFrom = new InternetAddress(fromEmail);
    msg.setFrom(addressFrom);
    // set recipients
    InternetAddress[] addressTo = new InternetAddress[recipients.length];
    for (int i = 0; i < recipients.length; i++) addressTo[i] = new InternetAddress(recipients[i]);
    msg.setRecipients(Message.RecipientType.TO, addressTo);
    // check and set reply-to
    if (replyTo != null && replyTo.length > 0) {
        Address[] replyToAddresses = new Address[replyTo.length];
        for (int i = 0; i < replyTo.length; i++) replyToAddresses[i] = new InternetAddress(replyTo[i]);
        msg.setReplyTo(replyToAddresses);
    }
    // Setting the Subject and Content Type
    msg.setSubject(subject);
    msg.setContent(message, htmlMail ? "text/html;charset=utf-8" : "text/plain;charset=utf-8");
    // send mail
    Transport.send(msg);
}
Example 11
Project: javamail4android-master  File: SMTPSaslLoginTest.java View source code
@Test
public void testFailure() {
    TestServer server = null;
    try {
        server = new TestServer(new SMTPSaslHandler());
        server.start();
        Thread.sleep(1000);
        Properties properties = new Properties();
        properties.setProperty("mail.smtp.host", "localhost");
        properties.setProperty("mail.smtp.port", "" + server.getPort());
        properties.setProperty("mail.smtp.sasl.enable", "true");
        properties.setProperty("mail.smtp.sasl.mechanisms", "DIGEST-MD5");
        properties.setProperty("mail.smtp.auth.digest-md5.disable", "true");
        //properties.setProperty("mail.debug.auth", "true");
        Session session = Session.getInstance(properties);
        //session.setDebug(true);
        Transport t = session.getTransport("smtp");
        try {
            t.connect("test", "xtest");
            // should have failed
            fail("wrong password succeeded");
        } catch (AuthenticationFailedException ex) {
        } catch (Exception ex) {
            fail(ex.toString());
        } finally {
            t.close();
        }
    } catch (Exception e) {
        e.printStackTrace();
        fail(e.getMessage());
    } finally {
        if (server != null) {
            server.quit();
            server.interrupt();
        }
    }
}
Example 12
Project: jentrata-msh-master  File: SmtpMail.java View source code
/**
	 * Attempts to connect the smtp transport object. Use -1 for the default
	 * port, and null for the default values from the session.
	 * 
	 * @throws SmtpMailException
	 * 
	 * @throws MessagingException
	 */
public void transportConnect(String host, int port, String password, String username) throws SmtpMailException {
    try {
        transport.connect(host, port, password, username);
    } catch (AuthenticationFailedException e) {
        throw new SmtpMailException("Authentication failed when connecting to SMTP server.", e);
    } catch (IllegalStateException e) {
        throw new SmtpMailException("Service is alread connected.", e);
    } catch (MessagingException e) {
        throw new SmtpMailException("Could not connect to the SMTP server.", e);
    }
}
Example 13
Project: maven-h2o-master  File: SmtpMail.java View source code
/**
	 * Attempts to connect the smtp transport object. Use -1 for the default
	 * port, and null for the default values from the session.
	 * 
	 * @throws SmtpMailException
	 * 
	 * @throws MessagingException
	 */
public void transportConnect(String host, int port, String password, String username) throws SmtpMailException {
    try {
        transport.connect(host, port, password, username);
    } catch (AuthenticationFailedException e) {
        throw new SmtpMailException("Authentication failed when connecting to SMTP server.", e);
    } catch (IllegalStateException e) {
        throw new SmtpMailException("Service is alread connected.", e);
    } catch (MessagingException e) {
        throw new SmtpMailException("Could not connect to the SMTP server.", e);
    }
}
Example 14
Project: opencms-core-master  File: CmsSimpleMail.java View source code
/**
     * Overrides to add a better message for authentication exception.<p>
     * 
     * @see org.apache.commons.mail.Email#send()
     */
@Override
public String send() {
    String messageID = null;
    try {
        messageID = super.send();
    } catch (EmailException e) {
        if (e.getCause() instanceof AuthenticationFailedException) {
            CmsMailHost host = OpenCms.getSystemInfo().getMailSettings().getDefaultMailHost();
            CmsRuntimeException rte = new CmsRuntimeException(Messages.get().container(Messages.ERR_SEND_EMAIL_AUTHENTICATE_2, host.getUsername(), host.getHostname()));
            rte.initCause(e);
            throw rte;
        } else {
            CmsRuntimeException rte = new CmsRuntimeException(Messages.get().container(Messages.ERR_SEND_EMAIL_CONFIG_0));
            rte.initCause(e);
            throw rte;
        }
    }
    return messageID;
}
Example 15
Project: opencms-master  File: CmsSimpleMail.java View source code
/**
     * Overrides to add a better message for authentication exception.<p>
     * 
     * @see org.apache.commons.mail.Email#send()
     */
@Override
public String send() {
    String messageID = null;
    try {
        messageID = super.send();
    } catch (EmailException e) {
        if (e.getCause() instanceof AuthenticationFailedException) {
            CmsMailHost host = OpenCms.getSystemInfo().getMailSettings().getDefaultMailHost();
            CmsRuntimeException rte = new CmsRuntimeException(Messages.get().container(Messages.ERR_SEND_EMAIL_AUTHENTICATE_2, host.getUsername(), host.getHostname()));
            rte.initCause(e);
            throw rte;
        } else {
            CmsRuntimeException rte = new CmsRuntimeException(Messages.get().container(Messages.ERR_SEND_EMAIL_CONFIG_0));
            rte.initCause(e);
            throw rte;
        }
    }
    return messageID;
}
Example 16
Project: sling-master  File: SimpleMailServiceIT.java View source code
@Test
public void sendWithoutAuthentication() throws Exception {
    final Dictionary<String, Object> properties = MailBuilderConfigurations.minimal();
    createFactoryConfiguration(FACTORY_PID, properties);
    final MessageService messageService = getService(MessageService.class);
    final CompletableFuture<Result> future = messageService.send("simple test message", "recipient@example.net");
    try {
        future.get();
    } catch (Exception e) {
        logger.info(e.getMessage(), e);
        assertTrue(ExceptionUtils.getRootCause(e) instanceof AuthenticationFailedException);
    }
}
Example 17
Project: sonews-master  File: MailPoller.java View source code
@Override
public void run() {
    Log.get().info("Starting Mailinglist Poller...");
    int errors = 0;
    while (daemon.isRunning()) {
        try {
            // Wait some time between runs. At the beginning has advantages,
            // because the wait is not skipped if an exception occurs.
            // one minute * errors
            Thread.sleep(60000 * (errors + 1));
            final String host = Config.inst().get(Config.MLPOLL_HOST, "samplehost");
            final String username = Config.inst().get(Config.MLPOLL_USER, "user");
            final String password = Config.inst().get(Config.MLPOLL_PASSWORD, "mysecret");
            // Create empty properties
            Properties props = System.getProperties();
            props.put("mail.pop3.host", host);
            props.put("mail.mime.address.strict", "false");
            // Get session
            Session session = Session.getInstance(props);
            // Get the store
            Store store = session.getStore("pop3");
            store.connect(host, 110, username, password);
            // Get folder
            Folder folder = store.getFolder("INBOX");
            folder.open(Folder.READ_WRITE);
            // Get directory
            Message[] messages = folder.getMessages();
            // Dispatch messages and delete it afterwards on the inbox
            for (Message message : messages) {
                if (Dispatcher.toGroup(message) || Config.inst().get(Config.MLPOLL_DELETEUNKNOWN, false)) {
                    // Delete the message
                    message.setFlag(Flag.DELETED, true);
                }
            }
            // Close connection
            // true to expunge deleted messages
            folder.close(true);
            store.close();
            errors = 0;
        } catch (NoSuchProviderException ex) {
            Log.get().severe(ex.toString());
            daemon.requestShutdown();
        } catch (AuthenticationFailedException ex) {
            ex.printStackTrace();
            errors = errors < 5 ? errors + 1 : errors;
        } catch (InterruptedException ex) {
            System.out.println("sonews: " + this + " returns: " + ex);
            return;
        } catch (MessagingException ex) {
            ex.printStackTrace();
            errors = errors < 5 ? errors + 1 : errors;
        } catch (Exception ex) {
            ex.printStackTrace();
            errors = errors < 5 ? errors + 1 : errors;
        }
    }
    Log.get().severe("MailPoller exited.");
}
Example 18
Project: rce-master  File: MailServiceImpl.java View source code
/**
         * We need to decide if it worth to attempt a new delivery or if the failure indicates a permanent error like a configuration
         * mistake. For this purpose this method evaluates the cause of a MailExeption.
         * 
         * @param e MailExeption whose cause should be analyzed.
         * @return True in case of an configuration error; False, otherwise.
         */
private boolean isMailExceptionCausedByPermError(MailException e) {
    Throwable cause = e.getCause();
    if (cause != null) {
        // this check is used instead of instanceof to be sure to only match MessagingExceptions and not its subclasses
        if ((cause.getClass().equals(MessagingException.class) && !(cause.getMessage().equals(CAN_T_SEND_COMMAND_TO_SMTP_HOST))) || // AuthenticationFailedException extends MessagingException
        cause instanceof AuthenticationFailedException) {
            // configuration error
            return true;
        }
    }
    // no configuration error
    return false;
}
Example 19
Project: AribaWeb-Framework-master  File: MailMonitor.java View source code
public static Store connect(Properties loginParams) throws AuthenticationFailedException {
    initialize(loginParams);
    ProgressMonitor.instance().prepare("Connecting to mail server...", 0);
    String protocol = (String) loginParams.get(ProtocolProperty);
    Store store = null;
    try {
        store = session.getStore(protocol);
        String host = (String) loginParams.get(Fmt.S("mail.%s.host", protocol));
        String userName = (String) loginParams.get("mail.username");
        String password = (String) loginParams.get("mail.password");
        store.connect(host, userName, password);
    } catch (MessagingException e) {
        throw new AWGenericException(e);
    }
    return store;
}
Example 20
Project: bi-platform-v2-master  File: EmailComponent.java View source code
@Override
public boolean executeAction() {
    EmailAction emailAction = (EmailAction) getActionDefinition();
    String messagePlain = emailAction.getMessagePlain().getStringValue();
    String messageHtml = emailAction.getMessageHtml().getStringValue();
    String subject = emailAction.getSubject().getStringValue();
    String to = emailAction.getTo().getStringValue();
    String cc = emailAction.getCc().getStringValue();
    String bcc = emailAction.getBcc().getStringValue();
    String from = emailAction.getFrom().getStringValue(defaultFrom);
    if (from.trim().length() == 0) {
        from = defaultFrom;
    }
    if (ComponentBase.debug) {
        //$NON-NLS-1$
        debug(Messages.getInstance().getString("Email.DEBUG_TO_FROM", to, from));
        //$NON-NLS-1$
        debug(Messages.getInstance().getString("Email.DEBUG_CC_BCC", cc, bcc));
        //$NON-NLS-1$
        debug(Messages.getInstance().getString("Email.DEBUG_SUBJECT", subject));
        //$NON-NLS-1$
        debug(Messages.getInstance().getString("Email.DEBUG_PLAIN_MESSAGE", messagePlain));
        //$NON-NLS-1$
        debug(Messages.getInstance().getString("Email.DEBUG_HTML_MESSAGE", messageHtml));
    }
    if ((to == null) || (to.trim().length() == 0)) {
        // Get the output stream that the feedback is going into
        OutputStream feedbackStream = getFeedbackOutputStream();
        if (feedbackStream != null) {
            //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
            createFeedbackParameter("to", Messages.getInstance().getString("Email.USER_ENTER_EMAIL_ADDRESS"), "", "", true);
            //$NON-NLS-1$
            setFeedbackMimeType("text/html");
            return true;
        } else {
            return false;
        }
    }
    if (subject == null) {
        //$NON-NLS-1$
        error(Messages.getInstance().getErrorString("Email.ERROR_0005_NULL_SUBJECT", getActionName()));
        return false;
    }
    if ((messagePlain == null) && (messageHtml == null)) {
        //$NON-NLS-1$
        error(Messages.getInstance().getErrorString("Email.ERROR_0006_NULL_BODY", getActionName()));
        return false;
    }
    if (getRuntimeContext().isPromptPending()) {
        return true;
    }
    try {
        Properties props = new Properties();
        try {
            Document configDocument = PentahoSystem.getSystemSettings().getSystemSettingsDocument(//$NON-NLS-1$
            "smtp-email/email_config.xml");
            //$NON-NLS-1$
            List properties = configDocument.selectNodes("/email-smtp/properties/*");
            Iterator propertyIterator = properties.iterator();
            while (propertyIterator.hasNext()) {
                Node propertyNode = (Node) propertyIterator.next();
                String propertyName = propertyNode.getName();
                String propertyValue = propertyNode.getText();
                props.put(propertyName, propertyValue);
            }
        } catch (Exception e) {
            error(Messages.getInstance().getString("Email.ERROR_0013_CONFIG_FILE_INVALID"), e);
            return false;
        }
        //$NON-NLS-1$//$NON-NLS-2$
        boolean authenticate = "true".equalsIgnoreCase(props.getProperty("mail.smtp.auth"));
        // Get a Session object
        Session session;
        if (authenticate) {
            Authenticator authenticator = new EmailAuthenticator();
            session = Session.getInstance(props, authenticator);
        } else {
            session = Session.getInstance(props);
        }
        // component debug setting
        if (ComponentBase.debug && !props.containsKey("mail.debug")) {
            //$NON-NLS-1$
            session.setDebug(true);
        }
        // construct the message
        MimeMessage msg = new MimeMessage(session);
        if (from != null) {
            msg.setFrom(new InternetAddress(from));
        } else {
            // There should be no way to get here
            //$NON-NLS-1$
            error(Messages.getInstance().getString("Email.ERROR_0012_FROM_NOT_DEFINED"));
        }
        if ((to != null) && (to.trim().length() > 0)) {
            msg.setRecipients(Message.RecipientType.TO, InternetAddress.parse(to, false));
        }
        if ((cc != null) && (cc.trim().length() > 0)) {
            msg.setRecipients(Message.RecipientType.CC, InternetAddress.parse(cc, false));
        }
        if ((bcc != null) && (bcc.trim().length() > 0)) {
            msg.setRecipients(Message.RecipientType.BCC, InternetAddress.parse(bcc, false));
        }
        if (subject != null) {
            msg.setSubject(subject, LocaleHelper.getSystemEncoding());
        }
        EmailAttachment[] emailAttachments = emailAction.getAttachments();
        if ((messagePlain != null) && (messageHtml == null) && (emailAttachments.length == 0)) {
            msg.setText(messagePlain, LocaleHelper.getSystemEncoding());
        } else if (emailAttachments.length == 0) {
            if (messagePlain != null) {
                //$NON-NLS-1$          
                msg.setContent(messagePlain, "text/plain; charset=" + LocaleHelper.getSystemEncoding());
            }
            if (messageHtml != null) {
                //$NON-NLS-1$
                msg.setContent(messageHtml, "text/html; charset=" + LocaleHelper.getSystemEncoding());
            }
        } else {
            // need to create a multi-part message...
            // create the Multipart and add its parts to it
            Multipart multipart = new MimeMultipart();
            // create and fill the first message part
            if (messageHtml != null) {
                // create and fill the first message part
                MimeBodyPart htmlBodyPart = new MimeBodyPart();
                //$NON-NLS-1$
                htmlBodyPart.setContent(messageHtml, "text/html; charset=" + LocaleHelper.getSystemEncoding());
                multipart.addBodyPart(htmlBodyPart);
            }
            if (messagePlain != null) {
                MimeBodyPart textBodyPart = new MimeBodyPart();
                //$NON-NLS-1$
                textBodyPart.setContent(messagePlain, "text/plain; charset=" + LocaleHelper.getSystemEncoding());
                multipart.addBodyPart(textBodyPart);
            }
            for (EmailAttachment element : emailAttachments) {
                IPentahoStreamSource source = element.getContent();
                if (source == null) {
                    //$NON-NLS-1$
                    error(Messages.getInstance().getErrorString("Email.ERROR_0015_ATTACHMENT_FAILED"));
                    return false;
                }
                DataSource dataSource = new ActivationHelper.PentahoStreamSourceWrapper(source);
                String attachmentName = element.getName();
                if (ComponentBase.debug) {
                    //$NON-NLS-1$
                    debug(Messages.getInstance().getString("Email.DEBUG_ADDING_ATTACHMENT", attachmentName));
                }
                // create the second message part
                MimeBodyPart attachmentBodyPart = new MimeBodyPart();
                // attach the file to the message
                attachmentBodyPart.setDataHandler(new DataHandler(dataSource));
                attachmentBodyPart.setFileName(attachmentName);
                if (ComponentBase.debug) {
                    //$NON-NLS-1$
                    debug(Messages.getInstance().getString("Email.DEBUG_ATTACHMENT_SOURCE", dataSource.getName()));
                }
                multipart.addBodyPart(attachmentBodyPart);
            }
            // add the Multipart to the message
            msg.setContent(multipart);
        }
        //$NON-NLS-1$
        msg.setHeader("X-Mailer", EmailComponent.MAILER);
        msg.setSentDate(new Date());
        Transport.send(msg);
        if (ComponentBase.debug) {
            //$NON-NLS-1$
            debug(Messages.getInstance().getString("Email.DEBUG_EMAIL_SUCCESS"));
        }
        return true;
    // TODO: persist the content set for a while...
    } catch (SendFailedException e) {
        error(Messages.getInstance().getErrorString("Email.ERROR_0011_SEND_FAILED", to), e);
    } catch (AuthenticationFailedException e) {
        error(Messages.getInstance().getString("Email.ERROR_0014_AUTHENTICATION_FAILED", to), e);
    } catch (Throwable e) {
        error(Messages.getInstance().getErrorString("Email.ERROR_0011_SEND_FAILED", to), e);
    }
    return false;
}
Example 21
Project: cocoon-master  File: IMAPGenerator.java View source code
public void generate() throws SAXException, ProcessingException {
    try {
        Session sess = Session.getDefaultInstance(this.props, null);
        Store st = sess.getStore("imap");
        log("Connecting to IMAP server @ " + this.host);
        st.connect(this.host, this.user, this.pass);
        log("Attempting to open default folder");
        Folder f = st.getFolder("inbox");
        f.open(Folder.READ_WRITE);
        log("Downloading message list from folder");
        this.message = f.getMessages();
        int i = 0;
        log("Starting XML generation");
        this.contentHandler.startDocument();
        this.contentHandler.startPrefixMapping(PREFIX, URI);
        start("imap", XMLUtils.EMPTY_ATTRIBUTES);
        start("messages", XMLUtils.EMPTY_ATTRIBUTES);
        for (i = 0; i < this.message.length; i++) {
            // Loop through the messages and output XML.
            // TODO: actually use the attributes...
            start("msg", XMLUtils.EMPTY_ATTRIBUTES);
            start("subject", XMLUtils.EMPTY_ATTRIBUTES);
            data(this.message[i].getSubject());
            end("subject");
            start("from", XMLUtils.EMPTY_ATTRIBUTES);
            data(this.message[i].getFrom()[0].toString());
            end("from");
            start("sentDate", XMLUtils.EMPTY_ATTRIBUTES);
            data(this.message[i].getSentDate().toString());
            end("sentDate");
            start("num", XMLUtils.EMPTY_ATTRIBUTES);
            data(Integer.toString(this.message[i].getMessageNumber()));
            end("num");
            end("msg");
        }
        end("messages");
        end("imap");
        this.contentHandler.endPrefixMapping(PREFIX);
        this.contentHandler.endDocument();
        log("Finished generating XML");
    } catch (AuthenticationFailedException afe) {
        throw new ProcessingException("Failed to authenticate with the IMAP server.");
    } catch (Exception e) {
        throw new ProcessingException(e.toString());
    }
}
Example 22
Project: crash-master  File: MailPlugin.java View source code
public Boolean call() throws Exception {
    Properties props = new Properties();
    props.setProperty("mail.smtp.host", smtpHost);
    if (smtpPort != null) {
        props.setProperty("mail.smtp.port", Integer.toString(smtpPort));
    }
    //
    final String username = smtpUsername, password = smtpPassword;
    Authenticator authenticator;
    if (username != null && password != null) {
        props.setProperty("mail.smtp.auth", "true");
        authenticator = new Authenticator() {

            @Override
            protected PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication(username, password);
            }
        };
    } else {
        authenticator = null;
    }
    //
    if (Boolean.TRUE.equals(debug)) {
        props.setProperty("mail.debug", "true");
    }
    //
    if (smtpSecure != null) {
        switch(smtpSecure) {
            case NONE:
                break;
            case TLS:
                props.setProperty("mail.smtp.starttls.enable", "true");
                break;
            case SSL:
                throw new UnsupportedOperationException();
        }
    }
    //
    Session session = Session.getInstance(props, authenticator);
    MimeMessage message = new MimeMessage(session);
    //
    if (smtpFrom != null) {
        message.setFrom(new InternetAddress(smtpFrom));
    }
    //
    message.setRecipients(Message.RecipientType.TO, addresses);
    if (subject != null) {
        message.setSubject(subject);
    }
    //
    MimePart bodyPart;
    if (attachments != null && attachments.length > 0) {
        Multipart multipart = new MimeMultipart();
        bodyPart = new MimeBodyPart();
        bodyPart.setContent(body, type);
        for (DataSource attachment : attachments) {
            MimeBodyPart attachmentPart = new MimeBodyPart();
            attachmentPart.setDataHandler(new DataHandler(attachment));
            attachmentPart.setFileName(attachment.getName());
            multipart.addBodyPart(attachmentPart);
        }
        message.setContent(multipart);
    } else {
        bodyPart = message;
    }
    //
    if (type != null) {
        bodyPart.setContent(body, type);
    } else {
        bodyPart.setText(body.toString());
    }
    //
    try {
        Transport.send(message);
    } catch (AuthenticationFailedException e) {
        return false;
    }
    return true;
}
Example 23
Project: echo2-master  File: EmailApp.java View source code
/**
     * Connects to the mail server with the given e-mail address and
     * password.   Displays the <code>MailScreen</code> on success.
     *
     * @param emailAddress e-mail address 
     * @param password the password
     * @return true if the application was able to connect to the
     *         server using the specified information, false if not.
     */
public boolean connect(String emailAddress, String password) {
    Properties properties = System.getProperties();
    if (!FAUX_MODE) {
        properties.put("mail.smtp.host", SEND_MAIL_SERVER);
        properties.put("mail.smtp.port", SEND_MAIL_PORT);
    }
    try {
        mailSession = Session.getDefaultInstance(properties, null);
        store = mailSession.getStore(RECEIVE_PROTOCOL);
        store.connect(RECEIVE_MAIL_SERVER, emailAddress, password);
        // Store user name.
        this.emailAddress = emailAddress;
        // Display MailScreen.
        MailScreen mailScreen = new MailScreen();
        mailScreen.setStore(store);
        getDefaultWindow().setContent(mailScreen);
    } catch (AuthenticationFailedException ex) {
        return false;
    } catch (MessagingException ex) {
        processFatalException(ex);
    }
    // Return indicating that the user was successfully authenticated.
    return true;
}
Example 24
Project: elexis-3-core-master  File: MailClient.java View source code
private void handleException(MessagingException e) {
    if (e instanceof AuthenticationFailedException) {
        lastError = ErrorTyp.AUTHENTICATION;
    } else if (e.getNextException() instanceof UnknownHostException) {
        lastError = ErrorTyp.CONNECTION;
    } else if (e instanceof AddressException) {
        lastError = ErrorTyp.ADDRESS;
    }
}
Example 25
Project: hipergate-master  File: SessionHandler.java View source code
// sendMessage
// ---------------------------------------------------------------------------
/**
   * <p>Get a list of all folder messages which are not deleted</p>
   * Messages are returned in ascending date order, oldest messages are returned first
   * @param sFolderName Folder Name, for example: "INBOX"
   * @return An array of strings with format
   * <msg>
   * <num>[1..n]</num>
   * <id>message unique identifier</id>
   * <type>message content-type</type>
   * <disposition>message content-disposition</disposition>
   * <len>message length in bytes</len>
   * <priority>X-Priority header</priority>
   * <spam>X-Spam-Flag header</spam>
   * <subject><![CDATA[message subject]]></subject>
   * <sent>yyy-mm-dd hh:mi:ss</sent>
   * <received>yyy-mm-dd hh:mi:ss</received>
   * <from><![CDATA[personal name of sender]]></from>
   * <to><![CDATA[personal name or e-mail of receiver]]></to>
   * <size>integer size in kilobytes</size>
   * <err>error description (if any)</err>
   * </msg>
   * @throws AuthenticationFailedException
   * @throws NoSuchProviderException
   * @throws MessagingException
   * @since 4.0
   */
public String[] listFolderMessages(String sFolderName) throws AuthenticationFailedException, NoSuchProviderException, MessagingException {
    Chronometer oChMeter = null;
    if (DebugFile.trace) {
        DebugFile.writeln("Begin SessionHandler.listFolderMessages(" + sFolderName + ")");
        DebugFile.incIdent();
        oChMeter = new Chronometer();
    }
    HeadersHelper oHlpr = new HeadersHelper();
    String[] aMsgsXml = null;
    if (DebugFile.trace)
        DebugFile.writeln("getting " + sFolderName + " folder");
    Folder oFldr = getFolder(sFolderName);
    if (DebugFile.trace)
        DebugFile.writeln("opening " + sFolderName + " folder");
    oFldr.open(Folder.READ_ONLY);
    if (DebugFile.trace)
        DebugFile.writeln(sFolderName + " opened in read only mode");
    Message[] aMsgsObj = oFldr.getMessages();
    int iTotalCount = 0;
    if (null != aMsgsObj)
        iTotalCount = aMsgsObj.length;
    int iDeleted = 0;
    if (iTotalCount > 0) {
        if (DebugFile.trace)
            DebugFile.writeln("Folder.getMessages(" + String.valueOf(iTotalCount) + ")");
        FetchProfile oFtchPrfl = new FetchProfile();
        oFtchPrfl.add(FetchProfile.Item.ENVELOPE);
        oFtchPrfl.add(FetchProfile.Item.CONTENT_INFO);
        oFtchPrfl.add(FetchProfile.Item.FLAGS);
        oFtchPrfl.add("X-Priority");
        oFtchPrfl.add("X-Spam-Flag");
        if (DebugFile.trace) {
            DebugFile.writeln("Folder.fetch(Message[], ENVELOPE & CONTENT_INFO & FLAGS)");
            oChMeter.start();
        }
        oFldr.fetch(aMsgsObj, oFtchPrfl);
        if (DebugFile.trace) {
            DebugFile.writeln(String.valueOf(iTotalCount) + " headers fetched in " + String.valueOf(oChMeter.stop() / 1000l) + " seconds");
            oChMeter.start();
        }
        aMsgsXml = new String[iTotalCount];
        for (int m = 0; m < iTotalCount; m++) {
            if (aMsgsObj[m].isSet(Flags.Flag.DELETED)) {
                iDeleted++;
            } else {
                oHlpr.setMessage((MimeMessage) aMsgsObj[m]);
                aMsgsXml[m - iDeleted] = oHlpr.toXML();
            }
        // fi
        }
        // next (m)
        aMsgsObj = null;
        if (iDeleted > 0)
            aMsgsXml = Arrays.copyOfRange(aMsgsXml, 0, iTotalCount - iDeleted);
        if (DebugFile.trace) {
            DebugFile.writeln(String.valueOf(iTotalCount - iDeleted) + " messages to XML in " + String.valueOf(oChMeter.stop()) + " ms");
        }
    } else {
        if (DebugFile.trace)
            DebugFile.writeln("No messages found at folder " + sFolderName);
    }
    // fi (iTotalCount>0)
    oFldr.close(false);
    if (DebugFile.trace) {
        DebugFile.writeln(String.valueOf(iTotalCount) + " messages fetched in " + String.valueOf(oChMeter.stop() / 1000l) + " seconds");
        DebugFile.decIdent();
        if (null == aMsgsXml)
            DebugFile.writeln("End SessionHandler.listFolderMessages() : 0");
        else
            DebugFile.writeln("End SessionHandler.listFolderMessages() : " + String.valueOf(aMsgsXml.length));
    }
    return aMsgsXml;
}
Example 26
Project: loklak_server-master  File: InstallationPageService.java View source code
@Override
public JSONObject serviceImpl(Query post, HttpServletResponse response, Authorization authorization, final JSONObjectWithDefault permissions) throws APIException {
    JSONObject result = new JSONObject();
    if (post.get("finish", false)) {
        LoklakInstallation.shutdown(0);
        return null;
    }
    if (post.get("abort", false)) {
        LoklakInstallation.shutdown(1);
        return null;
    }
    if (post.get("checkSmtpCredentials", false)) {
        String smtpHostName = post.get("smtpHostName", null);
        String smtpUsername = post.get("smtpUsername", null);
        String smtpPassword = post.get("smtpPassword", null);
        String smtpHostEncryption = post.get("smtpHostEncryption", null);
        int smtpHostPort = post.get("smtpHostPort", 0);
        boolean smtpDisableCertificateChecking = post.get("smtpDisableCertificateChecking", false);
        if (smtpHostName == null || smtpHostEncryption == null || smtpUsername == null || smtpPassword == null) {
            throw new APIException(400, "Bad request");
        }
        try {
            LoklakEmailHandler.checkConnection(smtpHostName, smtpUsername, smtpPassword, smtpHostEncryption, smtpHostPort, smtpDisableCertificateChecking);
            return result;
        } catch (AuthenticationFailedException e) {
            throw new APIException(422, e.getMessage());
        } catch (Throwable e) {
            throw new APIException(400, e.getMessage());
        }
    }
    // read from file
    Properties properties = new Properties();
    try {
        BufferedInputStream stream = new BufferedInputStream(new FileInputStream(customConfigPath));
        properties.load(stream);
        stream.close();
    } catch (Exception e) {
        throw new APIException(500, "Server error");
    }
    // admin
    String adminEmail = post.get("adminEmail", null);
    String adminPassword = post.get("adminPassword", null);
    if (adminEmail != null && adminPassword != null) {
        // check email pattern
        Pattern pattern = Pattern.compile(LoklakEmailHandler.EMAIL_PATTERN);
        if (!pattern.matcher(adminEmail).matches()) {
            throw new APIException(400, "no valid email address");
        }
        // check password pattern
        pattern = Pattern.compile("^(?=.*\\d)(?=.*[a-z])(?=.*[A-Z]).{8,64}$");
        if (adminEmail.equals(adminPassword) || !pattern.matcher(adminPassword).matches()) {
            throw new APIException(400, "invalid password");
        }
        // check if id exists already
        ClientCredential credential = new ClientCredential(ClientCredential.Type.passwd_login, adminEmail);
        Authentication authentication = new Authentication(credential, DAO.authentication);
        if (authentication.getIdentity() != null) {
            throw new APIException(422, "email already taken");
        }
        // create new id
        ClientIdentity identity = new ClientIdentity(ClientIdentity.Type.email, credential.getName());
        authentication.setIdentity(identity);
        // set authentication details
        String salt = createRandomString(20);
        authentication.put("salt", salt);
        authentication.put("passwordHash", getHash(adminPassword, salt));
        authentication.put("activated", true);
        // set authorization details
        Authorization adminAuthorization = new Authorization(identity, DAO.authorization, DAO.userRoles);
        adminAuthorization.setUserRole(DAO.userRoles.getDefaultUserRole(BaseUserRole.ADMIN));
        result.put("admin_email", adminEmail);
    }
    String adminLocalOnly = post.get("adminLocalOnly", null);
    if ("true".equals(adminLocalOnly) || "false".equals(adminLocalOnly))
        properties.setProperty("users.admin.localonly", adminLocalOnly);
    // peername
    String peerName = post.get("peername", null);
    if (peerName != null)
        properties.setProperty("peername", peerName);
    // backend
    String backendPushEnabled = post.get("backendPushEnabled", null);
    if ("true".equals(backendPushEnabled) || "false".equals(backendPushEnabled))
        properties.setProperty("backend.push.enabled", backendPushEnabled);
    String backend = post.get("backend", null);
    if (backend != null)
        properties.setProperty("backend", backend);
    // cert checking
    String trustSelfSignedCerts = post.get("trustSelfSignedCerts", null);
    if (trustSelfSignedCerts != null)
        properties.setProperty("httpsclient.trustselfsignedcerts", trustSelfSignedCerts);
    // https setting
    String httpsMode = post.get("httpsMode", null);
    if (httpsMode != null)
        properties.setProperty("https.mode", httpsMode);
    String httpsKeySource = post.get("httpsKeySource", null);
    if (httpsKeySource != null)
        properties.setProperty("https.keysource", httpsKeySource);
    String httpsKeystore = post.get("httpsKeystore", null);
    if (httpsKeystore != null)
        properties.setProperty("keystore.name", httpsKeystore);
    String httpsKeystorePassword = post.get("httpsKeystorePassword", null);
    if (httpsKeystorePassword != null)
        properties.setProperty("keystore.password", httpsKeystorePassword);
    String httpsKey = post.get("httpsKey", null);
    if (httpsKey != null)
        properties.setProperty("https.key", httpsKey);
    String httpsCert = post.get("httpsCert", null);
    if (httpsCert != null)
        properties.setProperty("https.cert", httpsCert);
    // smtp
    String smtpEnabled = post.get("smtpEnabled", null);
    if ("true".equals(smtpEnabled) || "false".equals(smtpEnabled))
        properties.setProperty("smtp.mails.enabled", smtpEnabled);
    String smtpHostName = post.get("smtpHostName", null);
    if (smtpHostName != null)
        properties.setProperty("smtp.host.name", smtpHostName);
    Integer smtpHostPort = post.get("smtpHostPort", 0);
    if (smtpHostPort > 0 && smtpHostPort < 65535)
        properties.setProperty("smtp.host.port", smtpHostPort.toString());
    String smtpHostEncryption = post.get("smtpHostEncryption", null);
    if ("none".equals(smtpHostEncryption) || "tls".equals(smtpHostEncryption) || "starttls".equals(smtpHostEncryption))
        properties.setProperty("smtp.host.encryption", smtpHostEncryption);
    String smtpEmail = post.get("smtpEmail", null);
    if (smtpEmail != null)
        properties.setProperty("smtp.sender.email", smtpEmail);
    String smtpDisplayname = post.get("smtpDisplayname", null);
    if (smtpDisplayname != null)
        properties.setProperty("smtp.sender.displayname", smtpDisplayname);
    String smtpUsername = post.get("smtpUsername", null);
    if (smtpUsername != null)
        properties.setProperty("smtp.sender.username", smtpUsername);
    String smtpPassword = post.get("smtpPassword", null);
    if (smtpPassword != null)
        properties.setProperty("smtp.sender.password", smtpPassword);
    String smtpDisableCertificateChecking = post.get("smtpDisableCertificateChecking", null);
    if ("true".equals(smtpDisableCertificateChecking) || "false".equals(smtpDisableCertificateChecking))
        properties.setProperty("smtp.trustselfsignedcerts", smtpDisableCertificateChecking);
    // host url
    String hostUrl = post.get("hostUrl", null);
    if (hostUrl != null)
        properties.setProperty("host.url", hostUrl);
    String shortLinkStub = post.get("shortLinkStub", null);
    if (shortLinkStub != null)
        properties.setProperty("shortlink.urlstub", shortLinkStub);
    // user signup
    String publicSignup = post.get("publicSignup", null);
    if (publicSignup != null)
        properties.setProperty("users.public.signup", publicSignup);
    // write to file
    try {
        FileOutputStream stream = new FileOutputStream(customConfigPath);
        properties.store(stream, "This file can be used to customize the configuration file conf/config.properties");
        stream.close();
    } catch (Exception e) {
        throw new APIException(500, "Server error");
    }
    return result;
}
Example 27
Project: openbd-core-master  File: cfImapConnection.java View source code
private void openConnection() {
    try {
        Properties props = System.getProperties();
        props.put("mail.imap.partialfetch", "false");
        Session session = Session.getInstance(props, null);
        mailStore = session.getStore(getData("service").getString().toLowerCase());
        mailStore.connect(getData("server").getString(), getData("username").getString(), getData("password").getString());
        setData("succeeded", cfBooleanData.TRUE);
    } catch (AuthenticationFailedException A) {
        setData("errortext", new cfStringData(A.getMessage()));
    } catch (MessagingException M) {
        setData("errortext", new cfStringData(M.getMessage()));
    } catch (SecurityException SE) {
        setData("errortext", new cfStringData("CFIMAP is not supported if SocketPermission is not enabled for the IMAP server. (" + SE.getMessage() + ")"));
    } catch (Exception E) {
        setData("errortext", new cfStringData(E.getMessage()));
    }
}
Example 28
Project: jbpm-master  File: SendHtmlTest.java View source code
private void checkBadAuthentication(String toAddress, String fromAddress, String testMethodName, String username, String password) {
    // Setup email
    WorkItemImpl workItem = createEmailWorkItem(toAddress, fromAddress, testMethodName);
    Connection connection = new Connection(emailHost, emailPort, username, password);
    // send email
    Email email = EmailWorkItemHandler.createEmail(workItem, connection);
    try {
        SendHtml.sendHtml(email, connection);
    } catch (Throwable t) {
        assertTrue("Unexpected exception of type " + t.getClass().getSimpleName() + ", not " + t.getClass().getSimpleName(), (t instanceof RuntimeException));
        assertNotNull("Expected RuntimeException to have a cause.", t.getCause());
        Throwable cause = t.getCause();
        assertNotNull("Expected cause to have a cause.", cause.getCause());
        cause = cause.getCause();
        assertTrue("Unexpected exception of type " + cause.getClass().getSimpleName() + ", not " + cause.getClass().getSimpleName(), (cause instanceof AuthenticationFailedException));
    }
}
Example 29
Project: KolabDroid-master  File: IMAPStore.java View source code
/**
     * Implementation of protocolConnect().  Will create a connection
     * to the server and authenticate the user using the mechanisms
     * specified by various properties. <p>
     *
     * The <code>host</code>, <code>user</code>, and <code>password</code>
     * parameters must all be non-null.  If the authentication mechanism
     * being used does not require a password, an empty string or other
     * suitable dummy password should be used.
     */
protected synchronized boolean protocolConnect(String host, int pport, String user, String password) throws MessagingException {
    IMAPProtocol protocol = null;
    // check for non-null values of host, password, user
    if (host == null || password == null || user == null) {
        if (debug)
            out.println("DEBUG: protocolConnect returning false" + ", host=" + host + ", user=" + user + ", password=" + (password != null ? "<non-null>" : "<null>"));
        return false;
    }
    // set the port correctly
    if (pport != -1) {
        port = pport;
    } else {
        port = PropUtil.getIntSessionProperty(session, "mail." + name + ".port", port);
    }
    // use the default if needed
    if (port == -1) {
        port = defaultPort;
    }
    try {
        boolean poolEmpty;
        synchronized (pool) {
            poolEmpty = pool.authenticatedConnections.isEmpty();
        }
        if (poolEmpty) {
            if (debug)
                out.println("DEBUG: trying to connect to host \"" + host + "\", port " + port + ", isSSL " + isSSL);
            protocol = new IMAPProtocol(name, host, port, session.getDebug(), session.getDebugOut(), session.getProperties(), isSSL);
            if (debug)
                out.println("DEBUG: protocolConnect login" + ", host=" + host + ", user=" + user + ", password=<non-null>");
            login(protocol, user, password);
            protocol.addResponseHandler(this);
            this.host = host;
            this.user = user;
            this.password = password;
            synchronized (pool) {
                pool.authenticatedConnections.addElement(protocol);
            }
        }
    } catch (CommandFailedException cex) {
        if (protocol != null)
            protocol.disconnect();
        protocol = null;
        throw new AuthenticationFailedException(cex.getResponse().getRest());
    } catch (// any other exception
    ProtocolException // any other exception
    pex) {
        throw new MessagingException(pex.getMessage(), pex);
    } catch (IOException ioex) {
        throw new MessagingException(ioex.getMessage(), ioex);
    }
    return true;
}
Example 30
Project: pentaho-platform-master  File: EmailComponent.java View source code
@Override
public boolean executeAction() {
    EmailAction emailAction = (EmailAction) getActionDefinition();
    String messagePlain = emailAction.getMessagePlain().getStringValue();
    String messageHtml = emailAction.getMessageHtml().getStringValue();
    String subject = emailAction.getSubject().getStringValue();
    String to = emailAction.getTo().getStringValue();
    String cc = emailAction.getCc().getStringValue();
    String bcc = emailAction.getBcc().getStringValue();
    String from = emailAction.getFrom().getStringValue(defaultFrom);
    if (from.trim().length() == 0) {
        from = defaultFrom;
    }
    if (ComponentBase.debug) {
        //$NON-NLS-1$
        debug(Messages.getInstance().getString("Email.DEBUG_TO_FROM", to, from));
        //$NON-NLS-1$
        debug(Messages.getInstance().getString("Email.DEBUG_CC_BCC", cc, bcc));
        //$NON-NLS-1$
        debug(Messages.getInstance().getString("Email.DEBUG_SUBJECT", subject));
        //$NON-NLS-1$
        debug(Messages.getInstance().getString("Email.DEBUG_PLAIN_MESSAGE", messagePlain));
        //$NON-NLS-1$
        debug(Messages.getInstance().getString("Email.DEBUG_HTML_MESSAGE", messageHtml));
    }
    if ((to == null) || (to.trim().length() == 0)) {
        // Get the output stream that the feedback is going into
        OutputStream feedbackStream = getFeedbackOutputStream();
        if (feedbackStream != null) {
            createFeedbackParameter("to", Messages.getInstance().getString("Email.USER_ENTER_EMAIL_ADDRESS"), "", "", //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
            true);
            //$NON-NLS-1$
            setFeedbackMimeType("text/html");
            return true;
        } else {
            return false;
        }
    }
    if (subject == null) {
        //$NON-NLS-1$
        error(Messages.getInstance().getErrorString("Email.ERROR_0005_NULL_SUBJECT", getActionName()));
        return false;
    }
    if ((messagePlain == null) && (messageHtml == null)) {
        //$NON-NLS-1$
        error(Messages.getInstance().getErrorString("Email.ERROR_0006_NULL_BODY", getActionName()));
        return false;
    }
    if (getRuntimeContext().isPromptPending()) {
        return true;
    }
    try {
        Properties props = new Properties();
        final IEmailService service = PentahoSystem.get(IEmailService.class, "IEmailService", PentahoSessionHolder.getSession());
        props.put("mail.smtp.host", service.getEmailConfig().getSmtpHost());
        props.put("mail.smtp.port", ObjectUtils.toString(service.getEmailConfig().getSmtpPort()));
        props.put("mail.transport.protocol", service.getEmailConfig().getSmtpProtocol());
        props.put("mail.smtp.starttls.enable", ObjectUtils.toString(service.getEmailConfig().isUseStartTls()));
        props.put("mail.smtp.auth", ObjectUtils.toString(service.getEmailConfig().isAuthenticate()));
        props.put("mail.smtp.ssl", ObjectUtils.toString(service.getEmailConfig().isUseSsl()));
        props.put("mail.smtp.quitwait", ObjectUtils.toString(service.getEmailConfig().isSmtpQuitWait()));
        props.put("mail.from.default", service.getEmailConfig().getDefaultFrom());
        String fromName = service.getEmailConfig().getFromName();
        if (StringUtils.isEmpty(fromName)) {
            fromName = Messages.getInstance().getString("schedulerEmailFromName");
        }
        props.put("mail.from.name", fromName);
        props.put("mail.debug", ObjectUtils.toString(service.getEmailConfig().isDebug()));
        Session session;
        if (service.getEmailConfig().isAuthenticate()) {
            props.put("mail.userid", service.getEmailConfig().getUserId());
            props.put("mail.password", service.getEmailConfig().getPassword());
            Authenticator authenticator = new EmailAuthenticator();
            session = Session.getInstance(props, authenticator);
        } else {
            session = Session.getInstance(props);
        }
        // debugging is on if either component (xaction) or email config debug is on
        if (service.getEmailConfig().isDebug() || ComponentBase.debug) {
            session.setDebug(true);
        }
        // construct the message
        MimeMessage msg = new MimeMessage(session);
        if (from != null) {
            msg.setFrom(new InternetAddress(from));
        } else {
            // There should be no way to get here
            //$NON-NLS-1$
            error(Messages.getInstance().getString("Email.ERROR_0012_FROM_NOT_DEFINED"));
        }
        if ((to != null) && (to.trim().length() > 0)) {
            msg.setRecipients(Message.RecipientType.TO, InternetAddress.parse(to, false));
        }
        if ((cc != null) && (cc.trim().length() > 0)) {
            msg.setRecipients(Message.RecipientType.CC, InternetAddress.parse(cc, false));
        }
        if ((bcc != null) && (bcc.trim().length() > 0)) {
            msg.setRecipients(Message.RecipientType.BCC, InternetAddress.parse(bcc, false));
        }
        if (subject != null) {
            msg.setSubject(subject, LocaleHelper.getSystemEncoding());
        }
        EmailAttachment[] emailAttachments = emailAction.getAttachments();
        if ((messagePlain != null) && (messageHtml == null) && (emailAttachments.length == 0)) {
            msg.setText(messagePlain, LocaleHelper.getSystemEncoding());
        } else if (emailAttachments.length == 0) {
            if (messagePlain != null) {
                //$NON-NLS-1$          
                msg.setContent(messagePlain, "text/plain; charset=" + LocaleHelper.getSystemEncoding());
            }
            if (messageHtml != null) {
                //$NON-NLS-1$
                msg.setContent(messageHtml, "text/html; charset=" + LocaleHelper.getSystemEncoding());
            }
        } else {
            // need to create a multi-part message...
            // create the Multipart and add its parts to it
            Multipart multipart = new MimeMultipart();
            // create and fill the first message part
            if (messageHtml != null) {
                // create and fill the first message part
                MimeBodyPart htmlBodyPart = new MimeBodyPart();
                //$NON-NLS-1$
                htmlBodyPart.setContent(messageHtml, "text/html; charset=" + LocaleHelper.getSystemEncoding());
                multipart.addBodyPart(htmlBodyPart);
            }
            if (messagePlain != null) {
                MimeBodyPart textBodyPart = new MimeBodyPart();
                //$NON-NLS-1$
                textBodyPart.setContent(messagePlain, "text/plain; charset=" + LocaleHelper.getSystemEncoding());
                multipart.addBodyPart(textBodyPart);
            }
            for (EmailAttachment element : emailAttachments) {
                IPentahoStreamSource source = element.getContent();
                if (source == null) {
                    //$NON-NLS-1$
                    error(Messages.getInstance().getErrorString("Email.ERROR_0015_ATTACHMENT_FAILED"));
                    return false;
                }
                DataSource dataSource = new ActivationHelper.PentahoStreamSourceWrapper(source);
                String attachmentName = element.getName();
                if (ComponentBase.debug) {
                    //$NON-NLS-1$
                    debug(Messages.getInstance().getString("Email.DEBUG_ADDING_ATTACHMENT", attachmentName));
                }
                // create the second message part
                MimeBodyPart attachmentBodyPart = new MimeBodyPart();
                // attach the file to the message
                attachmentBodyPart.setDataHandler(new DataHandler(dataSource));
                attachmentBodyPart.setFileName(attachmentName);
                if (ComponentBase.debug) {
                    //$NON-NLS-1$
                    debug(Messages.getInstance().getString("Email.DEBUG_ATTACHMENT_SOURCE", dataSource.getName()));
                }
                multipart.addBodyPart(attachmentBodyPart);
            }
            // add the Multipart to the message
            msg.setContent(multipart);
        }
        //$NON-NLS-1$
        msg.setHeader("X-Mailer", EmailComponent.MAILER);
        msg.setSentDate(new Date());
        Transport.send(msg);
        if (ComponentBase.debug) {
            //$NON-NLS-1$
            debug(Messages.getInstance().getString("Email.DEBUG_EMAIL_SUCCESS"));
        }
        return true;
    // TODO: persist the content set for a while...
    } catch (SendFailedException e) {
        error(Messages.getInstance().getErrorString("Email.ERROR_0011_SEND_FAILED", to), e);
    } catch (AuthenticationFailedException e) {
        error(Messages.getInstance().getString("Email.ERROR_0014_AUTHENTICATION_FAILED", to), e);
    } catch (Throwable e) {
        error(Messages.getInstance().getErrorString("Email.ERROR_0011_SEND_FAILED", to), e);
    }
    return false;
}
Example 31
Project: quercus-gae-master  File: MailModule.java View source code
/**
   * Send mail using JavaMail.
   */
public static boolean mail(Env env, String to, String subject, StringValue message, @Optional String additionalHeaders, @Optional String additionalParameters) {
    Transport smtp = null;
    try {
        HashMap<String, String> headers = splitHeaders(additionalHeaders);
        if (to == null || to.equals(""))
            to = headers.get("to");
        Properties props = new Properties();
        StringValue host = env.getIni("SMTP");
        if (host != null && !host.toString().equals(""))
            props.put("mail.smtp.host", host.toString());
        else if (System.getProperty("mail.smtp.host") != null)
            props.put("mail.smtp.host", System.getProperty("mail.smtp.host"));
        StringValue port = env.getIni("smtp_port");
        if (port != null && !port.toString().equals(""))
            props.put("mail.smtp.port", port.toString());
        else if (System.getProperty("mail.smtp.port") != null)
            props.put("mail.smtp.port", System.getProperty("mail.smtp.port"));
        if (System.getProperty("mail.smtp.class") != null)
            props.put("mail.smtp.class", System.getProperty("mail.smtp.class"));
        StringValue user = null;
        if (headers.get("from") != null)
            user = env.createStringOld(headers.get("from"));
        if (user == null)
            user = env.getIni("sendmail_from");
        if (user != null && !user.toString().equals("")) {
            String userString = user.toString();
            /*
        int p = userString.indexOf('<');
        int q = userString.indexOf('>');
        
        if (p >= 0 && q >= 0) {
          userString = userString.substring(p + 1, q);
        }
        */
            props.put("mail.from", userString);
        } else if (System.getProperty("mail.from") != null)
            props.put("mail.from", System.getProperty("mail.from"));
        else {
            try {
                InetAddress addr = InetAddress.getLocalHost();
                String email = (System.getProperty("user.name") + "@" + addr.getHostName());
                int index = email.indexOf('@');
                // for certain windows smtp servers
                if (email.indexOf('.', index) < 0)
                    email += ".com";
                props.put("mail.from", email);
            } catch (Exception e) {
                log.log(Level.FINER, e.toString(), e);
            }
        }
        String username = env.getIniString("smtp_username");
        String password = env.getIniString("smtp_password");
        if (password != null && !"".equals(password))
            props.put("mail.smtp.auth", "true");
        Session mailSession = Session.getInstance(props, null);
        smtp = mailSession.getTransport("smtp");
        MimeMessage msg = new MimeMessage(mailSession);
        if (subject == null)
            subject = "";
        msg.setSubject(subject);
        msg.setContent(message.toString(), "text/plain");
        ArrayList<Address> addrList = new ArrayList<Address>();
        if (to != null && to.length() > 0)
            addRecipients(msg, Message.RecipientType.TO, to, addrList);
        if (headers != null)
            addHeaders(msg, headers, addrList);
        Address[] from = msg.getFrom();
        if (from == null || from.length == 0) {
            log.fine(L.l("mail 'From' not set, setting to Java System property 'user.name'"));
            msg.setFrom();
        }
        msg.saveChanges();
        from = msg.getFrom();
        log.fine(L.l("sending mail, From: {0}, To: {1}", from[0], to));
        if (password != null && !"".equals(password))
            smtp.connect(username, password);
        else
            smtp.connect();
        Address[] addr;
        addr = new Address[addrList.size()];
        addrList.toArray(addr);
        smtp.sendMessage(msg, addr);
        log.fine("quercus-mail: sent mail to " + to);
        return true;
    } catch (RuntimeException e) {
        log.log(Level.FINER, e.toString(), e);
        throw e;
    } catch (AuthenticationFailedException e) {
        log.warning(L.l("Quercus[] mail could not send mail to '{0}' because authentication failed\n{1}", to, e.getMessage()));
        log.log(Level.FINE, e.toString(), e);
        env.warning(e.toString());
        return false;
    } catch (MessagingException e) {
        Throwable cause = e;
        log.warning(L.l("Quercus[] mail could not send mail to '{0}'\n{1}", to, cause.getMessage()));
        log.log(Level.FINE, cause.toString(), cause);
        env.warning(cause.getMessage());
        return false;
    } catch (Exception e) {
        Throwable cause = e;
        log.warning(L.l("Quercus[] mail could not send mail to '{0}'\n{1}", to, cause.getMessage()));
        log.log(Level.FINE, cause.toString(), cause);
        env.warning(cause.toString());
        return false;
    } finally {
        try {
            if (smtp != null)
                smtp.close();
        } catch (Exception e) {
            log.log(Level.FINER, e.toString(), e);
        }
    }
}
Example 32
Project: quercus-master  File: MailModule.java View source code
/**
    * Send mail using JavaMail.
    */
public static boolean mail(Env env, String to, String subject, StringValue message, @Optional String additionalHeaders, @Optional String additionalParameters) {
    Transport smtp = null;
    try {
        HashMap<String, String> headers = splitHeaders(additionalHeaders);
        if (to == null || to.equals("")) {
            to = headers.get("to");
        }
        Properties props = new Properties();
        StringValue host = env.getIni("SMTP");
        if (host != null && !host.toString().equals("")) {
            props.put("mail.smtp.host", host.toString());
        } else if (System.getProperty("mail.smtp.host") != null) {
            props.put("mail.smtp.host", System.getProperty("mail.smtp.host"));
        }
        StringValue port = env.getIni("smtp_port");
        if (port != null && !port.toString().equals("")) {
            props.put("mail.smtp.port", port.toString());
        } else if (System.getProperty("mail.smtp.port") != null) {
            props.put("mail.smtp.port", System.getProperty("mail.smtp.port"));
        }
        if (System.getProperty("mail.smtp.class") != null) {
            props.put("mail.smtp.class", System.getProperty("mail.smtp.class"));
        }
        StringValue user = null;
        if (headers.get("from") != null) {
            user = env.createString(headers.get("from"));
        }
        if (user == null) {
            user = env.getIni("sendmail_from");
        }
        if (user != null && !user.toString().equals("")) {
            String userString = user.toString();
            props.put("mail.from", userString);
        } else if (System.getProperty("mail.from") != null) {
            props.put("mail.from", System.getProperty("mail.from"));
        } else {
            try {
                InetAddress addr = InetAddress.getLocalHost();
                String email = (System.getProperty("user.name") + "@" + addr.getHostName());
                int index = email.indexOf('@');
                // for certain windows smtp servers
                if (email.indexOf('.', index) < 0) {
                    email += ".com";
                }
                props.put("mail.from", email);
            } catch (Exception e) {
                log.log(Level.FINER, e.toString(), e);
            }
        }
        String username = env.getIniString("smtp_username");
        String password = env.getIniString("smtp_password");
        if (password != null && !"".equals(password)) {
            props.put("mail.smtp.auth", "true");
        }
        Session mailSession = Session.getInstance(props, null);
        smtp = mailSession.getTransport("smtp");
        QuercusMimeMessage msg = new QuercusMimeMessage(mailSession);
        if (subject == null) {
            subject = "";
        }
        msg.setSubject(subject);
        msg.setContent(message.toString(), "text/plain");
        ArrayList<Address> addrList = new ArrayList<Address>();
        if (to != null && to.length() > 0) {
            addRecipients(msg, Message.RecipientType.TO, to, addrList);
        }
        if (headers != null) {
            addHeaders(msg, headers, addrList);
        }
        Address[] from = msg.getFrom();
        if (from == null || from.length == 0) {
            log.fine(L.l("mail 'From' not set, setting to Java System property 'user.name'"));
            msg.setFrom();
        }
        msg.saveChanges();
        from = msg.getFrom();
        log.fine(L.l("sending mail, From: {0}, To: {1}", from[0], to));
        if (password != null && !"".equals(password)) {
            smtp.connect(username, password);
        } else {
            smtp.connect();
        }
        Address[] addr;
        addr = new Address[addrList.size()];
        addrList.toArray(addr);
        smtp.sendMessage(msg, addr);
        log.fine("quercus-mail: sent mail to " + to);
        return true;
    } catch (RuntimeException e) {
        log.log(Level.FINER, e.toString(), e);
        throw e;
    } catch (AuthenticationFailedException e) {
        log.warning(L.l("Quercus[] mail could not send mail to '{0}' " + "because authentication failed\n{1}", to, e.getMessage()));
        log.log(Level.FINE, e.toString(), e);
        env.warning(e.toString());
        return false;
    } catch (MessagingException e) {
        Throwable cause = e;
        log.warning(L.l("Quercus[] mail could not send mail to '{0}'\n{1}", to, cause.getMessage()));
        log.log(Level.FINE, cause.toString(), cause);
        env.warning(cause.getMessage());
        return false;
    } catch (Exception e) {
        Throwable cause = e;
        log.warning(L.l("Quercus[] mail could not send mail to '{0}'\n{1}", to, cause.getMessage()));
        log.log(Level.FINE, cause.toString(), cause);
        env.warning(cause.toString());
        return false;
    } finally {
        try {
            if (smtp != null) {
                smtp.close();
            }
        } catch (Exception e) {
            log.log(Level.FINER, e.toString(), e);
        }
    }
}
Example 33
Project: resin-master  File: MailModule.java View source code
/**
   * Send mail using JavaMail.
   */
public static boolean mail(Env env, String to, String subject, StringValue message, @Optional String additionalHeaders, @Optional String additionalParameters) {
    Transport smtp = null;
    try {
        HashMap<String, String> headers = splitHeaders(additionalHeaders);
        if (to == null || to.equals(""))
            to = headers.get("to");
        Properties props = new Properties();
        StringValue host = env.getIni("SMTP");
        if (host != null && !host.toString().equals(""))
            props.put("mail.smtp.host", host.toString());
        else if (System.getProperty("mail.smtp.host") != null)
            props.put("mail.smtp.host", System.getProperty("mail.smtp.host"));
        StringValue port = env.getIni("smtp_port");
        if (port != null && !port.toString().equals(""))
            props.put("mail.smtp.port", port.toString());
        else if (System.getProperty("mail.smtp.port") != null)
            props.put("mail.smtp.port", System.getProperty("mail.smtp.port"));
        if (System.getProperty("mail.smtp.class") != null)
            props.put("mail.smtp.class", System.getProperty("mail.smtp.class"));
        StringValue user = null;
        if (headers.get("from") != null)
            user = env.createString(headers.get("from"));
        if (user == null)
            user = env.getIni("sendmail_from");
        if (user != null && !user.toString().equals("")) {
            String userString = user.toString();
            props.put("mail.from", userString);
        } else if (System.getProperty("mail.from") != null)
            props.put("mail.from", System.getProperty("mail.from"));
        else {
            try {
                InetAddress addr = InetAddress.getLocalHost();
                String email = (System.getProperty("user.name") + "@" + addr.getHostName());
                int index = email.indexOf('@');
                // for certain windows smtp servers
                if (email.indexOf('.', index) < 0)
                    email += ".com";
                props.put("mail.from", email);
            } catch (Exception e) {
                log.log(Level.FINER, e.toString(), e);
            }
        }
        String username = env.getIniString("smtp_username");
        String password = env.getIniString("smtp_password");
        if (password != null && !"".equals(password))
            props.put("mail.smtp.auth", "true");
        Session mailSession = Session.getInstance(props, null);
        smtp = mailSession.getTransport("smtp");
        QuercusMimeMessage msg = new QuercusMimeMessage(mailSession);
        if (subject == null)
            subject = "";
        msg.setSubject(subject);
        msg.setContent(message.toString(), "text/plain");
        ArrayList<Address> addrList = new ArrayList<Address>();
        if (to != null && to.length() > 0)
            addRecipients(msg, Message.RecipientType.TO, to, addrList);
        if (headers != null)
            addHeaders(msg, headers, addrList);
        Address[] from = msg.getFrom();
        if (from == null || from.length == 0) {
            log.fine(L.l("mail 'From' not set, setting to Java System property 'user.name'"));
            msg.setFrom();
        }
        msg.saveChanges();
        from = msg.getFrom();
        log.fine(L.l("sending mail, From: {0}, To: {1}", from[0], addrList));
        if (password != null && !"".equals(password))
            smtp.connect(username, password);
        else
            smtp.connect();
        Address[] addr;
        addr = new Address[addrList.size()];
        addrList.toArray(addr);
        smtp.sendMessage(msg, addr);
        log.fine("quercus-mail: sent mail to " + to);
        return true;
    } catch (RuntimeException e) {
        log.log(Level.FINER, e.toString(), e);
        throw e;
    } catch (AuthenticationFailedException e) {
        log.warning(L.l("Quercus[] mail could not send mail to '{0}' " + "because authentication failed\n{1}", to, e.getMessage()));
        log.log(Level.FINE, e.toString(), e);
        env.warning(e.toString());
        return false;
    } catch (MessagingException e) {
        Throwable cause = e;
        log.warning(L.l("Quercus[] mail could not send mail to '{0}'\n{1}", to, cause.getMessage()));
        log.log(Level.FINE, cause.toString(), cause);
        env.warning(cause.getMessage());
        return false;
    } catch (Exception e) {
        Throwable cause = e;
        log.warning(L.l("Quercus[] mail could not send mail to '{0}'\n{1}", to, e));
        log.log(Level.FINE, cause.toString(), cause);
        env.warning(cause.toString());
        return false;
    } finally {
        try {
            if (smtp != null)
                smtp.close();
        } catch (Exception e) {
            log.log(Level.FINER, e.toString(), e);
        }
    }
}
Example 34
Project: xwiki-application-mailarchive-master  File: DefaultMailReader.java View source code
/**
     * {@inheritDoc}
     * 
     * @see org.xwiki.contrib.mail.IMailReader#check(java.lang.String, int, java.lang.String, java.lang.String,
     *      java.lang.String, java.lang.String, boolean)
     */
@Override
public int check(final String folder, final boolean onlyUnread) {
    int result;
    boolean toClose = true;
    // If it is not, we close it after to leave everything as it was.
    if (store != null && store.isConnected()) {
        toClose = false;
    }
    try {
        List<Message> messages = read(folder, onlyUnread);
        result = messages.size();
    // FIXME: instead of converting exceptions to int code, would be better to create new Exception class
    // (like MailException) with provided error code, message and inner stacktrace, and present that to UI.
    } catch (AuthenticationFailedException e) {
        logger.warn("checkMails : ", e);
        return SourceConnectionErrors.AUTHENTICATION_FAILED.getCode();
    } catch (FolderNotFoundException e) {
        logger.warn("checkMails : ", e);
        return SourceConnectionErrors.FOLDER_NOT_FOUND.getCode();
    } catch (MessagingException e) {
        logger.warn("checkMails : ", e);
        if (e.getCause() instanceof java.net.UnknownHostException) {
            return SourceConnectionErrors.UNKNOWN_HOST.getCode();
        } else {
            return SourceConnectionErrors.CONNECTION_ERROR.getCode();
        }
    } catch (IllegalStateException e) {
        return SourceConnectionErrors.ILLEGAL_STATE.getCode();
    } catch (Throwable t) {
        logger.warn("checkMails : ", t);
        return SourceConnectionErrors.UNEXPECTED_EXCEPTION.getCode();
    }
    if (toClose) {
        close();
    }
    logger.debug("checkMails : " + result + " available from " + getMailSource().getHostname());
    return result;
}
Example 35
Project: biobank-master  File: SendErrorMessageDialog.java View source code
@Override
public void run(final IProgressMonitor monitor) {
    monitor.beginTask("Sending mail...", IProgressMonitor.UNKNOWN);
    try {
        Properties props = new Properties();
        props.put(MAIL_SMTP_HOST_KEY, email.getSmtpServer());
        props.put(MAIL_SMTP_AUTH_KEY, Boolean.TRUE.toString());
        // props.put("mail.debug", "true");
        props.put(MAIL_SMTP_PORT_KEY, email.getServerPort());
        props.put(MAIL_SMTP_SOCKET_FACTORY_PORT_KEY, email.getServerPort());
        props.put(MAIL_SMTP_SOCKET_FACTORY_CLASS_KEY, SSL_FACTORY);
        props.put(MAIL_SMTP_SOCKET_FACTORY_FALLBACK_KEY, Boolean.FALSE.toString());
        Session session = Session.getDefaultInstance(props, new javax.mail.Authenticator() {

            @Override
            protected PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication(email.getServerUsername(), email.getServerPassword());
            }
        });
        // session.setDebug(true);
        Transport.send(getEmailMessage(session));
        monitor.done();
    } catch (AuthenticationFailedException afe) {
        BgcPlugin.openAsyncError("Authentification Error", NLS.bind("Wrong authentification for {0}", email.getServerUsername()));
        monitor.setCanceled(true);
        return;
    } catch (Exception e) {
        BgcPlugin.openAsyncError("Error sending mail", e);
        monitor.setCanceled(true);
        return;
    }
}
Example 36
Project: inspectIT-master  File: EMailSenderTest.java View source code
@Test
public void authenticationFailes() throws Exception {
    when(objectFactoryMock.getSmtpTransport()).thenReturn(transportMock);
    doThrow(AuthenticationFailedException.class).when(transportMock).connect("host", 25, "user", "passwd");
    mailSender.defaultRecipientString = null;
    mailSender.smtpPropertiesString = null;
    mailSender.smtpHost = "host";
    mailSender.smtpPort = 25;
    mailSender.smtpUser = "user";
    mailSender.smtpPassword = "passwd";
    mailSender.smtpEnabled = true;
    mailSender.init();
    verify(objectFactoryMock).getSmtpTransport();
    verify(transportMock).connect("host", 25, "user", "passwd");
    verifyNoMoreInteractions(objectFactoryMock, transportMock);
    assertThat(mailSender.isConnected(), is(false));
}
Example 37
Project: jmeter-master  File: SmtpSampler.java View source code
private boolean executeMessage(SampleResult result, SendMailCommand sendMailCmd, Message message) {
    boolean didSampleSucceed = false;
    try {
        sendMailCmd.execute(message);
        result.setResponseCodeOK();
        result.setResponseMessage("Message successfully sent!\n" + sendMailCmd.getServerResponse());
        didSampleSucceed = true;
    } catch (AuthenticationFailedException afex) {
        log.warn("", afex);
        result.setResponseCode("500");
        result.setResponseMessage("AuthenticationFailedException: authentication failed - wrong username / password!\n" + afex);
    } catch (Exception ex) {
        log.warn("", ex);
        result.setResponseCode("500");
        result.setResponseMessage(ex.getMessage());
    }
    return didSampleSucceed;
}
Example 38
Project: liquidsite-master  File: MailQueue.java View source code
/**
     * Processes the specified mail message. This will attempt to
     * send a number of generated mails from the message, although
     * not all.
     *
     * @param message        the mail message to send
     *
     * @throws MailTransportException if the mail transport couldn't
     *             be initialized correctly
     * @throws MailMessageException if the mail message couldn't be
     *             sent due to an error in the message 
     */
private void processMessage(MailMessage message) throws MailTransportException, MailMessageException {
    Transport transport;
    Message msg;
    String error;
    int count = 0;
    // Connect to SMTP server
    try {
        transport = session.getTransport();
    } catch (NoSuchProviderException e) {
        error = "failed to create SMTP transport";
        LOG.error(error, e);
        throw new MailTransportException(error, e);
    }
    try {
        transport.connect();
    } catch (AuthenticationFailedException e) {
        error = "failed to authenticate to SMTP server";
        LOG.error(error, e);
        throw new MailTransportException(error, e);
    } catch (MessagingException e) {
        error = "unknown error while sending message";
        LOG.error(error, e);
        throw new MailTransportException(error, e);
    } catch (IllegalStateException e) {
        error = "already connected to SMTP transport";
        LOG.error(error, e);
        throw new MailTransportException(error, e);
    }
    // Send a number of mail messages
    try {
        while (message.hasMoreMessages() && count < MAX_SEND_COUNT) {
            msg = message.getNextMessage(session);
            transport.sendMessage(msg, msg.getAllRecipients());
            count++;
        }
    } catch (SendFailedException e) {
        error = "failed to send mail message";
        LOG.error(error, e);
        throw new MailMessageException(error, e);
    } catch (MessagingException e) {
        error = "unknown error while sending message";
        LOG.error(error, e);
        throw new MailMessageException(error, e);
    } finally {
        try {
            transport.close();
        } catch (MessagingException ignore) {
        }
    }
}
Example 39
Project: spring-framework-2.5.x-master  File: JavaMailSenderImpl.java View source code
/**
	 * Actually send the given array of MimeMessages via JavaMail.
	 * @param mimeMessages MimeMessage objects to send
	 * @param originalMessages corresponding original message objects
	 * that the MimeMessages have been created from (with same array
	 * length and indices as the "mimeMessages" array), if any
	 * @throws org.springframework.mail.MailAuthenticationException
	 * in case of authentication failure
	 * @throws org.springframework.mail.MailSendException
	 * in case of failure when sending a message
	 */
protected void doSend(MimeMessage[] mimeMessages, Object[] originalMessages) throws MailException {
    Map failedMessages = new LinkedHashMap();
    try {
        Transport transport = getTransport(getSession());
        transport.connect(getHost(), getPort(), getUsername(), getPassword());
        try {
            for (int i = 0; i < mimeMessages.length; i++) {
                MimeMessage mimeMessage = mimeMessages[i];
                try {
                    if (mimeMessage.getSentDate() == null) {
                        mimeMessage.setSentDate(new Date());
                    }
                    String messageId = mimeMessage.getMessageID();
                    mimeMessage.saveChanges();
                    if (messageId != null) {
                        // Preserve explicitly specified message id...
                        mimeMessage.setHeader(HEADER_MESSAGE_ID, messageId);
                    }
                    transport.sendMessage(mimeMessage, mimeMessage.getAllRecipients());
                } catch (MessagingException ex) {
                    Object original = (originalMessages != null ? originalMessages[i] : mimeMessage);
                    failedMessages.put(original, ex);
                }
            }
        } finally {
            transport.close();
        }
    } catch (AuthenticationFailedException ex) {
        throw new MailAuthenticationException(ex);
    } catch (MessagingException ex) {
        throw new MailSendException("Mail server connection failed", ex);
    }
    if (!failedMessages.isEmpty()) {
        throw new MailSendException(failedMessages);
    }
}
Example 40
Project: spring-framework-master  File: JavaMailSenderImpl.java View source code
/**
	 * Actually send the given array of MimeMessages via JavaMail.
	 * @param mimeMessages MimeMessage objects to send
	 * @param originalMessages corresponding original message objects
	 * that the MimeMessages have been created from (with same array
	 * length and indices as the "mimeMessages" array), if any
	 * @throws org.springframework.mail.MailAuthenticationException
	 * in case of authentication failure
	 * @throws org.springframework.mail.MailSendException
	 * in case of failure when sending a message
	 */
protected void doSend(MimeMessage[] mimeMessages, Object[] originalMessages) throws MailException {
    Map<Object, Exception> failedMessages = new LinkedHashMap<>();
    Transport transport = null;
    try {
        for (int i = 0; i < mimeMessages.length; i++) {
            // Check transport connection first...
            if (transport == null || !transport.isConnected()) {
                if (transport != null) {
                    try {
                        transport.close();
                    } catch (Exception ex) {
                    }
                    transport = null;
                }
                try {
                    transport = connectTransport();
                } catch (AuthenticationFailedException ex) {
                    throw new MailAuthenticationException(ex);
                } catch (Exception ex) {
                    for (int j = i; j < mimeMessages.length; j++) {
                        Object original = (originalMessages != null ? originalMessages[j] : mimeMessages[j]);
                        failedMessages.put(original, ex);
                    }
                    throw new MailSendException("Mail server connection failed", ex, failedMessages);
                }
            }
            // Send message via current transport...
            MimeMessage mimeMessage = mimeMessages[i];
            try {
                if (mimeMessage.getSentDate() == null) {
                    mimeMessage.setSentDate(new Date());
                }
                String messageId = mimeMessage.getMessageID();
                mimeMessage.saveChanges();
                if (messageId != null) {
                    // Preserve explicitly specified message id...
                    mimeMessage.setHeader(HEADER_MESSAGE_ID, messageId);
                }
                transport.sendMessage(mimeMessage, mimeMessage.getAllRecipients());
            } catch (Exception ex) {
                Object original = (originalMessages != null ? originalMessages[i] : mimeMessage);
                failedMessages.put(original, ex);
            }
        }
    } finally {
        try {
            if (transport != null) {
                transport.close();
            }
        } catch (Exception ex) {
            if (!failedMessages.isEmpty()) {
                throw new MailSendException("Failed to close server connection after message failures", ex, failedMessages);
            } else {
                throw new MailSendException("Failed to close server connection after message sending", ex);
            }
        }
    }
    if (!failedMessages.isEmpty()) {
        throw new MailSendException(failedMessages);
    }
}
Example 41
Project: aipo-master  File: ALPop3MailReceiver.java View source code
/**
   * POP3 サー��らメールを�信�る.
   * 
   * @param delete
   *          �信��メールを削除�る����.削除�る場��,true.
   * @param enableSavingDays
   *          指定日数を超��メールを削除�る����.削除�る場��,true.
   * @param savingDays
   *          メール削除�指定日数
   * @param denyReceivedMail
   *          �信済�メッセージを�り込���場��,true.
   * @param authReceiveFlag
   *          �信時��証方�
   * @throws Exception
   */
@Override
public int receive(String orgId) throws Exception {
    // POP3 サー�上�ストア
    Store pop3Store = null;
    // POP3 サー�上�フォルダ
    POP3Folder pop3Folder = null;
    // ローカルストア
    ALFolder receiveFolder = null;
    // ��セッション中�メール� UID �一覧
    List<String> newUIDL = null;
    // ��セッション��存��メール� UID �一覧
    List<String> receivedUIDL = new ArrayList<String>();
    // 今,�信���るメール� UID
    String nowReceivedUID = null;
    boolean overMailMaxSize = false;
    // 一通�メール��信を完了����フラグ
    boolean finishedReceiving = false;
    try {
        // POP3 サー���接続
        Session session = getSession(rcontext.getAuthReceiveFlag(), rcontext.getEncryptionFlag());
        pop3Store = session.getStore("pop3");
        pop3Store.connect(rcontext.getPop3Host(), Integer.parseInt(rcontext.getPop3Port()), rcontext.getPop3UserId(), rcontext.getPop3UserPasswd());
        if (!pop3Store.isConnected()) {
            // POP3 サー���接続失敗時�処�
            close(pop3Store, pop3Folder, receiveFolder);
            return RECEIVE_MSG_FAIL_CONNECT;
        }
        // POP3 サーãƒ?上ã?®ãƒ¡ãƒ¼ãƒ«ãƒ•ã‚©ãƒ«ãƒ€ã‚’é–‹ã??
        pop3Folder = (POP3Folder) pop3Store.getFolder("INBOX");
        if (pop3Folder == null) {
            close(pop3Store, null, receiveFolder);
            return RECEIVE_MSG_FAIL;
        }
        pop3Folder.open(Folder.READ_WRITE);
        // ローカルストア�接続
        receiveFolder = getALFolder();
        if (receiveFolder == null) {
            close(pop3Store, pop3Folder, null);
            return RECEIVE_MSG_FAIL;
        }
        // POP3 サー���存�れ��るメッセージ数を�得
        int totalMessages = pop3Folder.getMessageCount();
        if (totalMessages == 0) {
            // 新�メール数を�存�る.
            receiveFolder.setNewMailNum(0);
            close(pop3Store, pop3Folder, receiveFolder);
            receivedMailNum = 0;
            return receivedMailNum;
        }
        // �存���る UID �一覧を�得
        List<String> oldUIDL = receiveFolder.loadUID();
        // �信�るメール� UID �一覧を�得
        newUIDL = new ArrayList<String>();
        Message[] messages = pop3Folder.getMessages();
        String uid = null;
        totalMessages = messages.length;
        for (int i = 0; i < totalMessages; i++) {
            uid = pop3Folder.getUID(messages[i]);
            if (uid == null) {
                String[] xuidls = messages[i].getHeader("X-UIDL");
                if (xuidls != null && xuidls.length > 0) {
                    uid = xuidls[0];
                } else {
                    uid = ((MimeMessage) messages[i]).getMessageID();
                }
            }
            newUIDL.add(uid);
        }
        // UID �差分を�得
        BitSet retrieveFlags = new BitSet();
        if (rcontext.getDenyReceivedMail()) {
            for (int i = 0; i < totalMessages; i++) {
                if (!oldUIDL.contains(newUIDL.get(i))) {
                    retrieveFlags.set(i);
                    mailNumOnServer++;
                } else {
                    receivedUIDL.add(newUIDL.get(i));
                }
            }
        } else {
            for (int i = 0; i < totalMessages; i++) {
                retrieveFlags.set(i);
            }
            mailNumOnServer = totalMessages;
        }
        oldUIDL.clear();
        newUIDL.clear();
        ALStaticObject.getInstance().updateAccountStat(rcontext.getAccountId(), ALPop3MailReceiveThread.KEY_RECEIVE_MAIL_ALL_NUM, Integer.valueOf(mailNumOnServer));
        // �時点�ら指定日数を引��日時を�得.
        Calendar cal = Calendar.getInstance();
        cal.setTime(new Date());
        cal.set(Calendar.DATE, cal.get(Calendar.DATE) - rcontext.getSavingDays());
        Date limitDate = cal.getTime();
        MimeMessage tmpMessage = null;
        ALMailMessage alPop3MailMessage = null;
        for (int i = 0; i < totalMessages; i++) {
            finishedReceiving = false;
            tmpMessage = (MimeMessage) pop3Folder.getMessage(i + 1);
            // 新�メール��る�を確�
            if (retrieveFlags.get(i)) {
                nowReceivedUID = pop3Folder.getUID(tmpMessage);
                if (nowReceivedUID == null) {
                    String[] xuidls = tmpMessage.getHeader("X-UIDL");
                    if (xuidls != null && xuidls.length > 0) {
                        nowReceivedUID = xuidls[0];
                    } else {
                        nowReceivedUID = tmpMessage.getMessageID();
                    }
                }
                // (新�メール)メールを�信��存�る.
                alPop3MailMessage = new ALPop3Message((POP3Message) tmpMessage, i + 1);
                if (tmpMessage.getSize() <= ALMailUtils.getMaxMailSize()) {
                    // �信�能�メール容�以下��れ�,登録�る.
                    if (receiveFolder.saveMail(alPop3MailMessage, orgId)) {
                        if (rcontext.getDelete()) {
                            // �信��メールを POP3 サー�上�ら削除�る
                            tmpMessage.setFlag(Flags.Flag.DELETED, rcontext.getDelete());
                        } else {
                            if (rcontext.getEnableSavingDays()) {
                                // 指定日数を���メールを削除�る(ヘッダ Received �日付�判断�る).
                                Date receivedDate = ALMailUtils.getReceivedDate(tmpMessage);
                                if (receivedDate != null && receivedDate.before(limitDate)) {
                                    // �信��メールを POP3 サー�上�ら削除�る
                                    tmpMessage.setFlag(Flags.Flag.DELETED, true);
                                }
                            }
                        }
                        receivedUIDL.add(nowReceivedUID);
                        receivedMailNum++;
                    }
                } else {
                    if (receiveFolder.saveDefectiveMail(alPop3MailMessage, orgId)) {
                        receivedUIDL.add(nowReceivedUID);
                        receivedMailNum++;
                    }
                    overMailMaxSize = true;
                }
                ALStaticObject.getInstance().updateAccountStat(rcontext.getAccountId(), ALPop3MailReceiveThread.KEY_RECEIVE_MAIL_NUM, Integer.valueOf(receivedMailNum));
                if (receivedMailNum % UID_ADD_NUM == 0 && receivedMailNum != 0) {
                    receiveFolder.saveUID(receivedUIDL);
                }
            }
            finishedReceiving = true;
        }
        // POP3 サー���接続を閉�る
        close(pop3Store, pop3Folder, null);
    } catch (AuthenticationFailedException ae) {
        logger.error("ALPop3MailReceiver.receive", ae);
        if (!finishedReceiving) {
            receivedUIDL.remove(nowReceivedUID);
        }
        receiveFolder.saveUID(receivedUIDL);
        if (receivedUIDL != null) {
            receivedUIDL.clear();
        }
        receiveFolder.setNewMailNum(receivedMailNum);
        close(pop3Store, pop3Folder, receiveFolder);
        return RECEIVE_MSG_FAIL_AUTH;
    } catch (MessagingException me) {
        logger.error("ALPop3MailReceiver.receive", me);
        if (!finishedReceiving) {
            receivedUIDL.remove(nowReceivedUID);
        }
        receiveFolder.saveUID(receivedUIDL);
        if (receivedUIDL != null) {
            receivedUIDL.clear();
        }
        receiveFolder.setNewMailNum(receivedMailNum);
        close(pop3Store, pop3Folder, receiveFolder);
        return RECEIVE_MSG_FAIL_CONNECT;
    } catch (Exception e) {
        logger.error("ALPop3MailReceiver.receive", e);
        if (!finishedReceiving) {
            receivedUIDL.remove(nowReceivedUID);
        }
        receiveFolder.saveUID(receivedUIDL);
        if (receivedUIDL != null) {
            receivedUIDL.clear();
        }
        receiveFolder.setNewMailNum(receivedMailNum);
        close(pop3Store, pop3Folder, receiveFolder);
        return RECEIVE_MSG_FAIL_EXCEPTION;
    } catch (Throwable t) {
        logger.error("ALPop3MailReceiver.receive", t);
        if (!finishedReceiving) {
            receivedUIDL.remove(nowReceivedUID);
        }
        receiveFolder.saveUID(receivedUIDL);
        if (receivedUIDL != null) {
            receivedUIDL.clear();
        }
        receiveFolder.setNewMailNum(receivedMailNum);
        close(pop3Store, pop3Folder, receiveFolder);
        return RECEIVE_MSG_FAIL_OUTOFMEMORY;
    }
    try {
        // �信済��最新� UID �一覧を�存�る.
        receiveFolder.saveUID(receivedUIDL);
        if (receivedUIDL != null) {
            receivedUIDL.clear();
        }
        // 新�メール数を�存�る.
        receiveFolder.setNewMailNum(receivedMailNum);
        // ローカルフォルダを閉�る.
        receiveFolder.close();
    } catch (Exception e) {
        logger.error("ALPop3MailReceiver.receive", e);
        return RECEIVE_MSG_FAIL_EXCEPTION;
    } catch (Throwable t) {
        logger.error("ALPop3MailReceiver.receive", t);
        return RECEIVE_MSG_FAIL_OUTOFMEMORY;
    }
    if (overMailMaxSize) {
        return RECEIVE_MSG_FAIL_OVER_MAIL_MAX_SIZE;
    }
    return RECEIVE_MSG_SUCCESS;
}
Example 42
Project: FileBunker-master  File: BackupController.java View source code
private void handleBackupException(Exception e, BackupResult result, BackupEstimate estimate) {
    Log.log(e);
    VaultException vaultException = VaultException.extract(e);
    UnknownHostException unknownHostException = (UnknownHostException) ExceptionUtil.extract(UnknownHostException.class, e);
    AuthenticationFailedException authenticationException = (AuthenticationFailedException) ExceptionUtil.extract(AuthenticationFailedException.class, e);
    SendFailedException sendFailedException = (SendFailedException) ExceptionUtil.extract(SendFailedException.class, e);
    if (authenticationException != null) {
        String smtp = vault.configuration().parameterForKey(WebMailFileStore.SmtpServerKey);
        String message = "FileBunker was unable to send backup files using the SMTP " + "server " + smtp + " because your authentication credentials are " + "invalid.  Please supply the correct credentials in the " + "FileBunker configuration, by selecting the 'Configure' " + "button next to the 'Requires Authentication' checkbox.";
        MessageDialog.openInformation(getShell(), "SMTP Authentication Error", message);
    } else if (unknownHostException != null || sendFailedException != null) {
        String smtp = vault.configuration().parameterForKey(WebMailFileStore.SmtpServerKey);
        String message;
        if (unknownHostException != null) {
            message = "FileBunker was unable to send backup files using the SMTP " + "server " + smtp + ".  Please correct this address in the FileBunker " + "configuration.";
        } else if (sendFailedException.getMessage() != null && sendFailedException.getMessage().indexOf("550") >= 0) {
            // We need to use authentication and we aren't
            message = "The SMTP server " + smtp + " requires authentication.  " + "Please provide these credentials in the FileBunker " + "configuration.";
        } else {
            // Misc sendFailedException.
            File file = vaultException == null ? null : vaultException.file();
            if (file == null) {
                message = "An error occurred while trying to send a backup email.";
            } else {
                message = "An error occurred while trying to send a backup email for " + file.getName() + ".";
            }
            message += formatBackupResultMessage(result, estimate, true);
        }
        MessageDialog.openInformation(getShell(), "Error", message);
    } else if (vaultException instanceof FailedLoginException) {
        FailedLoginException failedLogin = (FailedLoginException) vaultException;
        String name;
        if (failedLogin.store() != null) {
            name = failedLogin.store().name();
        } else {
            name = "your gmail account";
        }
        String message = "FileBunker was unable to login to " + name + ".  ";
        message += "Please check the email address and password you " + "specified in the FileBunker configuration.  ";
        message += formatBackupResultMessage(result, estimate, true);
        MessageDialog.openInformation(getShell(), "Failed Login", message);
    } else if (vaultException instanceof InsufficientSpaceException) {
        String message = "The backup could not be performed due to a lack " + "of space in the repository.  No files were backed up.";
        MessageDialog.openInformation(getShell(), "Backup Error", message);
    } else if (vaultException instanceof OperationCanceledVaultException) {
        String message = "The backup was canceled.  ";
        message += formatBackupResultMessage(result, estimate, true);
        MessageDialog.openInformation(getShell(), "Backup Canceled", message);
    } else {
        Log.log(e);
        File file = vaultException == null ? null : vaultException.file();
        String message;
        if (file == null) {
            message = "An error occurred while performing the backup.  ";
        } else {
            message = "An error occurred while backing up " + file.getPath() + ".  ";
        }
        message += formatBackupResultMessage(result, estimate, true);
        MessageDialog.openError(getShell(), "Backup Error", message);
    }
}
Example 43
Project: pentaho-platform-plugin-reporting-master  File: SimpleEmailComponent.java View source code
/**
   * Perform the primary function of this component, this is, to execute. This method will be invoked immediately
   * following a successful validate().
   * <p/>
   * This method has 2 ways of working:
   * <p/>
   * 1. You supply a mimeMessage: That mimeMessage will be sent; Optionally, contents will be added as attachment and
   * the original mimeMessage will be encapsulated under a multipart/mixed
   * <p/>
   * <p/>
   * 2. You supply a messageHtml and/or a messageText. A new mimemessage will be built. If you supply both, a
   * multipart/alternative will be used. After that attachments will be included
   * 
   * @return true if successful execution
   * @throws Exception
   */
public boolean execute() throws Exception {
    try {
        // Get the session object
        final Session session = buildSession();
        // Create the message
        final MimeMessage msg = new MimeMessage(session);
        // From, to, etc.
        applyMessageHeaders(msg);
        // Get main message multipart
        final Multipart multipartBody = getMultipartBody(session);
        // Process attachments
        final Multipart mainMultiPart = processAttachments(multipartBody);
        msg.setContent(mainMultiPart);
        // Send it
        //$NON-NLS-1$
        msg.setHeader("X-Mailer", MAILER);
        msg.setSentDate(new Date());
        Transport.send(msg);
        return true;
    } catch (SendFailedException e) {
        log.error(Messages.getInstance().getString("ReportPlugin.emailSendFailed"));
    } catch (AuthenticationFailedException e) {
        log.error(Messages.getInstance().getString("ReportPlugin.emailAuthenticationFailed"));
    }
    return false;
}
Example 44
Project: Car-Cast-master  File: ContentService.java View source code
@Override
public void run() {
    try {
        partialWakeLock.acquire();
        Log.i("CarCast", "starting recording thread.");
        // Lets not the phone go to sleep while doing
        // downloads....
        PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
        PowerManager.WakeLock wl = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "ContentService download thread");
        WifiManager.WifiLock wifiLock = null;
        try {
            // The intent here is keep the phone from shutting
            // down during a download.
            wl.acquire();
            // If we have wifi now, lets hold on to it.
            WifiManager wifi = (WifiManager) getSystemService(Context.WIFI_SERVICE);
            if (wifi.isWifiEnabled()) {
                wifiLock = wifi.createWifiLock("CarCast");
                if (wifiLock != null)
                    wifiLock.acquire();
                Log.i("CarCast", "recording Locked Wifi.");
            }
            // Give wifi two seconds to stablize
            Thread.sleep(2000);
            MailRecordings.doIt(ContentService.this);
        } finally {
            if (wifiLock != null) {
                try {
                    wifiLock.release();
                    Log.i("CarCast", "recording released Wifi.");
                } catch (Throwable t) {
                    Log.i("CarCast", "recording Yikes, issue releasing Wifi.");
                }
            }
            wl.release();
        }
    } catch (javax.mail.AuthenticationFailedException afe) {
        doWarning(activity, "Problem authenticating.  Check username/password.");
    } catch (final Throwable t) {
        Log.i("CarCast", "Unpleasentness during email of recording: " + t.getMessage() + " " + t.getClass());
        String msg = t.getMessage();
        if (msg == null) {
            msg = t.toString();
        }
        doWarning(activity, msg);
    } finally {
        Log.i("CarCast", "finished recording post thread.");
        partialWakeLock.release();
        publishRecordingsThread = null;
    }
}
Example 45
Project: email-preview-master  File: JavamailAccountDaoImpl.java View source code
private Folder getUserInbox(Session session, String folderName) throws MessagingException {
    // Assertions.
    if (session == null) {
        String msg = "Argument 'session' cannot be null";
        throw new IllegalArgumentException(msg);
    }
    try {
        Store store = session.getStore();
        store.connect();
        if (log.isDebugEnabled()) {
            log.debug("Mail store connection established to get user inbox");
        }
        // Retrieve user's inbox folder
        Folder root = store.getDefaultFolder();
        Folder inboxFolder = root.getFolder(folderName);
        return inboxFolder;
    } catch (AuthenticationFailedException e) {
        throw new MailAuthenticationException(e);
    }
}
Example 46
Project: libreplan-master  File: ConfigurationController.java View source code
/**
     * Test E-mail connection.
     *
     * @param host
     *            the host
     * @param port
     *            the port
     * @param username
     *            the username
     * @param password
     *            the password
     */
private void testEmailConnection(String host, String port, String username, String password) {
    Properties props = System.getProperties();
    Transport transport = null;
    try {
        if ("SMTP".equals(protocolsCombobox.getSelectedItem().getLabel())) {
            props.setProperty("mail.smtp.port", port);
            props.setProperty("mail.smtp.host", host);
            props.setProperty("mail.smtp.connectiontimeout", Integer.toString(3000));
            Session session = Session.getInstance(props, null);
            transport = session.getTransport("smtp");
            if ("".equals(username) && "".equals(password)) {
                transport.connect();
            }
        } else if (STARTTLS_PROTOCOL.equals(protocolsCombobox.getSelectedItem().getLabel())) {
            props.setProperty("mail.smtps.port", port);
            props.setProperty("mail.smtps.host", host);
            props.setProperty("mail.smtps.connectiontimeout", Integer.toString(3000));
            Session session = Session.getInstance(props, null);
            transport = session.getTransport("smtps");
            if (!"".equals(username) && password != null) {
                transport.connect(host, username, password);
            }
        }
        messages.clearMessages();
        if (transport != null) {
            if (transport.isConnected()) {
                messages.showMessage(Level.INFO, _("Connection successful!"));
            } else if (!transport.isConnected()) {
                messages.showMessage(Level.WARNING, _("Connection unsuccessful"));
            }
        }
    } catch (AuthenticationFailedException e) {
        messages.clearMessages();
        messages.showMessage(Level.ERROR, _("Invalid credentials"));
    } catch (MessagingException e) {
        LOG.error(e);
        messages.clearMessages();
        messages.showMessage(Level.ERROR, _("Cannot connect"));
    } catch (Exception e) {
        LOG.error(e);
        messages.clearMessages();
        messages.showMessage(Level.ERROR, _("Failed to connect"));
    }
}