Example usage for javax.mail Authenticator Authenticator

List of usage examples for javax.mail Authenticator Authenticator

Introduction

In this page you can find the example usage for javax.mail Authenticator Authenticator.

Prototype

Authenticator

Source Link

Usage

From source file:com.krawler.notify.email.SimpleEmailSender.java

private Authenticator getAuthenticator(final PasswordAuthentication authInfo) {
    if (authInfo != null)
        return new Authenticator() {
            protected PasswordAuthentication getPasswordAuthentication() {
                return authInfo;
            }/*from   w w  w. ja v a2 s  .  co  m*/
        };

    if (loginName != null && loginName.length() > 0 && password != null && password.length() > 0) {
        return new Authenticator() {
            protected PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication(loginName, password);
            }
        };
    }

    return null;
}

From source file:org.apache.synapse.transport.mail.MailEchoRawXMLTest.java

public void testRoundTripPOX() throws Exception {

    String msgId = UUIDGenerator.getUUID();

    Session session = Session.getInstance(props, new Authenticator() {
        public PasswordAuthentication getPasswordAuthentication() {
            return new PasswordAuthentication("synapse.test.1", "mailpassword");
        }// w  ww.j ava 2s .  c  o m
    });
    session.setDebug(log.isTraceEnabled());

    WSMimeMessage msg = new WSMimeMessage(session);
    msg.setFrom(new InternetAddress("synapse.test.0@gmail.com"));
    msg.setReplyTo(InternetAddress.parse("synapse.test.0@gmail.com"));
    InternetAddress[] address = { new InternetAddress("synapse.test.6@gmail.com") };
    msg.setRecipients(Message.RecipientType.TO, address);
    msg.setSubject("POX Roundtrip");
    msg.setHeader(BaseConstants.SOAPACTION, Constants.AXIS2_NAMESPACE_URI + "/echoOMElement");
    msg.setSentDate(new Date());
    msg.setHeader(MailConstants.MAIL_HEADER_MESSAGE_ID, msgId);
    msg.setHeader(MailConstants.MAIL_HEADER_X_MESSAGE_ID, msgId);
    msg.setText(POX_MESSAGE);
    Transport.send(msg);

    Thread.yield();
    Thread.sleep(1000 * 10);

    Object reply = null;
    boolean replyNotFound = true;
    int retryCount = 3;
    while (replyNotFound) {
        log.debug("Checking for response ... with MessageID : " + msgId);
        reply = getMessage(msgId);
        if (reply != null) {
            replyNotFound = false;
        } else {
            if (retryCount-- > 0) {
                Thread.sleep(10000);
            } else {
                break;
            }
        }
    }

    if (reply != null && reply instanceof String) {
        log.debug("Result Body : " + reply);
        XMLStreamReader reader = StAXUtils.createXMLStreamReader(new StringReader((String) reply));
        OMElement res = new StAXOMBuilder(reader).getDocumentElement();
        if (res != null) {
            AXIOMXPath xpath = new AXIOMXPath("//my:myValue");
            xpath.addNamespace("my", "http://localhost/axis2/services/EchoXMLService");
            Object result = xpath.evaluate(res);
            if (result != null && result instanceof OMElement) {
                assertEquals("omTextValue", ((OMElement) result).getText());
            }
        }
    } else {
        fail("Did not receive the reply mail");
    }
}

From source file:de.kp.ames.web.function.access.imap.ImapConsumer.java

/**
 * @param host//  ww w  .  ja va 2  s  . co  m
 * @param port
 * @param alias
 * @param keypass
 * @return
 */
private Session createSession(String host, String port, final String alias, final String keypass) {

    Properties props = setProperties(host, port);

    /*
     * Authenticator & Session
     */
    Session session = Session.getInstance(props, new Authenticator() {
        @Override
        protected PasswordAuthentication getPasswordAuthentication() {
            return new PasswordAuthentication(alias, keypass);
        }
    });

    return session;

}

From source file:org.nuxeo.ecm.automation.core.mail.Mailer.java

/**
 * Set SMTP credential//from  ww w  .  ja v  a  2 s  .co  m
 *
 * @param user
 * @param pass
 */
public void setCredentials(final String user, final String pass) {
    config.setProperty("mail.smtp.auth", "true");
    auth = new Authenticator() {
        @Override
        protected PasswordAuthentication getPasswordAuthentication() {
            return new PasswordAuthentication(user, pass);
        }
    };
    session = null;
}

From source file:org.apache.axis2.transport.mail.MailTransportSender.java

