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.consol.citrus.demo.devoxx.service.MailService.java

/**
 * Send mail via SMTP connection./*from ww  w  . j av  a2  s  .  co m*/
 * @param to
 * @param subject
 * @param body
 */
public void sendMail(String to, String subject, String body) {
    Properties props = new Properties();
    props.put("mail.smtp.host", mailServerHost);
    props.put("mail.smtp.port", mailServerPort);
    props.put("mail.smtp.auth", true);

    Authenticator authenticator = new Authenticator() {
        private PasswordAuthentication pa = new PasswordAuthentication(username, password);

        @Override
        public PasswordAuthentication getPasswordAuthentication() {
            return pa;
        }
    };

    Session session = Session.getInstance(props, authenticator);
    session.setDebug(true);
    MimeMessage message = new MimeMessage(session);
    try {
        message.setFrom(new InternetAddress(from));
        InternetAddress[] address = { new InternetAddress(to) };
        message.setRecipients(Message.RecipientType.TO, address);
        message.setSubject(subject);
        message.setSentDate(new Date());
        message.setText(body);
        Transport.send(message);
    } catch (MessagingException e) {
        log.error("Failed to send mail!", e);
    }
}

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

public MailClient(String user, String host, String password, boolean debug) {
    from = user + '@' + host;
    authentication = new PasswordAuthentication(user, password);

    Properties props = new Properties();

    props.put("mail.user", user);
    props.put("mail.host", host);
    props.put("mail.debug", debug ? "true" : "false");
    props.put("mail.store.protocol", "pop3");
    props.put("mail.transport.protocol", "smtp");
    session = Session.getInstance(props, this);
}

From source file:portal.api.util.EmailUtil.java

