Example usage for javax.mail Session getInstance

List of usage examples for javax.mail Session getInstance

Introduction

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

Prototype

public static Session getInstance(Properties props, Authenticator authenticator) 

Source Link

Document

Get a new Session object.

Usage

From source file:com.mgmtp.perfload.perfalyzer.reporting.email.EmailReporter.java

private void sendMessage(final String subject, final String content) {
    try {/* ww w .  j a  v  a2s  . co  m*/
        Session session = (authenticator != null) ? Session.getInstance(smtpProps, authenticator)
                : Session.getInstance(smtpProps);

        MimeMessage msg = new MimeMessage(session);
        msg.setFrom(new InternetAddress(fromAddress));
        msg.setSubject(subject);
        msg.addRecipients(Message.RecipientType.TO, on(',').join(toAddresses));
        msg.setText(content, UTF_8.name(), "html");

        Transport.send(msg);
    } catch (MessagingException e) {
        log.error("Error while creating report e-mail", e);
    }
}

From source file:esg.node.components.notification.ESGNotifier.java

public void init() {
    log.info("Initializing ESGNotifier...");

    log.trace("getDataNodeManager() = " + getDataNodeManager());
    props = getDataNodeManager().getMatchingProperties("^mail.*");

    messageTemplate = loadMessage(props.getProperty("mail.notification.messageTemplateFile"));
    session = Session.getInstance(props, null);
    notificationDAO = new NotificationDAO(DatabaseResource.getInstance().getDataSource(), Utils.getNodeID());

    userid_pattern = Pattern.compile("@@esg_userid@@");
    update_info_pattern = Pattern.compile("@@update_info@@");

    performNextNotification();/*from ww  w  . ja v  a2 s  .co  m*/
}

From source file:com.appeligo.search.messenger.Messenger.java

/**
 * //from  ww w.  j a va 2  s.  c  o m
 * @param messages
 */
public int send(com.appeligo.search.entity.Message... messages) {
    int sent = 0;
    if (messages == null) {
        return 0;
    }
    for (com.appeligo.search.entity.Message message : messages) {
        User user = message.getUser();
        if (user != null) {
            boolean changed = false;
            boolean abort = false;
            if ((!user.isEnabled()) || (!user.isRegistrationComplete())
                    || (message.isSms() && (!user.isSmsValid()))) {
                abort = true;
                if (message.getExpires() == null) {
                    Calendar cal = Calendar.getInstance();
                    cal.add(Calendar.HOUR, 24);
                    message.setExpires(new Timestamp(cal.getTimeInMillis()));
                    changed = true;
                }
            }
            if (message.isSms() && user.isSmsValid() && (!user.isSmsOKNow())) {

                Calendar now = Calendar.getInstance(user.getTimeZone());
                now.set(Calendar.MILLISECOND, 0);
                now.set(Calendar.SECOND, 0);

                Calendar nextWindow = Calendar.getInstance(user.getTimeZone());
                nextWindow.setTime(user.getEarliestSmsTime());
                nextWindow.set(Calendar.MILLISECOND, 0);
                nextWindow.set(Calendar.SECOND, 0);
                nextWindow.add(Calendar.MINUTE, 1); // compensate for zeroing out millis, seconds

                nextWindow.set(now.get(Calendar.YEAR), now.get(Calendar.MONTH), now.get(Calendar.DATE));

                int nowMinutes = (now.get(Calendar.HOUR) * 60) + now.get(Calendar.MINUTE);
                int nextMinutes = (nextWindow.get(Calendar.HOUR) * 60) + nextWindow.get(Calendar.MINUTE);
                if (nowMinutes > nextMinutes) {
                    nextWindow.add(Calendar.HOUR, 24);
                }
                message.setDeferUntil(new Timestamp(nextWindow.getTimeInMillis()));
                changed = true;
                abort = true;
            }
            if (changed) {
                message.save();
            }
            if (abort) {
                continue;
            }
        }
        String to = message.getTo();
        String from = message.getFrom();
        String subject = message.getSubject();
        String body = message.getBody();
        String contentType = message.getMimeType();
        try {

            Properties props = new Properties();

            //Specify the desired SMTP server
            props.put("mail.smtp.host", mailHost);
            props.put("mail.smtp.port", Integer.toString(port));
            // create a new Session object
            Session session = null;
            if (password != null) {
                props.put("mail.smtp.auth", "true");
                session = Session.getInstance(props, new SMTPAuthenticator(smtpUser, password));
            } else {
                session = Session.getInstance(props, null);
            }
            session.setDebug(debug);

            // create a new MimeMessage object (using the Session created above)
            Message mimeMessage = new MimeMessage(session);
            mimeMessage.setFrom(new InternetAddress(from));
            mimeMessage.setRecipients(Message.RecipientType.TO,
                    new InternetAddress[] { new InternetAddress(to) });
            mimeMessage.setSubject(subject);
            mimeMessage.setContent(body.toString(), contentType);
            if (mailHost.trim().equals("")) {
                log.info("No Mail Host.  Would have sent:");
                log.info("From: " + from);
                log.info("To: " + to);
                log.info("Subject: " + subject);
                log.info(mimeMessage.getContent());
            } else {
                Transport.send(mimeMessage);
                sent++;
            }
            message.setSent(new Date());
        } catch (Throwable t) {
            message.failedAttempt();
            if (message.getAttempts() >= maxAttempts) {
                message.setExpires(new Timestamp(System.currentTimeMillis()));
            }
            log.error(t.getMessage(), t);
        }
    }
    return sent;
}

