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:cz.filmtit.userspace.Emailer.java

/**
 * Sends an email with parameters that has been collected before in the fields of the class.
 * @return Sign if the email has been successfully sent
 */// www  . j av  a  2 s  .c  o  m
public boolean send() {
    if (hasCollectedData()) {
        // send mail;
        javax.mail.Session session;
        logger.info("Emailer",
                "Create session for mail login " + (String) configuration.getProperty("mail.filmtit.address")
                        + " password" + (String) configuration.getProperty("mail.filmtit.password"));
        session = javax.mail.Session.getDefaultInstance(configuration, new javax.mail.Authenticator() {
            protected PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication((String) configuration.getProperty("mail.filmtit.address"),
                        (String) configuration.getProperty("mail.filmtit.password"));
            }
        });
        session.setDebug(true);
        javax.mail.internet.MimeMessage message = new javax.mail.internet.MimeMessage(session);
        try {
            message.addRecipient(Message.RecipientType.TO, new InternetAddress(this.email));
            message.setFrom(new InternetAddress((String) configuration.getProperty("mail.filmtit.address")));
            message.setSubject(this.subject);
            message.setText(this.message);

            Transport transportSSL = session.getTransport();
            transportSSL.connect((String) configuration.getProperty("mail.smtps.host"),
                    Integer.parseInt(configuration.getProperty("mail.smtps.port")),
                    (String) configuration.getProperty("mail.filmtit.address"),
                    (String) configuration.getProperty("mail.filmtit.password")); // account used
            transportSSL.sendMessage(message, message.getAllRecipients());
            transportSSL.close();
        } catch (MessagingException ex) {
            logger.error("Emailer", "An error while sending an email. " + ex);
        }
        return true;
    }
    logger.warning("Emailer", "Emailer has not collected all data to be able to send an email.");
    return false;
}

From source file:io.kodokojo.service.SmtpEmailSender.java

@Override
public void send(List<String> to, List<String> cc, List<String> ci, String subject, String content,
        boolean htmlContent) {
    if (CollectionUtils.isEmpty(to)) {
        throw new IllegalArgumentException("to must be defined.");
    }//from   www.j  a  va2 s . com
    if (isBlank(content)) {
        throw new IllegalArgumentException("content must be defined.");
    }
    Session session = Session.getDefaultInstance(properties, new Authenticator() {
        @Override
        protected PasswordAuthentication getPasswordAuthentication() {
            return new PasswordAuthentication(username, password);
        }
    });
    Message message = new MimeMessage(session);
    try {
        message.setFrom(from);
        message.setSubject(subject);
        InternetAddress[] toInternetAddress = convertToInternetAddress(to);
        message.setRecipients(Message.RecipientType.TO, toInternetAddress);
        if (CollectionUtils.isNotEmpty(cc)) {
            InternetAddress[] ccInternetAddress = convertToInternetAddress(cc);
            message.setRecipients(Message.RecipientType.CC, ccInternetAddress);
        }
        if (CollectionUtils.isNotEmpty(ci)) {
            InternetAddress[] ciInternetAddress = convertToInternetAddress(ci);
            message.setRecipients(Message.RecipientType.BCC, ciInternetAddress);
        }
        if (htmlContent) {
            message.setContent(content, "text/html");
        } else {
            message.setText(content);
        }
        message.setHeader("X-Mailer", "Kodo Kojo mailer");
        message.setSentDate(new Date());
        Transport.send(message);

    } catch (MessagingException e) {
        LOGGER.error("Unable to send email to {} with subject '{}'", StringUtils.join(to, ","), subject, e);
    }
}

From source file:com.freemarker.mail.GMail.java

public boolean sendMailUsingJavaMailAPI(String to, String message1, HttpServletRequest req, String mid,
        String createdby, String pname, String mname) {
    String FinalMessage = new FreeMarkerMailTemplateCreater().createAndReturnTemplateDataMapping(message1,
            getTemplateLocation(req), mid, createdby, pname, mname);
    String from = "analytixdstest@gmail.com";
    final String username = "analytixdstest@gmail.com";
    final String password = "analytix000";
    String host = "smtp.gmail.com";
    Properties props = new Properties();
    props.put("mail.smtp.auth", "true");
    props.put("mail.smtp.starttls.enable", "true");
    props.put("mail.smtp.host", host);
    props.put("mail.smtp.port", "587");
    Session session = Session.getInstance(props, new javax.mail.Authenticator() {
        protected PasswordAuthentication getPasswordAuthentication() {
            return new PasswordAuthentication(username, password);
        }/*w w  w. ja va  2 s .com*/
    });
    try {
        Message message = new MimeMessage(session);
        message.setFrom(new InternetAddress(from));
        message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(to));
        message.setContent(FinalMessage, "text/html; charset=utf-8");
        message.saveChanges();
        message.setSubject("Analytix Test Mail");
        Transport.send(message);
        return true;
    } catch (MessagingException e) {
        return false;

    }
}

