Example usage for javax.mail PasswordAuthentication PasswordAuthentication

List of usage examples for javax.mail PasswordAuthentication PasswordAuthentication

Introduction

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

Prototype

public PasswordAuthentication(String userName, String password) 

Source Link

Document

Initialize a new PasswordAuthentication

Usage

From source file:com.github.thorqin.webapi.mail.MailService.java

private void doSendMail(Mail mail) {
    long beginTime = System.currentTimeMillis();
    Properties props = new Properties();
    Session session;/*www  . ja v a 2s .  c o m*/
    props.put("mail.smtp.auth", String.valueOf(serverConfig.useAuthentication()));
    // If want to display SMTP protocol detail then uncomment following statement
    // props.put("mail.debug", "true");
    props.put("mail.smtp.host", serverConfig.getHost());
    if (serverConfig.getPort() != null) {
        props.put("mail.smtp.port", serverConfig.getPort());
    }
    if (serverConfig.getSecure().equals(MailConfig.SECURE_STARTTLS)) {
        props.put("mail.smtp.starttls.enable", "true");
        if (!serverConfig.useAuthentication())
            session = Session.getInstance(props);
        else
            session = Session.getInstance(props, new javax.mail.Authenticator() {
                @Override
                protected PasswordAuthentication getPasswordAuthentication() {
                    return new PasswordAuthentication(serverConfig.getUsername(), serverConfig.getPassword());
                }
            });
    } else if (serverConfig.getSecure().equals(MailConfig.SECURE_SSL)) {
        props.put("mail.smtp.socketFactory.port", serverConfig.getPort());
        props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
        props.put("mail.smtp.socketFactory.fallback", "false");
        if (!serverConfig.useAuthentication())
            session = Session.getInstance(props);
        else
            session = Session.getInstance(props, new javax.mail.Authenticator() {
                @Override
                protected PasswordAuthentication getPasswordAuthentication() {
                    return new PasswordAuthentication(serverConfig.getUsername(), serverConfig.getPassword());
                }
            });
    } else {
        if (!serverConfig.useAuthentication())
            session = Session.getInstance(props);
        else
            session = Session.getInstance(props, new javax.mail.Authenticator() {
                @Override
                protected PasswordAuthentication getPasswordAuthentication() {
                    return new PasswordAuthentication(serverConfig.getUsername(), serverConfig.getPassword());
                }
            });
    }

    // Uncomment to show SMTP protocal
    // session.setDebug(true);

    MimeMessage message = new MimeMessage(session);
    StringBuilder mailTo = new StringBuilder();
    try {
        if (mail.from != null)
            message.setFrom(new InternetAddress(mail.from));
        else if (serverConfig.getFrom() != null)
            message.setFrom(new InternetAddress(serverConfig.getFrom()));
        if (mail.to != null) {
            for (String to : mail.to) {
                if (mailTo.length() > 0)
                    mailTo.append(",");
                mailTo.append(to);
                message.addRecipient(Message.RecipientType.TO, new InternetAddress(to));
            }
        }
        if (mail.subject != null)
            message.setSubject("=?UTF-8?B?" + Base64.encodeBase64String(mail.subject.getBytes("utf-8")) + "?=");
        message.setSentDate(new Date());

        BodyPart bodyPart = new MimeBodyPart();
        if (mail.htmlBody != null)
            bodyPart.setContent(mail.htmlBody, "text/html;charset=utf-8");
        else if (mail.textBody != null)
            bodyPart.setText(mail.textBody);
        Multipart multipart = new MimeMultipart();
        multipart.addBodyPart(bodyPart);

        if (mail.attachments != null) {
            for (String attachment : mail.attachments) {
                BodyPart attachedBody = new MimeBodyPart();
                File attachedFile = new File(attachment);
                DataSource source = new FileDataSource(attachedFile);
                attachedBody.setDataHandler(new DataHandler(source));
                attachedBody.setDisposition(MimeBodyPart.ATTACHMENT);
                String filename = attachedFile.getName();
                attachedBody.setFileName(
                        "=?UTF-8?B?" + Base64.encodeBase64String(filename.getBytes("utf-8")) + "?=");
                multipart.addBodyPart(attachedBody);
            }
        }

        message.setContent(multipart);
        message.saveChanges();
        Transport transport = session.getTransport("smtp");
        transport.connect();

        transport.sendMessage(message, message.getAllRecipients());
        transport.close();
        if (serverConfig.enableTrace()) {
            MailInfo info = new MailInfo();
            info.recipients = mail.to;
            info.sender = StringUtil.join(message.getFrom());
            info.smtpServer = serverConfig.getHost();
            info.smtpUser = serverConfig.getUsername();
            info.subject = mail.subject;
            info.startTime = beginTime;
            info.runningTime = System.currentTimeMillis() - beginTime;
            MonitorService.record(info);
        }
    } catch (Exception ex) {
        logger.log(Level.SEVERE, "Send mail failed!", ex);
    }
}