public static void SendRegistrationActivationEmail(String email, String messageBody, String subj) {

    Properties props = new Properties();

    // Session session = Session.getDefaultInstance(props, null);

    props.setProperty("mail.transport.protocol", "smtp");
    props.put("mail.smtp.auth", "true");
    if ((PortalRepository.getPropertyByName("mailhost").getValue() != null)
            && (!PortalRepository.getPropertyByName("mailhost").getValue().isEmpty()))
        props.setProperty("mail.host", PortalRepository.getPropertyByName("mailhost").getValue());
    if ((PortalRepository.getPropertyByName("mailuser").getValue() != null)
            && (!PortalRepository.getPropertyByName("mailuser").getValue().isEmpty()))
        props.setProperty("mail.user", PortalRepository.getPropertyByName("mailuser").getValue());
    if ((PortalRepository.getPropertyByName("mailpassword").getValue() != null)
            && (!PortalRepository.getPropertyByName("mailpassword").getValue().isEmpty()))
        props.setProperty("mail.password", PortalRepository.getPropertyByName("mailpassword").getValue());

    String adminemail = PortalRepository.getPropertyByName("adminEmail").getValue();
    final String username = PortalRepository.getPropertyByName("mailuser").getValue();
    final String password = PortalRepository.getPropertyByName("mailpassword").getValue();

    logger.info("adminemail = " + adminemail);
    logger.info("subj = " + subj);

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

    Transport transport;
    try {
        transport = mailSession.getTransport();

        MimeMessage msg = new MimeMessage(mailSession);
        msg.setSentDate(new Date());
        msg.setFrom(new InternetAddress(adminemail, adminemail));
        msg.setSubject(subj);
        msg.setContent(messageBody, "text/html; charset=ISO-8859-1");
        msg.addRecipient(Message.RecipientType.TO, new InternetAddress(email, email));
        msg.addRecipient(Message.RecipientType.CC, new InternetAddress(adminemail, adminemail));

        transport.connect();

        Address[] recips = (Address[]) ArrayUtils.addAll(msg.getRecipients(Message.RecipientType.TO),
                msg.getRecipients(Message.RecipientType.CC));

        transport.sendMessage(msg, recips);

        transport.close();

    } catch (NoSuchProviderException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (MessagingException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (UnsupportedEncodingException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

}

From source file:com.cloudbees.demo.beesshop.util.MailSessionFactoryBean.java

@Override
public void afterPropertiesSet() throws Exception {
    if (Strings.isNullOrEmpty(this.smtpUser)) {
        logger.info("Initialize anonymous mail session");
        mailSession = Session.getInstance(smtpProperties);
    } else {// ww  w .  j ava 2  s  .  c o m
        logger.info("Initialize mail session with user='{}', password='xxx'", smtpUser);

        smtpProperties.setProperty("mail.smtp.auth", "true");
        mailSession = Session.getInstance(smtpProperties, new Authenticator() {
            @Override
            protected PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication(smtpUser, smtpPassword);
            }
        });
    }
    mailSession.setDebug(debug);
}

From source file:de.tuttas.servlets.MailSender.java

private void transmitMail(MailObject mo) throws MessagingException {

    // creates a new session with an authenticator
    Authenticator auth = new Authenticator() {
        public PasswordAuthentication getPasswordAuthentication() {
            return new PasswordAuthentication(Config.getInstance().user, Config.getInstance().pass);
        }// w  w w.ja v a  2s  .  com
    };
    Session session = Session.getInstance(properties, auth);
    // creates a new e-mail message
    MimeMessage msg = new MimeMessage(session);

    msg.setFrom(new InternetAddress(mo.getFrom()));
    InternetAddress[] toAddresses = mo.getRecipient();
    msg.setRecipients(Message.RecipientType.TO, toAddresses);
    InternetAddress[] bccAdresses = mo.getBcc();
    InternetAddress[] ccAdresses = mo.getCC();

    if (bccAdresses[0] != null)
        msg.setRecipients(Message.RecipientType.BCC, bccAdresses);
    if (ccAdresses[0] != null)
        msg.setRecipients(Message.RecipientType.CC, ccAdresses);
    msg.setSubject(mo.getSubject(), "UTF-8");

    msg.setSentDate(new Date());
    msg.setContent(mo.getContent(), "text/plain; charset=UTF-8");
    // sends the e-mail
    // TODO Kommentar entfernen
    Transport.send(msg);
}

From source file:uk.ac.ox.it.ords.api.project.services.impl.SendMailTLS.java

protected void sendMail(String subject, String messageText) throws Exception {

    ////  ww w  .j av a2s.  com
    // Validate Mail server settings
    //
    if (!props.containsKey("mail.smtp.username") || !props.containsKey("mail.smtp.password")
            || !props.containsKey("mail.smtp.host")) {
        log.error("Unable to send emails as email server configuration is missing");
        throw new Exception("Unable to send emails as email server configuration is missing");
    }

    Session session = Session.getInstance(props, new javax.mail.Authenticator() {
        @Override
        protected PasswordAuthentication getPasswordAuthentication() {
            return new PasswordAuthentication(props.get("mail.smtp.username").toString(),
                    props.get("mail.smtp.password").toString());
        }
    });

    try {
        Message message = new MimeMessage(session);
        message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(email));
        message.setSubject(subject);
        message.setText(messageText);

        Transport.send(message);

        if (log.isDebugEnabled()) {
            log.debug(String.format("Sent email to %s", email));
            log.debug("with content: " + messageText);
        }
    } catch (MessagingException e) {
        log.error("Unable to send email to " + email, e);
        throw new Exception("Unable to send email to " + email, e);
    }
}

From source file:uk.ac.ox.it.ords.api.database.services.impl.SendMailTLS.java

protected void sendMail(String subject, String messageText) throws Exception {

    ///*  w  w w  .j av a  2  s  . c o  m*/
    // Validate Mail server settings
    //
    if (!props.containsKey("mail.smtp.username") || !props.containsKey("mail.smtp.password")
            || !props.containsKey("mail.smtp.host")) {
        log.error("Unable to send emails as email server configuration is missing");
        //throw new Exception("Unable to send emails as email server configuration is missing");
        return; // 
    }

    Session session = Session.getInstance(props, new javax.mail.Authenticator() {
        @Override
        protected PasswordAuthentication getPasswordAuthentication() {
            return new PasswordAuthentication(props.get("mail.smtp.username").toString(),
                    props.get("mail.smtp.password").toString());
        }
    });

    try {
        Message message = new MimeMessage(session);
        message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(email));
        message.setSubject(subject);
        message.setText(messageText);

        Transport.send(message);

        if (log.isDebugEnabled()) {
            log.debug(String.format("Sent email to %s", email));
            log.debug("with content: " + messageText);
        }
    } catch (MessagingException e) {
        log.error("Unable to send email to " + email, e);
        throw new Exception("Unable to send email to " + email, e);
    }
}