/**
 * Initialize the Mail sender and be ready to send messages
 * @param cfgCtx the axis2 configuration context
 * @param transportOut the transport-out description
 * @throws org.apache.axis2.AxisFault on error
 *///from w  w w  . j a va  2 s  . c om
public void init(ConfigurationContext cfgCtx, TransportOutDescription transportOut) throws AxisFault {
    super.init(cfgCtx, transportOut);

    // initialize SMTP session
    Properties props = new Properties();
    List<Parameter> params = transportOut.getParameters();
    for (Parameter p : params) {
        props.put(p.getName(), p.getValue());
    }

    if (props.containsKey(MailConstants.MAIL_SMTP_FROM)) {
        try {
            smtpFromAddress = new InternetAddress((String) props.get(MailConstants.MAIL_SMTP_FROM));
        } catch (AddressException e) {
            handleException("Invalid default 'From' address : " + props.get(MailConstants.MAIL_SMTP_FROM), e);
        }
    }

    if (props.containsKey(MailConstants.MAIL_SMTP_BCC)) {
        try {
            smtpBccAddresses = InternetAddress.parse((String) props.get(MailConstants.MAIL_SMTP_BCC));
        } catch (AddressException e) {
            handleException("Invalid default 'Bcc' address : " + props.get(MailConstants.MAIL_SMTP_BCC), e);
        }
    }

    if (props.containsKey(MailConstants.TRANSPORT_MAIL_FORMAT)) {
        defaultMailFormat = (String) props.get(MailConstants.TRANSPORT_MAIL_FORMAT);
    }

    smtpUsername = (String) props.get(MailConstants.MAIL_SMTP_USERNAME);
    smtpPassword = (String) props.get(MailConstants.MAIL_SMTP_PASSWORD);

    if (smtpUsername != null && smtpPassword != null) {
        session = Session.getInstance(props, new Authenticator() {
            public PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication(smtpUsername, smtpPassword);
            }
        });
    } else {
        session = Session.getInstance(props, null);
    }

    MailUtils.setupLogging(session, log, transportOut);

    // set the synchronise callback table
    if (cfgCtx.getProperty(BaseConstants.CALLBACK_TABLE) == null) {
        cfgCtx.setProperty(BaseConstants.CALLBACK_TABLE, new ConcurrentHashMap());
    }
}

From source file:com.bia.yahoomailjava.YahooMailService.java

/**
 * session is created only once//  w  w w  . j  ava 2s. c  om
 *
 * @return
 */
private Session createSession() {

    if (session != null && false) {
        return session;
    }
    Properties props = new Properties();
    props.put("mail.smtp.host", "smtp.mail.yahoo.com");
    props.put("mail.stmp.user", USERNAME);
    //To use TLS
    props.put("mail.smtp.auth", "true");
    props.put("mail.smtp.starttls.enable", "true");
    props.put("mail.smtp.password", PASSWORD);
    session = Session.getDefaultInstance(props, new Authenticator() {

        @Override
        protected PasswordAuthentication getPasswordAuthentication() {
            return new PasswordAuthentication(USERNAME, PASSWORD);
        }
    });
    return session;
}

From source file:com.twinsoft.convertigo.engine.admin.services.projects.Deploy.java