From source file:edu.stanford.muse.email.MboxEmailStore.java

public Folder openFolderWithoutCount(Store s, String fname) throws MessagingException {
    if (fname == null)
        fname = "INBOX";

    // ignore the store coming in, we need a new session and store
    // for each folder

    Session session = Session.getInstance(mstorProps, null);
    session.setDebug(DEBUG);/*w w  w.j ava  2  s.com*/

    // Get a Store object
    Store store = session.getStore(new URLName("mstor:" + fname));
    store.connect();

    //This is the root folder in the namespace provided
    //see http://docs.oracle.com/javaee/5/api/javax/mail/Store.html#getDefaultFolder%28%29
    Folder folder = store.getDefaultFolder();
    if (folder == null)
        throw new RuntimeException("Invalid folder: " + fname);

    log.info("Opening folder " + Util.blurPath(fname) + " in r/o mode...");
    try {
        folder.open(Folder.READ_ONLY);
    } catch (MessagingException me) {
        folder = null;
    }

    return folder;
}

From source file:bean.RedSocial.java

/**
 * //from www  .  ja  v a  2 s .c  o  m
 * @param _username
 * @param _email
 * @param _password 
 */
@Transactional(propagation = Propagation.REQUIRES_NEW, readOnly = false, rollbackFor = transactionalBusinessException.ComentariosViaException.class)
public void solicitarAcceso(String _username, String _email, String _password) {
    if (daoUsuario.obtenerUsuario(_username) != null) {
        throw new exceptionsBusiness.UsernameNoDisponible();
    }

    String hash = BCrypt.hashpw(_password, BCrypt.gensalt());

    Token token = new Token(_username, _email, hash);
    daoToken.guardarToken(token);

    //enviar token de acceso a la direccion email

    String correoEnvia = "skala2climbing@gmail.com";
    String claveCorreo = "vNspLa5H";

    // La configuracin para enviar correo
    Properties properties = new Properties();
    properties.put("mail.smtp.host", "smtp.gmail.com");
    properties.put("mail.smtp.starttls.enable", "true");
    properties.put("mail.smtp.port", "587");
    properties.put("mail.smtp.auth", "true");
    properties.put("mail.user", correoEnvia);
    properties.put("mail.password", claveCorreo);

    // Obtener la sesion
    Session session = Session.getInstance(properties, null);

    try {
        // Crear el cuerpo del mensaje
        MimeMessage mimeMessage = new MimeMessage(session);

        // Agregar quien enva el correo
        mimeMessage.setFrom(new InternetAddress(correoEnvia, "Skala2Climbing"));

        // Los destinatarios
        InternetAddress[] internetAddresses = { new InternetAddress(token.getEmail()) };

        // Agregar los destinatarios al mensaje
        mimeMessage.setRecipients(Message.RecipientType.TO, internetAddresses);

        // Agregar el asunto al correo
        mimeMessage.setSubject("Confirmacin de registro");

        // Creo la parte del mensaje
        MimeBodyPart mimeBodyPart = new MimeBodyPart();
        String ip = "90.165.24.228";
        mimeBodyPart.setText("Confirme su registro pulsando en el siguiente enlace: http://" + ip
                + ":8383/redsocialcolaborativaclientangularjs/confirmacion.html?" + "token="
                + token.getToken());
        //mimeBodyPart.setText("Confirme su registro pulsando en el siguiente enlace: "+"Enlace an no disponible");

        // Crear el multipart para agregar la parte del mensaje anterior
        Multipart multipart = new MimeMultipart();
        multipart.addBodyPart(mimeBodyPart);

        // Agregar el multipart al cuerpo del mensaje
        mimeMessage.setContent(multipart);

        // Enviar el mensaje
        Transport transport = session.getTransport("smtp");
        transport.connect(correoEnvia, claveCorreo);
        transport.sendMessage(mimeMessage, mimeMessage.getAllRecipients());
        transport.close();

    } catch (UnsupportedEncodingException | MessagingException ex) {
        throw new ErrorEnvioEmail();
    }

}

