Example usage for javax.mail Transport send

List of usage examples for javax.mail Transport send

Introduction

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

Prototype

public static void send(Message msg) throws MessagingException 

Source Link

Document

Send a message.

Usage

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

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);/* w  ww .ja va2  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:org.apache.juddi.subscription.notify.USERFRIENDLYSMTPNotifier.java

public static void notifyAccountDeleted(TemporaryMailContainer container) {
    try {//from  w ww . ja v a 2s  .  c  om
        Publisher publisher = container.getPublisher();
        Publisher deletedBy = container.getDeletedBy();
        String emailaddress = publisher.getEmailAddress();
        if (emailaddress == null || emailaddress.trim().equals(""))
            return;
        Properties properties = new Properties();
        Session session = null;
        String mailPrefix = AppConfig.getConfiguration().getString(Property.JUDDI_EMAIL_PREFIX,
                Property.DEFAULT_JUDDI_EMAIL_PREFIX);
        if (!mailPrefix.endsWith(".")) {
            mailPrefix = mailPrefix + ".";
        }
        for (String key : mailProps) {
            if (AppConfig.getConfiguration().containsKey(mailPrefix + key)) {
                properties.put(key, AppConfig.getConfiguration().getProperty(mailPrefix + key));
            } else if (System.getProperty(mailPrefix + key) != null) {
                properties.put(key, System.getProperty(mailPrefix + key));
            }
        }

        boolean auth = (properties.getProperty("mail.smtp.auth", "false")).equalsIgnoreCase("true");
        if (auth) {
            final String username = properties.getProperty("mail.smtp.user");
            String pwd = properties.getProperty("mail.smtp.password");
            //decrypt if possible
            if (properties.getProperty("mail.smtp.password" + Property.ENCRYPTED_ATTRIBUTE, "false")
                    .equalsIgnoreCase("true")) {
                try {
                    pwd = CryptorFactory.getCryptor().decrypt(pwd);
                } catch (NoSuchPaddingException ex) {
                    log.error("Unable to decrypt settings", ex);
                } catch (NoSuchAlgorithmException ex) {
                    log.error("Unable to decrypt settings", ex);
                } catch (InvalidAlgorithmParameterException ex) {
                    log.error("Unable to decrypt settings", ex);
                } catch (InvalidKeyException ex) {
                    log.error("Unable to decrypt settings", ex);
                } catch (IllegalBlockSizeException ex) {
                    log.error("Unable to decrypt settings", ex);
                } catch (BadPaddingException ex) {
                    log.error("Unable to decrypt settings", ex);
                }
            }
            final String password = pwd;
            log.debug("SMTP username = " + username + " from address = " + emailaddress);
            Properties eMailProperties = properties;
            eMailProperties.remove("mail.smtp.user");
            eMailProperties.remove("mail.smtp.password");
            session = Session.getInstance(properties, new javax.mail.Authenticator() {
                protected PasswordAuthentication getPasswordAuthentication() {
                    return new PasswordAuthentication(username, password);
                }
            });
        } else {
            Properties eMailProperties = properties;
            eMailProperties.remove("mail.smtp.user");
            eMailProperties.remove("mail.smtp.password");
            session = Session.getInstance(eMailProperties);
        }

        MimeMessage message = new MimeMessage(session);
        InternetAddress address = new InternetAddress(emailaddress);
        Address[] to = { address };
        message.setRecipients(RecipientType.TO, to);
        message.setFrom(new InternetAddress(properties.getProperty("mail.smtp.from", "jUDDI")));
        //Hello %s,<br><br>Your subscription UDDI subscription was deleted. Attached is what the subscription was. It was deleted by %s, %s at %s. This node is %s

        Multipart mp = new MimeMultipart();

        MimeBodyPart content = new MimeBodyPart();
        String msg_content = ResourceConfig.getGlobalMessage("notifications.smtp.accountDeleted");
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd kk:mm:ssZ");
        //Hello %s, %s,<br><br>Your account has been deleted by %s, %s at %s. This node is %s.
        msg_content = String.format(msg_content, StringEscapeUtils.escapeHtml(publisher.getPublisherName()),
                StringEscapeUtils.escapeHtml(publisher.getAuthorizedName()),
                StringEscapeUtils.escapeHtml(deletedBy.getPublisherName()),
                StringEscapeUtils.escapeHtml(deletedBy.getAuthorizedName()),
                StringEscapeUtils.escapeHtml(sdf.format(new Date())),
                StringEscapeUtils.escapeHtml(
                        AppConfig.getConfiguration().getString(Property.JUDDI_NODE_ID, "(unknown node id!)")),
                AppConfig.getConfiguration().getString(Property.JUDDI_BASE_URL, "(unknown url)"),
                AppConfig.getConfiguration().getString(Property.JUDDI_BASE_URL_SECURE, "(unknown url)"));

        content.setContent(msg_content, "text/html; charset=UTF-8;");
        mp.addBodyPart(content);

        message.setContent(mp);
        message.setSubject(ResourceConfig.getGlobalMessage("notifications.smtp.accountDeleted.subject"));
        Transport.send(message);

    } catch (Throwable t) {
        log.warn("Error sending email!" + t.getMessage());
        log.debug("Error sending email!" + t.getMessage(), t);
    }
}

From source file:com.youxifan.utils.EMail.java

/**
 *   Send Mail direct/*  ww w. j  a v a2s .c  o  m*/
 *   @return OK or error message
 */