From source file:net.jetrix.mail.MailSessionManager.java

/**
 * Initialize the mail session from the specified configuration.
 *///w  w w  .j ava  2s. co  m
public void setConfiguration(final MailSessionConfig config) {
    try {
        if (!StringUtils.isBlank(config.getHostname())) {
            Properties props = new Properties();
            props.setProperty("mail.transport.protocol", "smtp");
            props.setProperty("mail.smtp.host", config.getHostname());
            props.setProperty("mail.smtp.port", String.valueOf(config.getPort()));
            props.setProperty("mail.smtp.auth", String.valueOf(config.isAuth()));

            session = Session.getInstance(props, new Authenticator() {
                protected PasswordAuthentication getPasswordAuthentication() {
                    return new PasswordAuthentication(config.getUsername(), config.getPassword());
                }
            });

            // enable the debug mode if requested
            if (config.isDebug()) {
                session.setDebug(true);
            }
        } else {
            log.warning("Unable to initialize the mail session, the hostname is missing");
        }
    } catch (Exception e) {
        log.log(Level.SEVERE, "Unable to initialize the mail session", e);
    }
}

From source file:jease.cms.service.Mails.java

/**
 * Sends an email synchronously./*from   www  .ja  v a 2s .  c om*/
 */
public void send(String sender, String recipients, String subject, String text) throws MessagingException {
    if (properties != null) {
        Session session = Session.getInstance(properties.asProperties(), new javax.mail.Authenticator() {
            protected PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication(properties.getUser(), properties.getPassword());
            }
        });
        MimeMessage message = new MimeMessage(session);
        message.setFrom(new InternetAddress(sender));
        message.setReplyTo(new InternetAddress[] { new InternetAddress(sender) });
        message.setRecipients(Message.RecipientType.TO, recipients);
        message.setSubject(subject, "utf-8");
        message.setSentDate(new Date());
        message.setHeader("Content-Type", "text/plain; charset=\"utf-8\"");
        message.setHeader("Content-Transfer-Encoding", "quoted-printable");
        message.setText(text, "utf-8");
        Transport.send(message);
    }
}

From source file:uk.ac.ox.it.ords.api.statistics.services.impl.SendMailTLS.java

private void sendMail() {
    if (sendEmails) {
        if (username == null) {
            log.error("Unable to send emails due to null user");
            return;
        }/*from   w  w  w  .  j ava2  s.  com*/
        Session session = Session.getInstance(props, new javax.mail.Authenticator() {
            @Override
            protected PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication(props.get("mail.smtp.username").toString(),
                        props.get("mail.smtp.password").toString());
            }
        });

        try {
            Message message = new MimeMessage(session);
            message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(email));
            message.setSubject(subject);
            message.setText(messageText);
            message.setFrom(new InternetAddress("ords@it.ox.ac.uk"));

            Transport.send(message);

            if (log.isDebugEnabled()) {
                log.debug(String.format("Sent email to %s (name %s)", email, username));
                log.debug("with content: " + messageText);
            }

        } catch (MessagingException e) {
            log.error("Unable to send email to " + email + " username " + username, e);
        }
    }
}