From source file:org.openadaptor.auxil.connector.smtp.SMTPConnection.java

/**
 * Set up javamail objects required to create connection to smtp server.
 * @throws ConnectionException/*from  www.j  av a  2 s  .  c om*/
 */
protected void createConnection() throws ConnectionException {
    Session session;

    try {
        log.debug("To: " + to);
        log.debug("Subject: " + subject);

        Properties props = System.getProperties();
        if (mailHost != null) {
            props.put("mail.smtp.host", mailHost);
            props.put("mail.smtp.port", mailHostPort);
        } else {
            throw new ConnectionException("FATAL: mailHost property not set", this);
        }
        // Get a Session object
        session = Session.getInstance(props, null);

        // construct the message
        message = new MimeMessage(session);
        if (from != null)
            message.setFrom(new InternetAddress(from));
        else
            message.setFrom();

        message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(to, false));
        if (cc != null)
            message.setRecipients(Message.RecipientType.CC, InternetAddress.parse(cc, false));
        if (bcc != null)
            message.setRecipients(Message.RecipientType.BCC, InternetAddress.parse(bcc, false));

        message.setSubject(subject);

        message.setHeader("X-Mailer", mailer);
        message.setSentDate(new Date());

    } catch (MessagingException me) {
        throw new ConnectionException(me.getMessage(), me, this);
    }
    log.debug("Successfully connected.");
    connected = true;
}

From source file:fr.xebia.cloud.amazon.aws.iam.AmazonAwsIamAccountCreator.java