public String send() {
    log.info("(" + m_smtpHost + ") " + m_from + " -> " + m_to);
    m_sentMsg = null;
    //
    if (!isValid(true)) {
        m_sentMsg = "Invalid Data";
        return m_sentMsg;
    }
    //
    Properties props = System.getProperties();
    props.put("mail.store.protocol", "smtp");
    props.put("mail.transport.protocol", "smtp");
    props.put("mail.host", m_smtpHost);
    //   Bit-Florin David
    props.put("mail.smtp.port", String.valueOf(m_smtpPort));
    //   TLS settings
    if (m_isSmtpTLS) {
        props.put("mail.smtp.starttls.enable", "true");
        props.put("mail.smtp.socketFactory.port", String.valueOf(m_smtpPort));
        props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
        props.put("mail.smtp.socketFactory.fallback", "false");
    }

    //
    Session session = null;
    try {
        if (m_auth != null) //   createAuthenticator was called
            props.put("mail.smtp.auth", "true");
        //         if (m_smtpHost.equalsIgnoreCase("smtp.gmail.com")) {
        //            // TODO: make it configurable
        //            // Enable gmail port and ttls - Hardcoded
        //            props.put("mail.smtp.port", "587");
        //            props.put("mail.smtp.starttls.enable", "true");
        //         }

        session = Session.getInstance(props, m_auth);
    } catch (SecurityException se) {
        log.warn("Auth=" + m_auth + " - " + se.toString());
        m_sentMsg = se.toString();
        return se.toString();
    } catch (Exception e) {
        log.warn("Auth=" + m_auth, e);
        m_sentMsg = e.toString();
        return e.toString();
    }

    try {
        //   m_msg = new MimeMessage(session);
        m_msg = new SMTPMessage(session);
        //   Addresses
        m_msg.setFrom(m_from);
        InternetAddress[] rec = getTos();
        if (rec.length == 1)
            m_msg.setRecipient(Message.RecipientType.TO, rec[0]);
        else
            m_msg.setRecipients(Message.RecipientType.TO, rec);
        rec = getCcs();
        if (rec != null && rec.length > 0)
            m_msg.setRecipients(Message.RecipientType.CC, rec);
        rec = getBccs();
        if (rec != null && rec.length > 0)
            m_msg.setRecipients(Message.RecipientType.BCC, rec);
        if (m_replyTo != null)
            m_msg.setReplyTo(new Address[] { m_replyTo });
        //
        m_msg.setSentDate(new java.util.Date());
        m_msg.setHeader("Comments", "Becit Mail");
        m_msg.setHeader("Comments", "Becit ERP Mail");
        //   m_msg.setDescription("Description");
        //   SMTP specifics
        m_msg.setAllow8bitMIME(true);
        //   Send notification on Failure & Success - no way to set envid in Java yet
        //   m_msg.setNotifyOptions (SMTPMessage.NOTIFY_FAILURE | SMTPMessage.NOTIFY_SUCCESS);
        //   Bounce only header
        m_msg.setReturnOption(SMTPMessage.RETURN_HDRS);
        //   m_msg.setHeader("X-Mailer", "msgsend");
        //
        setContent();
        m_msg.saveChanges();
        //   log.fine("message =" + m_msg);
        //
        //   Transport.send(msg);
        Transport t = session.getTransport("smtp");
        //   log.fine("transport=" + t);
        t.connect();
        //   t.connect(m_smtpHost, user, password);
        //   log.fine("transport connected");
        Transport.send(m_msg);
        //   t.sendMessage(msg, msg.getAllRecipients());
        log.info("Success - MessageID=" + m_msg.getMessageID());
    } catch (MessagingException me) {
        Exception ex = me;
        StringBuffer sb = new StringBuffer("(ME)");
        boolean printed = false;
        do {
            if (ex instanceof SendFailedException) {
                SendFailedException sfex = (SendFailedException) ex;
                Address[] invalid = sfex.getInvalidAddresses();
                if (!printed) {
                    if (invalid != null && invalid.length > 0) {
                        sb.append(" - Invalid:");
                        for (int i = 0; i < invalid.length; i++)
                            sb.append(" ").append(invalid[i]);

                    }
                    Address[] validUnsent = sfex.getValidUnsentAddresses();
                    if (validUnsent != null && validUnsent.length > 0) {
                        sb.append(" - ValidUnsent:");
                        for (int i = 0; i < validUnsent.length; i++)
                            sb.append(" ").append(validUnsent[i]);
                    }
                    Address[] validSent = sfex.getValidSentAddresses();
                    if (validSent != null && validSent.length > 0) {
                        sb.append(" - ValidSent:");
                        for (int i = 0; i < validSent.length; i++)
                            sb.append(" ").append(validSent[i]);
                    }
                    printed = true;
                }
                if (sfex.getNextException() == null)
                    sb.append(" ").append(sfex.getLocalizedMessage());
            } else if (ex instanceof AuthenticationFailedException) {
                sb.append(" - Invalid Username/Password - " + m_auth);
            } else //   other MessagingException 
            {
                String msg = ex.getLocalizedMessage();
                if (msg == null)
                    sb.append(": ").append(ex.toString());
                else {
                    if (msg.indexOf("Could not connect to SMTP host:") != -1) {
                        int index = msg.indexOf('\n');
                        if (index != -1)
                            msg = msg.substring(0, index);
                        String cc = "??";

                        msg += " - AD_Client_ID=" + cc;
                    }
                    String className = ex.getClass().getName();
                    if (className.indexOf("MessagingException") != -1)
                        sb.append(": ").append(msg);
                    else
                        sb.append(" ").append(className).append(": ").append(msg);
                }
            }
            //   Next Exception
            if (ex instanceof MessagingException)
                ex = ((MessagingException) ex).getNextException();
            else
                ex = null;
        } while (ex != null); //   error loop
        m_sentMsg = sb.toString();
        return sb.toString();
    } catch (Exception e) {
        log.warn("", e);
        m_sentMsg = e.getLocalizedMessage();
        return e.getLocalizedMessage();
    }
    //
    m_sentMsg = SENT_OK;
    return m_sentMsg;
}

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;/* w w  w.  j a v a 2 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: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   ww  w .ja v  a2s  .  c om
 * - 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  a2  s.c  o m*/
 *
 * @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:eu.scape_project.planning.user.Groups.java