From source file:fr.treeptik.cloudunit.utils.EmailUtils.java

/**
 * Store general propreties (mailJet), create session and addressFrom
 *
 * @param mapConfigEmail/*from  w  w  w . j  ava  2  s.  co  m*/
 * @return
 * @throws AddressException
 * @throws MessagingException
 */
private Map<String, Object> initEmailConfig(Map<String, Object> mapConfigEmail)
        throws AddressException, MessagingException {

    Configuration configuration = new Configuration();
    configuration.setClassForTemplateLoading(this.getClass(), "/fr.treeptik.cloudunit.templates/");

    Properties props = new Properties();
    props.put("mail.smtp.auth", "true");
    props.put("mail.smtp.starttls.enable", "true");
    props.put("mail.smtp.host", smtpHost);
    props.put("mail.smtp.socketFactory.port", socketFactoryPort);
    props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
    props.put("mail.smtp.auth", "true");
    props.put("mail.smtp.port", smtpPort);

    Session session = Session.getDefaultInstance(props, new javax.mail.Authenticator() {
        protected PasswordAuthentication getPasswordAuthentication() {
            return new PasswordAuthentication(apiKey, secretKey);
        }
    });

    MimeMessage message = new MimeMessage(session);
    message.setFrom(new InternetAddress(emailFrom));

    mapConfigEmail.put("message", message);
    mapConfigEmail.put("configuration", configuration);

    return mapConfigEmail;

}

From source file:com.szmslab.quickjavamail.utils.MailProperties.java

/**
 * ????// www . j a v  a2  s .  c om
 *
 * @param userName
 *            ??
 * @param password
 *            
 * @return ?
 */
public MailProperties authenticate(final String userName, final String password) {
    if (StringUtils.isNotBlank(userName) && StringUtils.isNotBlank(password)) {
        authenticator = new Authenticator() {
            @Override
            protected PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication(userName, password);
            }
        };
        if (protocol.startsWith("smtp")) {
            setString(String.format("mail.%s.auth", protocol), Boolean.TRUE.toString());
        }
    }
    return this;
}

From source file:org.dspace.services.email.EmailServiceImpl.java

@Override
protected PasswordAuthentication getPasswordAuthentication() {
    if (null == cfg) {
        cfg = new DSpace().getConfigurationService();
    }//w ww.  ja v a2s  .c  o  m

    return new PasswordAuthentication(cfg.getProperty("mail.server.username"),
            cfg.getProperty("mail.server.password"));
}

From source file:com.ayu.filter.RegularService.java