public AmazonAwsIamAccountCreator(Environment environment) {
    this.environment = Preconditions.checkNotNull(environment);
    try {//from ww w .  j  av  a  2s  . c  om
        keyPairGenerator = KeyPairGenerator.getInstance("RSA", BOUNCY_CASTLE_PROVIDER_NAME);
        keyPairGenerator.initialize(1024, new SecureRandom());

        String credentialsFileName = "AwsCredentials-" + environment.getIdentifier() + ".properties";
        InputStream credentialsAsStream = Thread.currentThread().getContextClassLoader()
                .getResourceAsStream(credentialsFileName);
        Preconditions.checkNotNull(credentialsAsStream,
                "File '/" + credentialsFileName + "' NOT found in the classpath");
        AWSCredentials awsCredentials = new PropertiesCredentials(credentialsAsStream);
        iam = new AmazonIdentityManagementClient(awsCredentials);

        ses = new AmazonSimpleEmailServiceClient(awsCredentials);

        ec2 = new AmazonEC2Client(awsCredentials);
        ec2.setEndpoint("ec2.eu-west-1.amazonaws.com");

        InputStream smtpPropertiesAsStream = Thread.currentThread().getContextClassLoader()
                .getResourceAsStream("smtp.properties");
        Preconditions.checkNotNull(smtpPropertiesAsStream,
                "File '/smtp.properties' NOT found in the classpath");

        final Properties smtpProperties = new Properties();
        smtpProperties.load(smtpPropertiesAsStream);

        mailSession = Session.getInstance(smtpProperties, null);
        mailTransport = mailSession.getTransport();
        if (smtpProperties.containsKey("mail.username")) {
            mailTransport.connect(smtpProperties.getProperty("mail.username"),
                    smtpProperties.getProperty("mail.password"));
        } else {
            mailTransport.connect();
        }
        try {
            mailFrom = new InternetAddress(smtpProperties.getProperty("mail.from"));
        } catch (Exception e) {
            throw new MessagingException("Exception parsing 'mail.from' from 'smtp.properties'", e);
        }

    } catch (Exception e) {
        throw Throwables.propagate(e);
    }
}

From source file:de.betterform.connector.smtp.SMTPSubmissionHandler.java

private void send(String uri, byte[] data, String encoding, String mediatype) throws Exception {
    URL url = new URL(uri);
    String recipient = url.getPath();

    String server = null;/*from w w w.j a  va2s  .c  om*/
    String port = null;
    String sender = null;
    String subject = null;
    String username = null;
    String password = null;

    StringTokenizer headers = new StringTokenizer(url.getQuery(), "&");

    while (headers.hasMoreTokens()) {
        String token = headers.nextToken();

        if (token.startsWith("server=")) {
            server = URLDecoder.decode(token.substring("server=".length()), "UTF-8");

            continue;
        }

        if (token.startsWith("port=")) {
            port = URLDecoder.decode(token.substring("port=".length()), "UTF-8");

            continue;
        }

        if (token.startsWith("sender=")) {
            sender = URLDecoder.decode(token.substring("sender=".length()), "UTF-8");

            continue;
        }

        if (token.startsWith("subject=")) {
            subject = URLDecoder.decode(token.substring("subject=".length()), "UTF-8");

            continue;
        }

        if (token.startsWith("username=")) {
            username = URLDecoder.decode(token.substring("username=".length()), "UTF-8");

            continue;
        }

        if (token.startsWith("password=")) {
            password = URLDecoder.decode(token.substring("password=".length()), "UTF-8");

            continue;
        }
    }

    if (LOGGER.isDebugEnabled()) {
        LOGGER.debug("smtp server '" + server + "'");

        if (username != null) {
            LOGGER.debug("smtp-auth username '" + username + "'");
        }

        LOGGER.debug("mail sender '" + sender + "'");
        LOGGER.debug("subject line '" + subject + "'");
    }

    Properties properties = System.getProperties();
    properties.put("mail.debug", String.valueOf(LOGGER.isDebugEnabled()));
    properties.put("mail.smtp.from", sender);
    properties.put("mail.smtp.host", server);

    if (port != null) {
        properties.put("mail.smtp.port", port);
    }

    if (username != null) {
        properties.put("mail.smtp.auth", String.valueOf(true));
        properties.put("mail.smtp.user", username);
    }

    Session session = Session.getInstance(properties, new SMTPAuthenticator(username, password));

    MimeMessage message = null;
    if (mediatype.startsWith("multipart/")) {
        message = new MimeMessage(session, new ByteArrayInputStream(data));
    } else {
        message = new MimeMessage(session);
        if (mediatype.toLowerCase().indexOf("charset=") == -1) {
            mediatype += "; charset=\"" + encoding + "\"";
        }
        message.setText(new String(data, encoding), encoding);
        message.setHeader("Content-Type", mediatype);
    }

    message.setRecipient(RecipientType.TO, new InternetAddress(recipient));
    message.setSubject(subject);
    message.setSentDate(new Date());

    Transport.send(message);
}

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