@Override
protected void doUpload(HttpServletRequest request, Document document, FileItem item) throws Exception {
    if (!item.getName().endsWith(".car")) {
        ServiceUtils/*from   w w w .j a  va2s . co  m*/
                .addMessage(document, document.getDocumentElement(),
                        "The deployment of the project " + item.getName()
                                + " has failed. The archive file is not valid (.car required).",
                        "error", false);
    }

    super.doUpload(request, document, item);

    // Depending on client browsers, according to the documentation,
    // item.getName() can either return a full path file name, or
    // simply a file name.
    String projectArchive = item.getName();

    // Bugfix #1425
    int i = projectArchive.lastIndexOf('/');
    if (i == -1) {
        i = projectArchive.lastIndexOf('\\');
        if (i != -1) {
            projectArchive = projectArchive.substring(i + 1);
        }
    } else {
        projectArchive = projectArchive.substring(i + 1);
    }

    String projectName = projectArchive.substring(0, projectArchive.indexOf(".car"));

    Engine.theApp.databaseObjectsManager.deployProject(getRepository() + projectArchive, true, bAssembleXsl);

    if (Boolean.parseBoolean(
            EnginePropertiesManager.getProperty(PropertyName.NOTIFICATIONS_NOTIFY_PROJECT_DEPLOYMENT))) {

        final String fUser = (String) request.getSession().getAttribute(SessionKey.ADMIN_USER.toString());
        final String fProjectName = projectName;

        new Thread(new Runnable() {
            public void run() {
                try {
                    Properties props = new Properties();

                    props.put("mail.smtp.host",
                            EnginePropertiesManager.getProperty(PropertyName.NOTIFICATIONS_SMTP_HOST));
                    props.put("mail.smtp.socketFactory.port",
                            EnginePropertiesManager.getProperty(PropertyName.NOTIFICATIONS_SMTP_PORT));
                    props.put("mail.smtp.auth", "true");
                    props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
                    props.put("mail.smtp.socketFactory.fallback", "false");

                    // Initializing
                    Session mailSession = Session.getInstance(props, new Authenticator() {
                        @Override
                        public PasswordAuthentication getPasswordAuthentication() {
                            return new PasswordAuthentication(
                                    EnginePropertiesManager.getProperty(PropertyName.NOTIFICATIONS_SMTP_USER),
                                    EnginePropertiesManager
                                            .getProperty(PropertyName.NOTIFICATIONS_SMTP_PASSWORD));
                        }
                    });
                    MimeMessage message = new MimeMessage(mailSession);

                    message.addRecipient(Message.RecipientType.TO, new InternetAddress(
                            EnginePropertiesManager.getProperty(PropertyName.NOTIFICATIONS_TARGET_EMAIL)));
                    message.setSubject("[trial] deployment of " + fProjectName + " by " + fUser);
                    message.setText(message.getSubject() + "\n" + "http://trial.convertigo.net/cems/projects/"
                            + fProjectName + "\n" + "https://trial.convertigo.net/cems/projects/"
                            + fProjectName);
                    Transport.send(message);
                } catch (MessagingException e1) {
                }
            }
        }).start();
    }

    String message = "The project '" + projectName + "' has been successfully deployed.";
    Engine.logAdmin.info(message);
    ServiceUtils.addMessage(document, document.getDocumentElement(), message, "message", false);
}

From source file:com.brienwheeler.svc.email.impl.EmailService.java

@Override
protected void onStart() throws InterruptedException {
    freemarkerConfig = new Configuration();
    freemarkerConfig.setTemplateLoader(new SmartTemplateLoader(baseDirectory));
    freemarkerConfig.setDefaultEncoding("UTF-8");
    freemarkerConfig.setTemplateExceptionHandler(TemplateExceptionHandler.RETHROW_HANDLER);
    freemarkerConfig.setIncompatibleImprovements(new Version(2, 3, 20));

    Properties properties = new Properties();
    properties.setProperty("mail.smtp.host", mailHost);
    properties.setProperty("mail.smtp.port", Integer.toString(port));
    properties.setProperty("mail.smtp.auth", authenticated.toString());
    properties.setProperty("mail.smtp.starttls.enable", useStartTLS.toString());

    if (authenticated) {
        mailSession = Session.getInstance(properties, new Authenticator() {
            @Override//from   ww w. j a  v  a  2 s  .  c  o  m
            protected PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication(username, password);
            }
        });
    } else {
        mailSession = Session.getInstance(properties);
    }
}

From source file:com.cisco.iwe.services.util.EmailMonitor.java

/**
 * This method returns the corresponding JSON response.'Success = true' in case the Mail contents get stored in the database successfully. 'Success = false' in case of any errors 
 **//*from   w ww .  java 2s  .co  m*/