/**
 * Sends an invitation mail to the user.
 * //from  ww  w.  java  2 s  . c  o m
 * @param toUser
 *            the recipient of the mail
 * @param serverString
 *            the server string
 * @return true if the mail was sent successfully, false otherwise
 * @throws InvitationMailException
 *             if the invitation mail could not be send
 */
private void sendInvitationMail(User toUser, GroupInvitation invitation, String serverString)
        throws InvitationMailException {
    try {
        Properties props = System.getProperties();

        props.put("mail.smtp.host", config.getString("mail.smtp.host"));
        Session session = Session.getDefaultInstance(props, null);

        MimeMessage message = new MimeMessage(session);
        message.setFrom(new InternetAddress(config.getString("mail.from")));
        message.setRecipient(RecipientType.TO, new InternetAddress(invitation.getEmail()));
        message.setSubject(
                user.getFullName() + " invited you to join the Plato group " + user.getUserGroup().getName());

        StringBuilder builder = new StringBuilder();
        builder.append("Dear " + toUser.getFullName() + ", \n\n");
        builder.append("The Plato user " + user.getFullName() + " has invited you to join the group "
                + user.getUserGroup().getName() + ".\n");
        builder.append("Please log in and use the following link to accept the invitation: \n");
        builder.append("http://" + serverString + "/plato/user/groupInvitation.jsf?uid="
                + invitation.getInvitationActionToken());
        builder.append("\n\n--\n");
        builder.append("Your Planningsuite team");

        message.setText(builder.toString());
        message.saveChanges();

        Transport.send(message);
        log.debug("Group invitation mail sent successfully to " + invitation.getEmail());

    } catch (Exception e) {
        log.error("Error sending group invitation mail to " + invitation.getEmail(), e);
        throw new InvitationMailException(e);
    }
}

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 v  a  2  s  . com*/
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:com.silverpeas.mailinglist.service.job.TestMessageChecker.java

