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:org.pentaho.reporting.engine.classic.extensions.modules.mailer.MailProcessor.java

public static void performBursting(final MailDefinition definition)
        throws ReportProcessingException, MessagingException, ContentIOException {
    final Session session = Session.getInstance(definition.getSessionProperties(),
            definition.getAuthenticator());
    performBursting(definition, session);
}

From source file:org.georchestra.ldapadmin.ws.emails.EmailController.java

/**
 * Send an email based on json payload. Recipient should be present in LDAP directory or in configured whitelist.
 *
 * Json sent should have following keys :
 *
 * - to      : json array of email to send email to ex: ["you@rm.fr", "another-guy@rm.fr"]
 * - cc      : json array of email to 'CC' email ex: ["him@rm.fr"]
 * - bcc     : json array of email to add recipient as blind CC ["secret@rm.fr"]
 * - subject : subject of email//from  w w  w  .  j  ava  2  s.  co  m
 * - body    : Body of email
 *
 * Either 'to', 'cc' or 'bcc' parameter must be present in request. 'subject' and 'body' are mandatory.
 *
 * complete json example :
 *
 * {
 *   "to": ["you@rm.fr", "another-guy@rm.fr"],
 *   "cc": ["him@rm.fr"],
 *   "bcc": ["secret@rm.fr"],
 *   "subject": "test email",
 *   "body": "Hi, this a test EMail, please do not reply."
 * }
 *
 */
@RequestMapping(value = "/emailProxy", method = RequestMethod.POST, produces = "application/json; charset=utf-8", consumes = "application/json")
@ResponseBody
public String emailProxy(@RequestBody String rawRequest, HttpServletRequest request)
        throws JSONException, MessagingException, UnsupportedEncodingException, DataServiceException {

    JSONObject payload = new JSONObject(rawRequest);
    InternetAddress[] to = this.populateRecipient("to", payload);
    InternetAddress[] cc = this.populateRecipient("cc", payload);
    InternetAddress[] bcc = this.populateRecipient("bcc", payload);

    this.checkSubject(payload);
    this.checkBody(payload);
    this.checkRecipient(to, cc, bcc);

    LOG.info("EMail request : user=" + request.getHeader("sec-username") + " to="
            + this.extractAddress("to", payload) + " cc=" + this.extractAddress("cc", payload) + " bcc="
            + this.extractAddress("bcc", payload) + " roles=" + request.getHeader("sec-roles"));

    LOG.debug("EMail request : " + payload.toString());

    // Instanciate MimeMessage
    Properties props = System.getProperties();
    props.put("mail.smtp.host", this.emailFactory.getSmtpHost());
    props.put("mail.protocol.port", this.emailFactory.getSmtpPort());
    Session session = Session.getInstance(props, null);
    MimeMessage message = new MimeMessage(session);

    // Generate From header
    InternetAddress from = new InternetAddress();
    from.setAddress(this.georConfig.getProperty("emailProxyFromAddress"));
    from.setPersonal(request.getHeader("sec-firstname") + " " + request.getHeader("sec-lastname"));
    message.setFrom(from);

    // Generate Reply-to header
    InternetAddress replyTo = new InternetAddress();
    replyTo.setAddress(request.getHeader("sec-email"));
    replyTo.setPersonal(request.getHeader("sec-firstname") + " " + request.getHeader("sec-lastname"));
    message.setReplyTo(new Address[] { replyTo });

    // Generate to, cc and bcc headers
    if (to.length > 0)
        message.setRecipients(Message.RecipientType.TO, to);
    if (cc.length > 0)
        message.setRecipients(Message.RecipientType.CC, cc);
    if (bcc.length > 0)
        message.setRecipients(Message.RecipientType.BCC, bcc);

    // Add subject and body
    message.setSubject(payload.getString("subject"), "UTF-8");
    message.setText(payload.getString("body"), "UTF-8", "plain");
    message.setSentDate(new Date());

    // finally send message
    Transport.send(message);

    JSONObject res = new JSONObject();
    res.put("success", true);
    return res.toString();
}

From source file:com.netflix.genie.server.jobmanager.impl.JobMonitorImpl.java

/**
 * Check the properties file to figure out if an email needs to be sent at
 * the end of the job. If yes, get mail properties and try and send email
 * about Job Status.//from w w  w  .j av a  2 s .com
 *
 * @return 0 for success, -1 for failure
 * @throws GenieException on issue
 */