@Async
public void sendSSLMail(String text, String toMail) {

    final String username = "clouddefenceids";
    final String password = "";

    Properties props = new Properties();
    props.put("mail.smtp.auth", "true");
    props.put("mail.smtp.starttls.enable", "true");
    props.put("mail.smtp.host", "smtp.gmail.com");
    props.put("mail.smtp.port", "587");

    Session session = Session.getInstance(props, new javax.mail.Authenticator() {
        protected PasswordAuthentication getPasswordAuthentication() {
            return new PasswordAuthentication(username, password);
        }//from   w w  w.  j a  v  a  2 s .c om
    });

    try {

        Message message = new MimeMessage(session);
        message.setFrom(new InternetAddress(username));
        message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(toMail));
        message.setSubject("Forgot Password");
        message.setText(text);

        Transport.send(message);

        System.out.println("Done");

    } catch (MessagingException e) {
        throw new RuntimeException(e);
    }
}

From source file:org.wso2.carbon.registry.eventing.MimeEmailMessageHandler.java

/**
 *
 * @param configContext ConfigurationContext
 * @param message Mail body/*from  w  ww .  j a  va2 s .  co  m*/
 * @param subject Mail Subject
 * @param toAddress email to address
 * @throws RegistryException Registry exception
 */
public void sendMimeMessage(ConfigurationContext configContext, String message, String subject,
        String toAddress) throws RegistryException {
    Properties props = new Properties();
    if (configContext != null && configContext.getAxisConfiguration().getTransportOut("mailto") != null) {
        List<Parameter> params = configContext.getAxisConfiguration().getTransportOut("mailto").getParameters();
        for (Parameter parm : params) {
            props.put(parm.getName(), parm.getValue());
        }
    }
    if (threadPoolExecutor == null) {
        threadPoolExecutor = new ThreadPoolExecutor(MIN_THREAD, MAX_THREAD, DEFAULT_KEEP_ALIVE_TIME,
                TimeUnit.SECONDS, new LinkedBlockingQueue<Runnable>(1000));
    }
    String smtpFrom = props.getProperty(MailConstants.MAIL_SMTP_FROM);

    try {
        smtpFromAddress = new InternetAddress(smtpFrom);
    } catch (AddressException e) {
        log.error("Error in retrieving smtp address");
        throw new RegistryException("Error in transforming smtp address");
    }
    final String smtpUsername = props.getProperty(MailConstants.MAIL_SMTP_USERNAME);
    final String smtpPassword = props.getProperty(MailConstants.MAIL_SMTP_PASSWORD);
    if (smtpUsername != null && smtpPassword != null) {
        MimeEmailMessageHandler.session = Session.getInstance(props, new Authenticator() {
            public PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication(smtpUsername, smtpPassword);
            }
        });
    } else {
        MimeEmailMessageHandler.session = Session.getInstance(props);
    }
    threadPoolExecutor.submit(new EmailSender(toAddress, subject, message.toString(), "text/html"));
}

From source file:com.bia.monitor.service.EmailService.java

/**
 * session is created only once//from   ww  w  .jav a2s .co  m
 *
 * @return
 */
private Session createSession() {

    if (session != null) {
        return session;
    }
    boolean debug = false;

    Properties props = new Properties();
    props.put("mail.smtp.host", SMTP_HOST_NAME);
    props.put("mail.smtp.auth", "true");
    props.put("mail.debug", "false");
    props.put("mail.smtp.port", SMTP_PORT);
    props.put("mail.smtp.socketFactory.port", SMTP_PORT);
    props.put("mail.smtp.socketFactory.class", SSL_FACTORY);
    props.put("mail.smtp.socketFactory.fallback", "false");
    session = Session.getDefaultInstance(props, new javax.mail.Authenticator() {

        @Override
        protected PasswordAuthentication getPasswordAuthentication() {
            return new PasswordAuthentication(USERNAME, PASSWORD); // todo add password before deploy
        }
    });

    session.setDebug(debug);
    return session;
}

From source file:org.eclipse.ecr.automation.core.mail.Mailer.java

/**
 * Set SMTP credential//  w w w. j a  v a2s. c  om
 *
 * @param user
 * @param pass
 */