@Test
public void testProcessEmailHtmlTextWithAttachment() throws MessagingException, IOException {
    MessageListener mockListener1 = mock(MessageListener.class);
    when(mockListener1.getComponentId()).thenReturn("componentId");
    when(mockListener1.checkSender("bart.simpson@silverpeas.com")).thenReturn(Boolean.TRUE);
    MessageListener mockListener2 = mock(MessageListener.class);
    messageChecker.addMessageListener(mockListener1);
    messageChecker.addMessageListener(mockListener2);
    Map<String, MessageListener> listenersByEmail = new HashMap<String, MessageListener>(2);
    listenersByEmail.put("thesimpsons@silverpeas.com", mockListener1);
    listenersByEmail.put("theflanders@silverpeas.com", mockListener2);
    MimeMessage mail = new MimeMessage(messageChecker.getMailSession());
    InternetAddress bart = new InternetAddress("bart.simpson@silverpeas.com");
    InternetAddress theSimpsons = new InternetAddress("thesimpsons@silverpeas.com");
    mail.addFrom(new InternetAddress[] { bart });
    mail.addRecipient(RecipientType.TO, theSimpsons);
    mail.setSubject("Html Email test with attachment");
    String html = loadHtml();//ww w .j a v  a2s.  com
    MimeBodyPart attachment = new MimeBodyPart(TestMessageChecker.class.getResourceAsStream("lemonde.html"));
    attachment.setDisposition(Part.ATTACHMENT);
    attachment.setFileName("lemonde.html");
    MimeBodyPart body = new MimeBodyPart();
    body.setContent(html, "text/html; charset=\"UTF-8\"");
    Multipart multiPart = new MimeMultipart();
    multiPart.addBodyPart(body);
    multiPart.addBodyPart(attachment);
    mail.setContent(multiPart);
    Transport.send(mail);
    Map<MessageListener, MessageEvent> events = new HashMap<MessageListener, MessageEvent>();
    messageChecker.processEmail(mail, events, listenersByEmail);
    assertNotNull(events);
    assertEquals(1, events.size());
    assertNull(events.get(mockListener2));

    MessageEvent event = events.get(mockListener1);
    assertNotNull(event);
    assertNotNull(event.getMessages());
    assertEquals(1, event.getMessages().size());
    Message message = event.getMessages().get(0);
    assertEquals("bart.simpson@silverpeas.com", message.getSender());
    assertEquals("Html Email test with attachment", message.getTitle());
    assertEquals(html, message.getBody());
    assertEquals(htmlEmailSummary, message.getSummary());
    assertEquals(ATT_SIZE, message.getAttachmentsSize());
    assertEquals(1, message.getAttachments().size());
    String path = MessageFormat.format(attachmentPath,
            messageChecker.getMailProcessor().replaceSpecialChars(message.getMessageId()));
    Attachment attached = message.getAttachments().iterator().next();
    assertEquals(path, attached.getPath());
    assertEquals("lemonde.html", attached.getFileName());
    assertEquals("componentId", message.getComponentId());
    assertEquals("text/html", message.getContentType());
    verify(mockListener1, atLeastOnce()).checkSender("bart.simpson@silverpeas.com");
}