public String monitorEmailAndLoadDB() {
    License license = new License();
    license.setLicense(EmailParseConstants.ocrLicenseFile);
    Store emailStore = null;
    Folder folder = null;
    Properties props = new Properties();
    logger.info("EmailMonitor monitorEmailAndLoadDB Enter (+)");
    // Setting session and Store information
    // MailServerConnectivity - get the email credentials based on the environment
    String[] mailCredens = getEmailCredens();
    final String username = mailCredens[0];
    final String password = mailCredens[1];
    logger.info("monitorEmailAndLoadDB : Email ID : " + username);

    try {
        logger.info("EmailMonitor.monitorEmailAndLoadDB get the mail server properties");
        props.put(EmailParseConstants.emailAuthKey, "true");
        props.put(EmailParseConstants.emailHostKey, prop.getProperty(EmailParseConstants.emailHost));
        props.put(EmailParseConstants.emailPortKey, prop.getProperty(EmailParseConstants.emailPort));
        props.put(EmailParseConstants.emailTlsKey, "true");

        logger.info("EmailMonitor.monitorEmailAndLoadDB create the session object with mail server properties");
        Session session = Session.getDefaultInstance(props, new Authenticator() {
            @Override
            protected PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication(username, password);
            }
        });
        // Prod-MailServerConnectivity - create the POP3 store object and
        // connect with the pop server
        logger.info("monitorEmailAndLoadDB : create the POP3 store object");
        emailStore = (Store) session.getStore(prop.getProperty(EmailParseConstants.emailType));
        logger.info("monitorEmailAndLoadDB : Connecting to Store :" + emailStore.toString());
        emailStore.connect(prop.getProperty(EmailParseConstants.emailHost),
                Integer.parseInt(prop.getProperty(EmailParseConstants.emailPort)), username, password);
        logger.info("monitorEmailAndLoadDB : Connection Status:" + emailStore.isConnected());

        // create the folder object
        folder = emailStore.getFolder(prop.getProperty(EmailParseConstants.emailFolder));
        // Check if Inbox exists
        if (!folder.exists()) {
            logger.error("monitorEmailAndLoadDB : No INBOX exists...");
            System.exit(0);
        }
        // Open inbox and read messages
        logger.info("monitorEmailAndLoadDB : Connected to Folder");
        folder.open(Folder.READ_WRITE);

        // retrieve the messages from the folder in an array and process it
        Message[] msgArr = folder.getMessages();
        // Read each message and delete the same once data is stored in DB
        logger.info("monitorEmailAndLoadDB : Message length::::" + msgArr.length);

        SimpleDateFormat sdf2 = new SimpleDateFormat(EmailParseConstants.dateFormat);

        Date sent = null;
        String emailContent = null;
        String contentType = null;
        // for (int i = 0; i < msg.length; i++) {
        for (int i = msgArr.length - 1; i > msgArr.length - 2; i--) {
            Message message = msgArr[i];
            if (!message.isSet(Flags.Flag.SEEN)) {
                try {
                    sent = msgArr[i].getSentDate();
                    contentType = message.getContentType();
                    String fileType = null;
                    byte[] byteArr = null;
                    String validAttachments = EmailParseConstants.validAttachmentTypes;
                    if (contentType.contains("multipart")) {
                        Multipart multiPart = (Multipart) message.getContent();
                        int numberOfParts = multiPart.getCount();
                        for (int partCount = 0; partCount < numberOfParts; partCount++) {
                            MimeBodyPart part = (MimeBodyPart) multiPart.getBodyPart(partCount);
                            InputStream inStream = (InputStream) part.getInputStream();
                            ByteArrayOutputStream buffer = new ByteArrayOutputStream();
                            int nRead;
                            byte[] data = new byte[16384];
                            while ((nRead = inStream.read(data, 0, data.length)) != -1) {
                                buffer.write(data, 0, nRead);
                            }
                            buffer.flush();
                            byteArr = buffer.toByteArray();
                            if (Part.ATTACHMENT.equalsIgnoreCase(part.getDisposition())) {
                                fileType = part.getFileName().substring(part.getFileName().lastIndexOf("."),
                                        part.getFileName().length());
                                String fileDir = part.getFileName();
                                if (validAttachments.contains(fileType)) {
                                    part.saveFile(fileDir);
                                    saveAttachmentAndText(message.getFrom()[0].toString(), message.getSubject(),
                                            byteArr, emailContent.getBytes(), fileType, sent,
                                            fileType.equalsIgnoreCase(".PDF") ? scanPDF(fileDir)
                                                    : scanImage(fileDir).toString());
                                    deleteFile(fileDir);
                                } else {
                                    sendNotification();
                                }

                            } else {
                                // this part may be the message content
                                emailContent = part.getContent().toString();
                            }
                        }
                    } else if (contentType.contains("text/plain") || contentType.contains("text/html")) {
                        Object content = message.getContent();
                        if (content != null) {
                            emailContent = content.toString();
                        }
                    }
                    message.setFlag(Flags.Flag.DELETED, false);
                    logger.info(
                            "monitorEmailAndLoadDB : loadSuccess : Mail Parsed for : " + message.getSubject());
                    logger.info("monitorEmailAndLoadDB : loadSuccess : Created at : " + sdf2.format(sent));
                    logger.info("Message deleted");
                } catch (IOException e) {
                    logger.error("IO Exception in email monitoring: " + e);
                    logger.error(
                            "IO Exception in email monitoring message: " + Arrays.toString(e.getStackTrace()));
                } catch (SQLException sexp) {
                    logger.error("SQLException Occurred GetSpogDetails-db2 :", sexp);
                    buildErrorJson(ExceptionConstants.sqlErrCode, ExceptionConstants.sqlErrMsg);
                } catch (Exception e) {
                    logger.error("Unknown Exception in email monitoring: " + e);
                    logger.error("Unknown Exception in email monitoring message: "
                            + Arrays.toString(e.getStackTrace()));
                }
            }
        }

        // Close folder and store
        folder.close(true);
        emailStore.close();

    } catch (NoSuchProviderException e) {
        logger.error("monitorEmailAndLoadDB : NoSuchProviderException in email monitoring: " + e);
        logger.error("monitorEmailAndLoadDB : NoSuchProviderException in email monitoring message: "
                + Arrays.toString(e.getStackTrace()));
    } catch (MessagingException e) {
        logger.error("monitorEmailAndLoadDB : MessagingException in email monitoring: " + e);
        logger.error("monitorEmailAndLoadDB : MessagingException in email monitoring message: "
                + Arrays.toString(e.getStackTrace()));
    } finally {
        if (folder != null && folder.isOpen()) {
            // Close folder and store
            try {
                folder.close(true);
                emailStore.close();
            } catch (MessagingException e) {
                logger.error("monitorEmailAndLoadDB : MessagingException in email monitoring: " + e);
                logger.error("monitorEmailAndLoadDB : MessagingException in email monitoring: "
                        + Arrays.toString(e.getStackTrace()));
            }
        }
    }
    logger.info("EmailMonitor monitorEmailAndLoadDB Exit (-)");
    return buildSuccessJson().toString();
}