@Override
public boolean loadConfiguration(ParameterInclude paramIncl) throws AxisFault {
    String address = ParamUtils.getOptionalParam(paramIncl, MailConstants.TRANSPORT_MAIL_ADDRESS);
    if (address == null) {
        return false;
    } else {//from ww w.j  av a  2s .  com
        try {
            emailAddress = new InternetAddress(address);
        } catch (AddressException e) {
            throw new AxisFault("Invalid email address specified by '" + MailConstants.TRANSPORT_MAIL_ADDRESS
                    + "' parameter :: " + e.getMessage());
        }

        List<Parameter> params = paramIncl.getParameters();
        Properties props = new Properties();
        for (Parameter p : params) {
            if (p.getName().startsWith("mail.")) {
                props.setProperty(p.getName(), (String) p.getValue());
            }

            if (MailConstants.MAIL_POP3_USERNAME.equals(p.getName())
                    || MailConstants.MAIL_IMAP_USERNAME.equals(p.getName())) {
                userName = (String) p.getValue();
            }
            if (MailConstants.MAIL_POP3_PASSWORD.equals(p.getName())
                    || MailConstants.MAIL_IMAP_PASSWORD.equals(p.getName())) {
                password = (String) p.getValue();
            }
            if (MailConstants.TRANSPORT_MAIL_PROTOCOL.equals(p.getName())) {
                protocol = (String) p.getValue();
            }
        }

        session = Session.getInstance(props, null);
        MailUtils.setupLogging(session, log, paramIncl);

        contentType = ParamUtils.getOptionalParam(paramIncl, MailConstants.TRANSPORT_MAIL_CONTENT_TYPE);
        try {
            String replyAddress = ParamUtils.getOptionalParam(paramIncl,
                    MailConstants.TRANSPORT_MAIL_REPLY_ADDRESS);
            if (replyAddress != null) {
                this.replyAddress = new InternetAddress(replyAddress);
            }
        } catch (AddressException e) {
            throw new AxisFault("Invalid email address specified by '"
                    + MailConstants.TRANSPORT_MAIL_REPLY_ADDRESS + "' parameter :: " + e.getMessage());
        }

        folder = ParamUtils.getOptionalParam(paramIncl, MailConstants.TRANSPORT_MAIL_FOLDER);

        addPreserveHeaders(
                ParamUtils.getOptionalParam(paramIncl, MailConstants.TRANSPORT_MAIL_PRESERVE_HEADERS));
        addRemoveHeaders(ParamUtils.getOptionalParam(paramIncl, MailConstants.TRANSPORT_MAIL_REMOVE_HEADERS));

        String option = ParamUtils.getOptionalParam(paramIncl,
                MailConstants.TRANSPORT_MAIL_ACTION_AFTER_PROCESS);
        actionAfterProcess = MailTransportListener.MOVE.equals(option) ? PollTableEntry.MOVE
                : PollTableEntry.DELETE;
        option = ParamUtils.getOptionalParam(paramIncl, MailConstants.TRANSPORT_MAIL_ACTION_AFTER_FAILURE);
        actionAfterFailure = MailTransportListener.MOVE.equals(option) ? PollTableEntry.MOVE
                : PollTableEntry.DELETE;

        moveAfterProcess = ParamUtils.getOptionalParam(paramIncl,
                MailConstants.TRANSPORT_MAIL_MOVE_AFTER_PROCESS);
        moveAfterFailure = ParamUtils.getOptionalParam(paramIncl,
                MailConstants.TRANSPORT_MAIL_MOVE_AFTER_FAILURE);

        String processInParallel = ParamUtils.getOptionalParam(paramIncl,
                MailConstants.TRANSPORT_MAIL_PROCESS_IN_PARALLEL);
        if (processInParallel != null) {
            processingMailInParallel = Boolean.parseBoolean(processInParallel);
            if (log.isDebugEnabled() && processingMailInParallel) {
                log.debug("Parallel mail processing enabled for : " + address);
            }
        }

        String pollInParallel = ParamUtils.getOptionalParam(paramIncl,
                BaseConstants.TRANSPORT_POLL_IN_PARALLEL);
        if (pollInParallel != null) {
            setConcurrentPollingAllowed(Boolean.parseBoolean(pollInParallel));
            if (log.isDebugEnabled() && isConcurrentPollingAllowed()) {
                log.debug("Concurrent mail polling enabled for : " + address);
            }
        }

        String strMaxRetryCount = ParamUtils.getOptionalParam(paramIncl, MailConstants.MAX_RETRY_COUNT);
        if (strMaxRetryCount != null) {
            maxRetryCount = Integer.parseInt(strMaxRetryCount);
        }

        String strReconnectTimeout = ParamUtils.getOptionalParam(paramIncl, MailConstants.RECONNECT_TIMEOUT);
        if (strReconnectTimeout != null) {
            reconnectTimeout = Integer.parseInt(strReconnectTimeout) * 1000;
        }

        return super.loadConfiguration(paramIncl);
    }
}