From source file:at.molindo.notify.channel.mail.SimpleMailClient.java

protected Session createSmtpSession() {
    final Properties props = new Properties();
    props.setProperty("mail.smtp.host", _server);
    props.setProperty("mail.smtp.port", Integer.toString(_port != null ? _port : _security.getDefaultPort()));
    props.setProperty("mail.smtp.auth", Boolean.toString(_user != null));
    if (_security == Security.TLS) {
        props.setProperty("mail.smtp.starttls.enable", "true");
    } else if (_security == Security.SSL) {
        props.put("mail.smtp.ssl", "true");
        props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
    }//  w  w  w .j  a va  2  s .  c  o m
    // props.put("mail.debug", "true");
    return Session.getInstance(props, new javax.mail.Authenticator() {

        @Override
        protected PasswordAuthentication getPasswordAuthentication() {
            if (_user != null) {
                return new PasswordAuthentication(_user, _password);
            } else {
                return null;
            }
        }
    });
}

From source file:eagle.common.email.EagleMailClient.java

public EagleMailClient(AbstractConfiguration configuration) {
    try {/*from   w  w w.  ja va2s  .  c  o m*/
        ConcurrentMapConfiguration con = (ConcurrentMapConfiguration) configuration;
        velocityEngine = new VelocityEngine();
        velocityEngine.setProperty(RuntimeConstants.RESOURCE_LOADER, "classpath");
        velocityEngine.setProperty("classpath.resource.loader.class", ClasspathResourceLoader.class.getName());
        velocityEngine.init();

        con.setProperty("mail.transport.protocol", "smtp");
        final Properties config = con.getProperties();
        if (Boolean.parseBoolean(config.getProperty(AUTH_CONFIG))) {
            session = Session.getDefaultInstance(config, new Authenticator() {
                protected PasswordAuthentication getPasswordAuthentication() {
                    return new PasswordAuthentication(config.getProperty(USER_CONFIG),
                            config.getProperty(PWD_CONFIG));
                }
            });
        } else
            session = Session.getDefaultInstance(config, new Authenticator() {
            });
        final String debugMode = config.getProperty(DEBUG_CONFIG, "false");
        final boolean debug = Boolean.parseBoolean(debugMode);
        session.setDebug(debug);
    } catch (Exception e) {
        LOG.error("Failed connect to smtp server", e);
    }
}

From source file:de.hska.ld.core.service.impl.MailServiceImpl.java

@Override
public void sendMail(String fullName, String email, String templateFileName, Map<String, Object> model) {
    ;/*from w  ww  . j  a  v  a 2s  .co  m*/
    if (Boolean.parseBoolean(env.getProperty("email.enabled"))) {
        Locale locale = LocaleContextHolder.getLocale();
        ResourceBundle bundle = ResourceBundle.getBundle("messages", locale);
        model.put("dear", bundle.getString("email.dear"));
        model.put("fullName", fullName);
        model.put("greeting", bundle.getString("email.greeting"));

        String text = VelocityEngineUtils.mergeTemplateIntoString(velocityEngine,
                "templates/mail/" + templateFileName, "UTF-8", model);

        Properties properties = getMailProperties();

        Session session = Session.getInstance(properties, new javax.mail.Authenticator() {
            protected PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication(MAIL_PROPERTIES.getProperty("email.username"),
                        MAIL_PROPERTIES.getProperty("email.password"));
            }
        });

        try {
            MimeMessage message = new MimeMessage(session);
            MimeMessageHelper helper = new MimeMessageHelper(message, true);
            helper.setFrom(MAIL_PROPERTIES.getProperty("email.from.system"));
            helper.setTo(email);
            helper.setSubject(model.containsKey("subject") ? (String) model.get("subject") : "");
            helper.setText(text, true);
            Transport.send(message);
        } catch (MessagingException e) {
            e.printStackTrace();
        }
    }
}

From source file:org.openmrs.module.sync.SyncMailUtil.java