From source file:org.artifactory.mail.MailServiceImpl.java

/**
 * Send an e-mail message//from w w  w. ja  v a2  s.co m
 *
 * @param recipients Recipients of the message that will be sent
 * @param subject    The subject of the message
 * @param body       The body of the message
 * @param config     A mail server configuration to use
 * @throws Exception
 */
@Override
public void sendMail(String[] recipients, String subject, String body, final MailServerConfiguration config)
        throws EmailException {

    verifyParameters(recipients, config);

    if (!config.isEnabled()) {
        log.debug("Ignoring requested mail delivery. The given configuration is disabled.");
        return;
    }

    boolean debugEnabled = log.isDebugEnabled();

    Properties properties = new Properties();

    properties.put("mail.smtp.host", config.getHost());
    properties.put("mail.smtp.port", Integer.toString(config.getPort()));

    properties.put("mail.smtp.quitwait", "false");

    //Default protocol
    String protocol = "smtp";

    //Enable TLS if set
    if (config.isUseTls()) {
        properties.put("mail.smtp.starttls.enable", "true");
    }

    //Enable SSL if set
    boolean useSsl = config.isUseSsl();
    if (useSsl) {
        properties.put("mail.smtp.socketFactory.port", Integer.toString(config.getPort()));
        properties.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
        properties.put("mail.smtp.socketFactory.fallback", "false");
        //Requires special protocol
        protocol = "smtps";
    }

    //Set debug property if enabled by the logger
    properties.put("mail.debug", debugEnabled);

    Authenticator authenticator = null;
    if (!StringUtils.isEmpty(config.getUsername())) {
        properties.put("mail.smtp.auth", "true");
        authenticator = new Authenticator() {
            @Override
            protected PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication(config.getUsername(), config.getPassword());
            }
        };
    }

    Session session = Session.getInstance(properties, authenticator);
    Message message = new MimeMessage(session);

    String subjectPrefix = config.getSubjectPrefix();
    String fullSubject = (!StringUtils.isEmpty(subjectPrefix)) ? (subjectPrefix + " " + subject) : subject;
    try {
        message.setSubject(fullSubject);

        if (!StringUtils.isEmpty(config.getFrom())) {
            InternetAddress addressFrom = new InternetAddress(config.getFrom());
            message.setFrom(addressFrom);
        }

        InternetAddress[] addressTo = new InternetAddress[recipients.length];
        for (int i = 0; i < recipients.length; i++) {
            addressTo[i] = new InternetAddress(recipients[i]);
        }
        message.addRecipients(Message.RecipientType.TO, addressTo);

        //Create multi-part message in case we want to add html support
        Multipart multipart = new MimeMultipart("related");

        BodyPart htmlPart = new MimeBodyPart();
        htmlPart.setContent(body, "text/html");
        multipart.addBodyPart(htmlPart);
        message.setContent(multipart);

        //Set debug property if enabled by the logger
        session.setDebug(debugEnabled);

        //Connect and send
        Transport transport = session.getTransport(protocol);
        if (useSsl) {
            transport.connect(config.getHost(), config.getPort(), config.getUsername(), config.getPassword());
        } else {
            transport.connect();
        }
        transport.sendMessage(message, message.getAllRecipients());
        transport.close();
    } catch (MessagingException e) {
        String em = e.getMessage();
        throw new EmailException(
                "An error has occurred while sending an e-mail" + (em != null ? ": " + em.trim() : "") + ".\n",
                e);
    }
}