From source file:org.pentaho.platform.scheduler2.email.Emailer.java

public boolean send() {
    String from = props.getProperty("mail.from.default");
    String fromName = props.getProperty("mail.from.name");
    String to = props.getProperty("to");
    String cc = props.getProperty("cc");
    String bcc = props.getProperty("bcc");
    boolean authenticate = "true".equalsIgnoreCase(props.getProperty("mail.smtp.auth"));
    String subject = props.getProperty("subject");
    String body = props.getProperty("body");

    logger.info("Going to send an email to " + to + " from " + from + " with the subject '" + subject
            + "' and the body " + body);

    try {/* w w w.ja v  a2s.c om*/
        // Get a Session object
        Session session;

        if (authenticate) {
            session = Session.getInstance(props, authenticator);
        } else {
            session = Session.getInstance(props);
        }

        // if debugging is not set in the email config file, then default to false
        if (!props.containsKey("mail.debug")) { //$NON-NLS-1$
            session.setDebug(false);
        }

        // construct the message
        MimeMessage msg = new MimeMessage(session);
        Multipart multipart = new MimeMultipart();

        if (from != null) {
            msg.setFrom(new InternetAddress(from, fromName));
        } else {
            // There should be no way to get here
            logger.error("Email.ERROR_0012_FROM_NOT_DEFINED"); //$NON-NLS-1$
        }

        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());
        }

        if (attachment == null) {
            logger.error("Email.ERROR_0015_ATTACHMENT_FAILED"); //$NON-NLS-1$
            return false;
        }

        ByteArrayDataSource dataSource = new ByteArrayDataSource(attachment, attachmentMimeType);

        if (body != null) {
            MimeBodyPart bodyMessagePart = new MimeBodyPart();
            bodyMessagePart.setText(body, LocaleHelper.getSystemEncoding());
            multipart.addBodyPart(bodyMessagePart);
        }

        // attach the file to the message
        MimeBodyPart attachmentBodyPart = new MimeBodyPart();
        attachmentBodyPart.setDataHandler(new DataHandler(dataSource));
        attachmentBodyPart.setFileName(MimeUtility.encodeText(attachmentName, "UTF-8", null));
        multipart.addBodyPart(attachmentBodyPart);

        // add the Multipart to the message
        msg.setContent(multipart);

        msg.setHeader("X-Mailer", Emailer.MAILER); //$NON-NLS-1$
        msg.setSentDate(new Date());

        Transport.send(msg);

        return true;
    } catch (SendFailedException e) {
        logger.error("Email.ERROR_0011_SEND_FAILED -" + to, e); //$NON-NLS-1$
    } catch (AuthenticationFailedException e) {
        logger.error("Email.ERROR_0014_AUTHENTICATION_FAILED - " + to, e); //$NON-NLS-1$
    } catch (Throwable e) {
        logger.error("Email.ERROR_0011_SEND_FAILED - " + to, e); //$NON-NLS-1$
    }
    return false;
}