public static Session createSession(Map<String, String> settings) {
    Properties props = new Properties();
    props.setProperty("mail.transport.protocol", settings.get(MAIL_TRANSPORT_PROTOCOL));
    props.setProperty("mail.smtp.host", settings.get(MAIL_SMTP_HOST));
    props.setProperty("mail.smtp.port", settings.get(MAIL_SMTP_PORT));
    props.setProperty("mail.smtp.auth", settings.get(MAIL_SMTP_AUTH));
    props.setProperty("mail.smtp.starttls.enable", settings.get(MAIL_SMTP_STARTTLS_ENABLE));
    props.setProperty("mail.from", settings.get(MAIL_FROM));
    props.setProperty("mail.debug", settings.get(MAIL_DEBUG));

    final String mailUser = settings.get(MAIL_USER);
    final String mailPw = settings.get(MAIL_PASSWORD);

    Authenticator auth = new Authenticator() {
        @Override/*from   w  ww. j a  v a  2s  .com*/
        public PasswordAuthentication getPasswordAuthentication() {
            return new PasswordAuthentication(mailUser, mailPw);
        }
    };
    return Session.getInstance(props, auth);
}

From source file:net.ymate.module.mailsender.MailSendServerCfgMeta.java

public Session createIfNeed() {
    if (__mailSession == null) {
        synchronized (this) {
            if (__mailSession == null) {
                Properties _props = new Properties();
                _props.put("mail.smtp.host", smtpHost);
                _props.put("mail.smtp.auth", needAuth);
                _props.put("mail.transport.protocol", "smtp");
                if (tlsEnabled) {
                    _props.put("mail.smtp.starttls.enable", true);
                    _props.put("mail.smtp.socketFactory.port", smtpPort);
                    _props.put("mail.smtp.socketFactory.class", StringUtils
                            .defaultIfBlank(socketFactoryClassName, "javax.net.ssl.SSLSocketFactory"));
                    _props.put("mail.smtp.socketFactory.fallback", socketFactoryFallback);
                } else {
                    _props.put("mail.smtp.port", smtpPort);
                }//from w w w.  ja v a 2 s  .co m
                //
                __mailSession = Session.getInstance(_props, new Authenticator() {
                    @Override
                    protected PasswordAuthentication getPasswordAuthentication() {
                        return new PasswordAuthentication(smtpUsername, smtpPassword);
                    }
                });
                __mailSession.setDebug(debugEnabled);
            }
        }
    }
    return __mailSession;
}

From source file:org.restcomm.connect.email.EmailService.java

public EmailService(final Configuration config) {
    this.observers = new ArrayList<ActorRef>();
    configuration = config;/*from   ww w  .  ja  v  a  2s  . com*/
    this.host = configuration.getString("host");
    this.port = configuration.getString("port");
    this.user = configuration.getString("user");
    this.password = configuration.getString("password");
    if ((user != null && !user.isEmpty()) || (password != null && !password.isEmpty())
            || (port != null && !port.isEmpty()) || (host != null && !host.isEmpty())) {
        //allow smtp over ssl if port is set to 465
        if ("465".equals(port)) {
            this.isSslEnabled = true;
            useSSLSmtp();
        } else {
            //TLS uses port 587
            properties.setProperty("mail.smtp.host", host);
            properties.setProperty("mail.smtp.user", user);
            properties.setProperty("mail.smtp.password", password);
            properties.setProperty("mail.smtp.port", port);
        }
        properties.setProperty("mail.smtp.starttls.enable", "true");
        properties.setProperty("mail.transport.protocol", "smtps");
        // properties.setProperty("mail.smtp.ssl.enable", "true");
        properties.setProperty("mail.smtp.auth", "true");
        session = Session.getInstance(properties, new javax.mail.Authenticator() {
            protected PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication(user, password);
            }
        });
    }
}

From source file:rapture.mail.Mailer.java

public static Session getSession(final SMTPConfig config) {
    // Create some properties and get the default Session.
    Properties props = System.getProperties();
    props.put("mail.smtp.auth", config.isAuthentication());
    props.put("mail.smtp.starttls.enable", config.isTlsenable());
    props.put("mail.smtp.starttls.required", config.isTlsrequired());
    props.put("mail.smtp.host", config.getHost());
    props.put("mail.smtp.port", config.getPort());
    Session session = Session.getInstance(props, new javax.mail.Authenticator() {
        @Override/*w ww.  j a v  a 2 s  .c o  m*/
        protected PasswordAuthentication getPasswordAuthentication() {
            return new PasswordAuthentication(config.getUsername(), config.getPassword());
        }
    });
    return session;
}