public void setCredentials(final String user, final String pass) {
    config.setProperty("mail.smtp.auth", "true");
    this.auth = new Authenticator() {
        @Override
        protected PasswordAuthentication getPasswordAuthentication() {
            return new PasswordAuthentication(user, pass);
        }
    };
    session = null;
}

From source file:it.geosolutions.geobatch.mail.SendMailAction.java

public Queue<EventObject> execute(Queue<EventObject> events) throws ActionException {
    final Queue<EventObject> ret = new LinkedList<EventObject>();

    while (events.size() > 0) {
        final EventObject ev;
        try {//from ww  w. j a v  a2s .com
            if ((ev = events.remove()) != null) {
                if (LOGGER.isTraceEnabled()) {
                    LOGGER.trace("Send Mail action.execute(): working on incoming event: " + ev.getSource());
                }

                File mail = (File) ev.getSource();

                FileInputStream fis = new FileInputStream(mail);
                String kmlURL = IOUtils.toString(fis);

                // /////////////////////////////////////////////
                // Send the mail with the given KML URL
                // /////////////////////////////////////////////

                // Recipient's email ID needs to be mentioned.
                String mailTo = conf.getMailToAddress();

                // Sender's email ID needs to be mentioned
                String mailFrom = conf.getMailFromAddress();

                // Get system properties
                Properties properties = new Properties();

                // Setup mail server
                String mailSmtpAuth = conf.getMailSmtpAuth();
                properties.put("mail.smtp.auth", mailSmtpAuth);
                properties.put("mail.smtp.host", conf.getMailSmtpHost());
                properties.put("mail.smtp.starttls.enable", conf.getMailSmtpStarttlsEnable());
                properties.put("mail.smtp.port", conf.getMailSmtpPort());

                // Get the default Session object.
                final String mailAuthUsername = conf.getMailAuthUsername();
                final String mailAuthPassword = conf.getMailAuthPassword();

                Session session = Session.getDefaultInstance(properties,
                        (mailSmtpAuth.equalsIgnoreCase("true") ? new javax.mail.Authenticator() {
                            protected PasswordAuthentication getPasswordAuthentication() {
                                return new PasswordAuthentication(mailAuthUsername, mailAuthPassword);
                            }
                        } : null));

                try {
                    // Create a default MimeMessage object.
                    MimeMessage message = new MimeMessage(session);

                    // Set From: header field of the header.
                    message.setFrom(new InternetAddress(mailFrom));

                    // Set To: header field of the header.
                    message.addRecipient(Message.RecipientType.TO, new InternetAddress(mailTo));

                    // Set Subject: header field
                    message.setSubject(conf.getMailSubject());

                    String mailHeaderName = conf.getMailHeaderName();
                    String mailHeaderValule = conf.getMailHeaderValue();
                    if (mailHeaderName != null && mailHeaderValule != null) {
                        message.addHeader(mailHeaderName, mailHeaderValule);
                    }

                    String mailMessageText = conf.getMailContentHeader();

                    message.setText(mailMessageText + "\n\n" + kmlURL);

                    // Send message
                    Transport.send(message);

                    if (LOGGER.isInfoEnabled())
                        LOGGER.info("Sent message successfully....");

                } catch (MessagingException exc) {
                    ActionExceptionHandler.handleError(conf, this, "An error occurrd when sent message ...");
                    continue;
                }
            } else {
                if (LOGGER.isErrorEnabled()) {
                    LOGGER.error("Send Mail action.execute(): Encountered a NULL event: SKIPPING...");
                }
                continue;
            }
        } catch (Exception ioe) {
            if (LOGGER.isErrorEnabled()) {
                LOGGER.error("Send Mail action.execute(): Unable to produce the output: ",
                        ioe.getLocalizedMessage(), ioe);
            }
            throw new ActionException(this, ioe.getLocalizedMessage(), ioe);
        }
    }

    return ret;
}

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");
        }//from   w  w w . ja  v a  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");
    }
}