private boolean sendEmail(final String emailTo, final boolean killed) throws GenieException {
    LOG.debug("called");
    final Job job = this.jobService.getJob(this.jobId);

    if (!this.config.getBoolean("com.netflix.genie.server.mail.enable", false)) {
        LOG.warn("Email is disabled but user has specified an email address.");
        return false;
    }

    // Sender's email ID
    final String fromEmail = this.config.getString("com.netflix.genie.server.mail.smpt.from",
            "no-reply-genie@geniehost.com");
    LOG.info("From email address to use to send email: " + fromEmail);

    // Set the smtp server hostname. Use localhost as default
    final String smtpHost = this.config.getString("com.netflix.genie.server.mail.smtp.host", "localhost");
    LOG.debug("Email smtp server: " + smtpHost);

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

    // Setup mail server
    properties.setProperty("mail.smtp.host", smtpHost);

    // check whether authentication should be turned on
    Authenticator auth = null;

    if (this.config.getBoolean("com.netflix.genie.server.mail.smtp.auth", false)) {
        LOG.debug("Email Authentication Enabled");

        properties.put("mail.smtp.starttls.enable", "true");
        properties.put("mail.smtp.auth", "true");

        final String userName = config.getString("com.netflix.genie.server.mail.smtp.user");
        final String password = config.getString("com.netflix.genie.server.mail.smtp.password");

        if (userName == null || password == null) {
            LOG.error("Authentication is enabled and username/password for smtp server is null");
            return false;
        }
        LOG.debug("Constructing authenticator object with username" + userName + " and password " + password);
        auth = new SMTPAuthenticator(userName, password);
    } else {
        LOG.debug("Email authentication not enabled.");
    }

    // Get the default Session object.
    final Session session = Session.getInstance(properties, auth);

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

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

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

        JobStatus jobStatus;

        if (killed) {
            jobStatus = JobStatus.KILLED;
        } else {
            jobStatus = job.getStatus();
        }

        // Set Subject: header field
        message.setSubject("Genie Job " + job.getName() + " completed with Status: " + jobStatus);

        // Now set the actual message
        final String body = "Your Genie Job is complete\n\n" + "Job ID: " + job.getId() + "\n" + "Job Name: "
                + job.getName() + "\n" + "Status: " + job.getStatus() + "\n" + "Status Message: "
                + job.getStatusMsg() + "\n" + "Output Base URL: " + job.getOutputURI() + "\n";

        message.setText(body);

        // Send message
        Transport.send(message);
        LOG.info("Sent email message successfully....");
        return true;
    } catch (final MessagingException mex) {
        LOG.error("Got exception while sending email", mex);
        return false;
    }
}

From source file:org.socraticgrid.hl7.ucs.nifi.processor.SendEmail.java

private String sendEmail(String emailSubject, String fromEmail, String toEmail, String emailBody,
        String mimeType, String charset, String smtpServerUrl, String smtpServerPort, String username,
        String password, ServiceStatusController serviceStatusControllerService) throws Exception {

    String statusMessage = "Email sent successfully to " + toEmail;

    Properties props = new Properties();
    props.put("mail.smtp.auth", "true");
    props.put("mail.smtp.starttls.enable", "true");
    props.put("mail.smtp.host", smtpServerUrl);
    props.put("mail.smtp.port", smtpServerPort);

    Session session = Session.getInstance(props, new javax.mail.Authenticator() {
        protected PasswordAuthentication getPasswordAuthentication() {
            return new PasswordAuthentication(username, password);
        }//from www  .  ja  v a  2 s.  co m
    });
    try {
        MimeMessage message = new MimeMessage(session);
        message.setFrom(new InternetAddress(fromEmail));
        message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(toEmail));
        message.setSubject(emailSubject);
        message.setContent(emailBody, mimeType + "; charset=" + charset);
        Transport.send(message);
        getLogger().info("Email sent successfully!");
        serviceStatusControllerService.updateServiceStatus("EMAIL", Status.AVAILABLE);
    } catch (MessagingException e) {
        serviceStatusControllerService.updateServiceStatus("EMAIL", Status.UNAVAILABLE);
        getLogger().error("Unable to send Email! Reason : " + e.getMessage(), e);
        statusMessage = "Unable to send Email! Reason : " + e.getMessage();
        throw new RuntimeException(e);
    }
    return statusMessage;
}

From source file:io.uengine.mail.MailAsyncService.java

private Session setMailProperties(final String toUser) {
    Properties props = new Properties();
    props.put("mail.smtp.auth", auth);
    props.put("mail.smtp.starttls.enable", starttls);
    props.put("mail.smtp.host", host);
    props.put("mail.smtp.port", port);

    LogOutputStream loggerToStdOut = new LogOutputStream() {
        @Override/*ww  w  .j av a  2s.c om*/
        protected void processLine(String line, int level) {
            logger.debug("[JavaMail] [{}] {}", toUser, line);
        }
    };

    Session session = Session.getInstance(props, new Authenticator() {
        protected PasswordAuthentication getPasswordAuthentication() {
            return new PasswordAuthentication(account, password);
        }
    });
    session.setDebug(true);
    session.setDebugOut(new PrintStream(loggerToStdOut));
    return session;
}

From source file:it.cnr.icar.eric.server.event.EmailNotifier.java

private void postMail(String endpoint, String message, String subject, String contentType)
        throws MessagingException {

    // get the SMTP address
    String smtpHost = RegistryProperties.getInstance().getProperty("eric.server.event.EmailNotifier.smtp.host");

    // get the FROM address
    String fromAddress = RegistryProperties.getInstance()
            .getProperty("eric.server.event.EmailNotifier.smtp.from", "eric@localhost");

    // get the TO address that follows 'mailto:'
    String recipient = endpoint.substring(7);

    String smtpPort = RegistryProperties.getInstance().getProperty("eric.server.event.EmailNotifier.smtp.port",
            null);/*  ww  w.  ja va  2 s . com*/

    String smtpAuth = RegistryProperties.getInstance().getProperty("eric.server.event.EmailNotifier.smtp.auth",
            null);

    String smtpDebug = RegistryProperties.getInstance()
            .getProperty("eric.server.event.EmailNotifier.smtp.debug", "false");

    //Set the host smtp address
    Properties props = new Properties();
    props.put("mail.transport.protocol", "smtp");
    props.put("mail.smtp.debug", smtpDebug);
    props.put("mail.smtp.host", smtpHost);
    if ((smtpPort != null) && (smtpPort.length() > 0)) {
        props.put("mail.smtp.port", smtpPort);
    }
    Session session;
    if ("tls".equals(smtpAuth)) {
        // get the username
        String userName = RegistryProperties.getInstance()
                .getProperty("eric.server.event.EmailNotifier.smtp.user", null);

        String password = RegistryProperties.getInstance()
                .getProperty("eric.server.event.EmailNotifier.smtp.password", null);

        Authenticator authenticator = new MyAuthenticator(userName, password);
        props.put("mail.user", userName);
        props.put("mail.smtp.auth", "true");
        props.put("mail.smtp.starttls.enable", "true");

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

    session.setDebug(Boolean.valueOf(smtpDebug).booleanValue());

    // create a message
    Message msg = new MimeMessage(session);

    // set the from and to address
    InternetAddress addressFrom = new InternetAddress(fromAddress);
    msg.setFrom(addressFrom);

    InternetAddress[] addressTo = new InternetAddress[1];
    addressTo[0] = new InternetAddress(recipient);
    msg.setRecipients(Message.RecipientType.TO, addressTo);

    // Setting the Subject and Content Type
    msg.setSubject(subject);
    msg.setContent(message, contentType);
    Transport.send(msg);
}

From source file:com.netflix.genie.server.jobmanager.impl.JobMonitor.java

/**
 * Check the properties file to figure out if an email
 * needs to be sent at the end of the job. If yes, get
 * mail properties and try and send email about Job Status.
 * @return 0 for success, -1 for failure
 *//*from  w  w w  .ja va 2s.c o  m*/
private boolean sendEmail(String emailTo) {
    logger.debug("called");

    if (!config.getBoolean("netflix.genie.server.mail.enable", false)) {
        logger.warn("Email is disabled but user has specified an email address.");
        return false;
    }

    // Sender's email ID
    String fromEmail = config.getString("netflix.genie.server.mail.smpt.from", "no-reply-genie@geniehost.com");
    logger.info("From email address to use to send email: " + fromEmail);

    // Set the smtp server hostname. Use localhost as default
    String smtpHost = config.getString("netflix.genie.server.mail.smtp.host", "localhost");
    logger.debug("Email smtp server: " + smtpHost);

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

    // Setup mail server
    properties.setProperty("mail.smtp.host", smtpHost);

    // check whether authentication should be turned on
    Authenticator auth = null;

    if (config.getBoolean("netflix.genie.server.mail.smtp.auth", false)) {
        logger.debug("Email Authentication Enabled");

        properties.put("mail.smtp.starttls.enable", "true");
        properties.put("mail.smtp.auth", "true");

        String userName = config.getString("netflix.genie.server.mail.smtp.user");
        String password = config.getString("netflix.genie.server.mail.smtp.password");

        if ((userName == null) || (password == null)) {
            logger.error("Authentication is enabled and username/password for smtp server is null");
            return false;
        }
        logger.debug(
                "Constructing authenticator object with username" + userName + " and password " + password);
        auth = new SMTPAuthenticator(userName, password);
    } else {
        logger.debug("Email authentication not enabled.");
    }

    // Get the default Session object.
    Session session = Session.getInstance(properties, auth);

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

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

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

        // Set Subject: header field
        message.setSubject("Genie Job " + ji.getJobName() + " completed with Status: " + ji.getStatus());

        // Now set the actual message
        String body = "Your Genie Job is complete\n\n" + "Job ID: " + ji.getJobID() + "\n" + "Job Name: "
                + ji.getJobName() + "\n" + "Status: " + ji.getStatus() + "\n" + "Status Message: "
                + ji.getStatusMsg() + "\n" + "Output Base URL: " + ji.getOutputURI() + "\n";

        message.setText(body);

        // Send message
        Transport.send(message);
        logger.info("Sent email message successfully....");
        return true;
    } catch (MessagingException mex) {
        logger.error("Got exception while sending email", mex);
        return false;
    }
}

From source file:org.chiba.connectors.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  ava2 s  .  co m
    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()));

            continue;
        }

        if (token.startsWith("port=")) {
            port = URLDecoder.decode(token.substring("port=".length()));

            continue;
        }

        if (token.startsWith("sender=")) {
            sender = URLDecoder.decode(token.substring("sender=".length()));

            continue;
        }

        if (token.startsWith("subject=")) {
            subject = URLDecoder.decode(token.substring("subject=".length()));

            continue;
        }

        if (token.startsWith("username=")) {
            username = URLDecoder.decode(token.substring("username=".length()));

            continue;
        }

        if (token.startsWith("password=")) {
            password = URLDecoder.decode(token.substring("password=".length()));

            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:gov.nih.nci.cacisweb.util.CaCISUtil.java

/**
 * Sends email by setting some of the email properties that are common to Secure Email and XDS/NAV
 * /*w  w  w  .j av  a2s  . c  o  m*/
 * @param host
 * @param port
 * @param protocol
 * @param senderEmail
 * @param senderUser
 * @param senderPassword
 * @param subject
 * @param message
 * @param recepientEmail
 * @throws EmailException
 */
public void sendEmail(String host, String port, String senderEmail, String senderUser, String senderPassword,
        String subject, String body, String recepientEmail) throws MessagingException {
    log.debug("sendEmail(String host, String port, String protocol, String senderEmail, String senderUser,"
            + "String senderPassword, String subject, String message, String recepientEmail) - start");

    final String username = senderUser;
    final String password = senderPassword;

    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", port);

    Session session = Session.getInstance(props, new javax.mail.Authenticator() {

        protected PasswordAuthentication getPasswordAuthentication() {
            return new PasswordAuthentication(username, password);
        }
    });
    Message message = new MimeMessage(session);
    message.setFrom(new InternetAddress(senderEmail));
    message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(recepientEmail));
    message.setSubject(subject);
    message.setText(body);

    Transport.send(message);

    System.out.println("Done");

    // Email email = new SimpleEmail();
    // email.setHostName(host);
    // email.setSmtpPort(port);
    // // email.setAuthentication(senderUser, senderPassword);
    // email.setAuthenticator(new DefaultAuthenticator(senderUser, senderPassword));
    // email.addTo(recepientEmail);
    // email.setFrom(senderEmail);
    // email.setSubject(subject);
    // email.setMsg(message);
    // //email.setSSL(true);
    // log.info(String.format("Sending Email to %s, to report successful setup.", recepientEmail));
    // email.send();

    log.debug("sendEmail(String host, String port, String protocol, String senderEmail, String senderUser,"
            + "String senderPassword, String subject, String message, String recepientEmail) - end");
}