Example usage for javax.mail.internet MimeMessage setFrom

List of usage examples for javax.mail.internet MimeMessage setFrom

Introduction

In this page you can find the example usage for javax.mail.internet MimeMessage setFrom.

Prototype

public void setFrom(String address) throws MessagingException 

Source Link

Document

Set the RFC 822 "From" header field.

Usage

From source file:mitm.application.djigzo.james.matchers.HasValidPasswordTest.java

@Test
public void testMultipleMatches() throws MessagingException, EncryptorException {
    HasValidPassword matcher = new HasValidPassword();

    MockMatcherConfig matcherConfig = new MockMatcherConfig("test", "matchOnError=false", mailetContext);

    matcher.init(matcherConfig);/*from   ww  w .j ava2  s.co m*/

    Mail mail = new MockMail();

    MimeMessage message = new MimeMessage(MailSession.getDefaultSession());

    message.setContent("test", "text/plain");
    message.setFrom(new InternetAddress("123456@example.com"));

    message.saveChanges();

    mail.setMessage(message);

    Collection<MailAddress> recipients = new LinkedList<MailAddress>();

    recipients.add(new MailAddress("test2@example.com"));
    recipients.add(new MailAddress("test5@example.com"));

    mail.setRecipients(recipients);

    Collection<?> result = matcher.match(mail);

    assertEquals(2, result.size());
    assertTrue(result.contains(new MailAddress("test2@example.com")));
    assertTrue(result.contains(new MailAddress("test5@example.com")));

    DjigzoMailAttributes attributes = new DjigzoMailAttributesImpl(mail);

    Passwords passwords = attributes.getPasswords();

    assertNotNull(passwords);
    assertNotNull(passwords.get("test2@example.com"));
    assertEquals("test2", passwords.get("test2@example.com").getPassword());
    assertEquals("ID2", passwords.get("test2@example.com").getPasswordID());
    assertNotNull(passwords.get("test5@example.com"));
    assertEquals("test5", passwords.get("test5@example.com").getPassword());
    assertEquals("ID5", passwords.get("test5@example.com").getPasswordID());
}

From source file:org.tsm.concharto.lab.LabJavaMail.java

private void sendConfirmationEmail(User user) {
    //mailSender.setHost("skipper");
    SimpleMailMessage message = new SimpleMailMessage();
    message.setTo(user.getEmail());//from w w w.  j a  v  a2 s .  c  o  m
    String messageText = StringUtils.replace(WELCOME_MESSAGE, PARAM_NAME, user.getUsername());
    message.setText(messageText);
    message.setSubject(WELCOME_SUBJECT);
    message.setFrom("<Concharto Notifications> notify@concharto.com");

    JavaMailSenderImpl mailSender = new JavaMailSenderImpl();
    MimeMessage mimeMessage = mailSender.createMimeMessage();
    InternetAddress from = new InternetAddress();
    from.setAddress("notify@concharto.com");
    InternetAddress to = new InternetAddress();
    to.setAddress(user.getEmail());
    try {
        from.setPersonal("Concharto Notifications");
        mimeMessage.addRecipient(Message.RecipientType.TO, to);
        mimeMessage.setSubject(WELCOME_SUBJECT);
        mimeMessage.setText(messageText);
        mimeMessage.setFrom(from);
    } catch (UnsupportedEncodingException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (MessagingException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    mailSender.setHost("localhost");
    mailSender.send(mimeMessage);

    /*
    Confirm your registration with Concharto
            
    Hello sanmi,
            
    Welcome to the Concharto community!
            
    Please click on this link to confirm your registration: http://www.concharto.com/member/confirm.htm?id=:confirmation 
            
    You can find out more about us at http://wiki.concharto.com/wiki/About.
            
    If you were not expecting this email, just ignore it, no further action is required to terminate the request.
     */
}

From source file:org.igov.io.mail.Mail.java

public void sendOld() throws EmailException {
    LOG.info("init");
    try {/*from  w  w  w  .  j  a  va  2  s  .  co m*/
        MultiPartEmail oMultiPartEmail = new MultiPartEmail();
        LOG.info("(getHost()={})", getHost());
        oMultiPartEmail.setHostName(getHost());

        String[] asTo = { sMailOnly(getTo()) };
        if (getTo().contains("\\,")) {
            asTo = getTo().split("\\,");//sTo
            for (String s : asTo) {
                LOG.info("oMultiPartEmail.addTo (s={})", s);
                oMultiPartEmail.addTo(s, "receiver");
            }
        }

        LOG.info("(getFrom()={})", getFrom());
        LOG_BIG.debug("(getFrom()={})", getFrom());
        oMultiPartEmail.setFrom(getFrom(), getFrom());//"iGov"
        oMultiPartEmail.setSubject(getHead());
        LOG.info("getHead()={}", getHead());
        String sLogin = getAuthUser();
        if (sLogin != null && !"".equals(sLogin.trim())) {
            oMultiPartEmail.setAuthentication(sLogin, getAuthPassword());
            LOG.info("withAuth");
        } else {
            LOG.info("withoutAuth");
        }
        //oMultiPartEmail.setAuthentication(getAuthUser(), getAuthPassword());
        LOG.info("(getAuthUser()={})", getAuthUser());
        //LOG.info("getAuthPassword()=" + getAuthPassword());
        oMultiPartEmail.setSmtpPort(getPort());
        LOG.info("(getPort()={})", getPort());
        oMultiPartEmail.setSSL(isSSL());
        LOG.info("(isSSL()={})", isSSL());
        oMultiPartEmail.setTLS(isTLS());
        LOG.info("(isTLS()={})", isTLS());

        oSession = oMultiPartEmail.getMailSession();
        MimeMessage oMimeMessage = new MimeMessage(oSession);

        //oMimeMessage.setFrom(new InternetAddress(getFrom(), "iGov", DEFAULT_ENCODING));
        oMimeMessage.setFrom(new InternetAddress(getFrom(), getFrom()));
        //oMimeMessage.addRecipient(Message.RecipientType.CC, new InternetAddress(sTo, sToName, DEFAULT_ENCODING));
        String sReceiverName = "receiver";
        if (asTo.length == 1) {
            sReceiverName = getToName();
        }
        for (String s : asTo) {
            LOG.info("oMimeMessage.addRecipient (s={})", s);
            //oMultiPartEmail.addTo(s, "receiver");
            oMimeMessage.addRecipient(Message.RecipientType.TO,
                    new InternetAddress(s, sReceiverName, DEFAULT_ENCODING));
        }

        //oMimeMessage.addRecipient(Message.RecipientType.TO,
        //        new InternetAddress(sTo, "recipient", DEFAULT_ENCODING));
        //new InternetAddress(getTo(), "recipient", DEFAULT_ENCODING));
        oMimeMessage.setSubject(getHead(), DEFAULT_ENCODING);

        _AttachBody(getBody());
        //LOG.info("(getBody()={})", getBody());
        oMimeMessage.setContent(oMultiparts);

        //            oMimeMessage.getRecipients(Message.RecipientType.CC);
        //methodCallRunner.registrateMethod(Transport.class.getName(), "send", new Object[]{oMimeMessage});
        Transport.send(oMimeMessage);
        LOG.info("Send " + getTo() + "!!!!!!!!!!!!!!!!!!!!!!!!");
    } catch (Exception oException) {
        LOG.error("FAIL: {} (getTo()={})", oException.getMessage(), getTo());
        LOG.trace("FAIL:", oException);
        throw new EmailException("Error happened when sending email (" + getTo() + ")" + "Exception message: "
                + oException.getMessage(), oException);
    }
    LOG.info("SUCCESS: Sent!");
}

From source file:org.pentaho.reporting.platform.plugin.SimpleEmailComponent.java

private void applyMessageHeaders(final MimeMessage msg) throws Exception {

    msg.setFrom(new InternetAddress(from));
    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));
    }/*  www .  j  av  a  2 s .co  m*/
    if ((bcc != null) && (bcc.trim().length() > 0)) {
        msg.setRecipients(Message.RecipientType.BCC, InternetAddress.parse(bcc, false));
    }

    if (subject != null) {
        msg.setSubject(subject, LocaleHelper.getSystemEncoding());
    }

}

From source file:org.sakaiproject.tool.assessment.util.SamigoEmailService.java

public String send() {
    List attachmentList = null;// w w  w .j ava  2s  . c  om
    AttachmentData a = null;
    try {
        Properties props = new Properties();

        // Server
        if (smtpServer == null || smtpServer.equals("")) {
            log.info("samigo.email.smtpServer is not set");
            smtpServer = ServerConfigurationService.getString("smtp@org.sakaiproject.email.api.EmailService");
            if (smtpServer == null || smtpServer.equals("")) {
                log.info("smtp@org.sakaiproject.email.api.EmailService is not set");
                log.error(
                        "Please set the value of samigo.email.smtpServer or smtp@org.sakaiproject.email.api.EmailService");
                return "error";
            }
        }
        props.setProperty("mail.smtp.host", smtpServer);

        // Port
        if (smtpPort == null || smtpPort.equals("")) {
            log.warn("samigo.email.smtpPort is not set. The default port 25 will be used.");
        } else {
            props.setProperty("mail.smtp.port", smtpPort);
        }

        Session session;
        session = Session.getInstance(props);
        session.setDebug(true);
        MimeMessage msg = new MimeMessage(session);

        InternetAddress fromIA = new InternetAddress(fromEmailAddress, fromName);
        msg.setFrom(fromIA);
        InternetAddress[] toIA = { new InternetAddress(toEmailAddress, toName) };
        msg.setRecipients(Message.RecipientType.TO, toIA);

        if ("yes".equals(ccMe)) {
            InternetAddress[] ccIA = { new InternetAddress(fromEmailAddress, fromName) };
            msg.setRecipients(Message.RecipientType.CC, ccIA);
        }
        msg.setSubject(subject);

        EmailBean emailBean = (EmailBean) ContextUtil.lookupBean("email");
        attachmentList = emailBean.getAttachmentList();
        StringBuilder content = new StringBuilder(message);
        ArrayList fileList = new ArrayList();
        ArrayList fileNameList = new ArrayList();
        if (attachmentList != null) {
            if (prefixedPath == null || prefixedPath.equals("")) {
                log.error("samigo.email.prefixedPath is not set");
                return "error";
            }
            Iterator iter = attachmentList.iterator();
            while (iter.hasNext()) {
                a = (AttachmentData) iter.next();
                if (a.getIsLink().booleanValue()) {
                    log.debug("send(): url");
                    content.append("<br/>\n\r");
                    content.append("<br/>"); // give a new line
                    content.append(a.getFilename());
                } else {
                    log.debug("send(): file");
                    File attachedFile = getAttachedFile(a.getResourceId());
                    fileList.add(attachedFile);
                    fileNameList.add(a.getFilename());
                }
            }
        }

        Multipart multipart = new MimeMultipart();
        MimeBodyPart messageBodyPart = new MimeBodyPart();
        messageBodyPart.setContent(content.toString(), "text/html");
        multipart.addBodyPart(messageBodyPart);
        msg.setContent(multipart);

        for (int i = 0; i < fileList.size(); i++) {
            messageBodyPart = new MimeBodyPart();
            FileDataSource source = new FileDataSource((File) fileList.get(i));
            messageBodyPart.setDataHandler(new DataHandler(source));
            messageBodyPart.setFileName((String) fileNameList.get(i));
            multipart.addBodyPart(messageBodyPart);
        }
        msg.setContent(multipart);

        Transport.send(msg);
    } catch (UnsupportedEncodingException e) {
        log.error("Exception throws from send()" + e.getMessage());
        return "error";
    } catch (MessagingException e) {
        log.error("Exception throws from send()" + e.getMessage());
        return "error";
    } catch (ServerOverloadException e) {
        log.error("Exception throws from send()" + e.getMessage());
        return "error";
    } catch (PermissionException e) {
        log.error("Exception throws from send()" + e.getMessage());
        return "error";
    } catch (IdUnusedException e) {
        log.error("Exception throws from send()" + e.getMessage());
        return "error";
    } catch (TypeException e) {
        log.error("Exception throws from send()" + e.getMessage());
        return "error";
    } catch (IOException e) {
        log.error("Exception throws from send()" + e.getMessage());
        return "error";
    } finally {
        if (attachmentList != null) {
            if (prefixedPath != null && !prefixedPath.equals("")) {
                StringBuilder sbPrefixedPath;
                Iterator iter = attachmentList.iterator();
                while (iter.hasNext()) {
                    sbPrefixedPath = new StringBuilder(prefixedPath);
                    sbPrefixedPath.append("/email_tmp/");
                    a = (AttachmentData) iter.next();
                    if (!a.getIsLink().booleanValue()) {
                        deleteAttachedFile(sbPrefixedPath.append(a.getResourceId()).toString());
                    }
                }
            }
        }
    }
    return "send";
}

From source file:nl.surfnet.coin.teams.control.AddMemberController.java

/**
 * Sends an email based on the {@link Invitation}
 *
 * @param invitation {@link Invitation} that contains the necessary data
 * @param subject    of the email//from   w  w w . jav a2s  .  co  m
 * @param inviter    {@link Person} who sends the invitation
 * @param locale     {@link Locale} for the mail
 */
protected void sendInvitationByMail(final Invitation invitation, final String subject, final Person inviter,
        final Locale locale) {

    final String html = composeInvitationMailMessage(invitation, inviter, locale, "html");
    final String plainText = composeInvitationMailMessage(invitation, inviter, locale, "plaintext");

    MimeMessagePreparator preparator = new MimeMessagePreparator() {
        public void prepare(MimeMessage mimeMessage) throws MessagingException {
            mimeMessage.addHeader("Precedence", "bulk");
            mimeMessage.setRecipient(Message.RecipientType.TO, new InternetAddress(invitation.getEmail()));
            mimeMessage.setFrom(new InternetAddress(environment.getSystemEmail()));
            mimeMessage.setSubject(subject);

            MimeMultipart rootMixedMultipart = controllerUtil.getMimeMultipartMessageBody(plainText, html);
            mimeMessage.setContent(rootMixedMultipart);
        }
    };

    mailService.sendAsync(preparator);
}

From source file:org.opens.emailsender.EmailSender.java

/**
 *
 * @param emailFrom/*from   www  . j  a  va2s  .  c  om*/
 * @param emailToSet
 * @param emailBccSet (can be null)
 * @param replyTo (can be null)
 * @param emailSubject
 * @param emailContent
 */
public void sendEmail(String emailFrom, Set<String> emailToSet, Set<String> emailBccSet, String replyTo,
        String emailSubject, String emailContent) {
    boolean debug = false;

    // Set the host smtp address
    Properties props = new Properties();
    props.put("mail.smtp.host", smtpHost);
    props.put("mail.smtp.auth", "true");
    props.put("mail.smtp.starttls.enable", "true");

    // create some properties and get the default Session
    Session session = Session.getInstance(props);
    session.setDebug(debug);
    try {
        Transport t = session.getTransport("smtp");
        t.connect(smtpHost, userName, password);

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

        // set the from and to address
        InternetAddress addressFrom;
        try {
            // Used default from address is passed one is null or empty or
            // blank
            addressFrom = (StringUtils.isNotBlank(emailFrom)) ? new InternetAddress(emailFrom)
                    : new InternetAddress(from);
            msg.setFrom(addressFrom);
            Address[] recipients = new InternetAddress[emailToSet.size()];
            int i = 0;
            for (String emailTo : emailToSet) {
                recipients[i] = new InternetAddress(emailTo);
                i++;
            }

            msg.setRecipients(Message.RecipientType.TO, recipients);

            if (CollectionUtils.isNotEmpty(emailBccSet)) {
                Address[] bccRecipients = new InternetAddress[emailBccSet.size()];
                i = 0;
                for (String emailBcc : emailBccSet) {
                    bccRecipients[i] = new InternetAddress(emailBcc);
                    i++;
                }
                msg.setRecipients(Message.RecipientType.BCC, bccRecipients);
            }

            if (StringUtils.isNotBlank(replyTo)) {
                Address[] replyToRecipients = { new InternetAddress(replyTo) };
                msg.setReplyTo(replyToRecipients);
            }

            // Setting the Subject
            msg.setSubject(emailSubject, CHARSET_KEY);

            // Setting content and charset (warning: both declarations of
            // charset are needed)
            msg.setHeader(CONTENT_TYPE_KEY, FULL_CHARSET_KEY);
            LOGGER.error("emailContent  " + emailContent);
            msg.setContent(emailContent, FULL_CHARSET_KEY);
            try {
                LOGGER.debug("emailContent from message object " + msg.getContent().toString());
            } catch (IOException ex) {
                LOGGER.error(ex.getMessage());
            } catch (MessagingException ex) {
                LOGGER.error(ex.getMessage());
            }
            for (Address addr : msg.getAllRecipients()) {
                LOGGER.error("addr " + addr);
            }
            t.sendMessage(msg, msg.getAllRecipients());
        } catch (AddressException ex) {
            LOGGER.warn(ex.getMessage());
        }
    } catch (NoSuchProviderException e) {
        LOGGER.warn(e.getMessage());
    } catch (MessagingException e) {
        LOGGER.warn(e.getMessage());
    }
}

From source file:org.mule.transport.email.transformers.StringToEmailMessage.java

@Override
public Object transformMessage(MuleMessage message, String outputEncoding) throws TransformerException {
    String endpointAddress = endpoint.getEndpointURI().getAddress();
    SmtpConnector connector = (SmtpConnector) endpoint.getConnector();
    String to = lookupProperty(message, MailProperties.TO_ADDRESSES_PROPERTY, endpointAddress);
    String cc = lookupProperty(message, MailProperties.CC_ADDRESSES_PROPERTY, connector.getCcAddresses());
    String bcc = lookupProperty(message, MailProperties.BCC_ADDRESSES_PROPERTY, connector.getBccAddresses());
    String from = lookupProperty(message, MailProperties.FROM_ADDRESS_PROPERTY, connector.getFromAddress());
    String replyTo = lookupProperty(message, MailProperties.REPLY_TO_ADDRESSES_PROPERTY,
            connector.getReplyToAddresses());
    String subject = lookupProperty(message, MailProperties.SUBJECT_PROPERTY, connector.getSubject());
    String contentType = lookupProperty(message, MailProperties.CONTENT_TYPE_PROPERTY,
            connector.getContentType());

    Properties headers = new Properties();
    Properties customHeaders = connector.getCustomHeaders();

    if (customHeaders != null && !customHeaders.isEmpty()) {
        headers.putAll(customHeaders);//from  ww  w .  j a v a 2  s.co  m
    }

    Properties otherHeaders = message.getOutboundProperty(MailProperties.CUSTOM_HEADERS_MAP_PROPERTY);
    if (otherHeaders != null && !otherHeaders.isEmpty()) {
        //TODO Whats going on here?
        //                final MuleContext mc = context.getMuleContext();
        //                for (Iterator iterator = message.getPropertyNames().iterator(); iterator.hasNext();)
        //                {
        //                    String propertyKey = (String) iterator.next();
        //                    mc.getRegistry().registerObject(propertyKey, message.getProperty(propertyKey), mc);
        //                }
        headers.putAll(templateParser.parse(new TemplateParser.TemplateCallback() {
            public Object match(String token) {
                return muleContext.getRegistry().lookupObject(token);
            }
        }, otherHeaders));

    }

    if (logger.isDebugEnabled()) {
        StringBuffer buf = new StringBuffer();
        buf.append("Constructing email using:\n");
        buf.append("To: ").append(to);
        buf.append(", From: ").append(from);
        buf.append(", CC: ").append(cc);
        buf.append(", BCC: ").append(bcc);
        buf.append(", Subject: ").append(subject);
        buf.append(", ReplyTo: ").append(replyTo);
        buf.append(", Content type: ").append(contentType);
        buf.append(", Payload type: ").append(message.getPayload().getClass().getName());
        buf.append(", Custom Headers: ").append(MapUtils.toString(headers, false));
        logger.debug(buf.toString());
    }

    try {
        MimeMessage email = new MimeMessage(
                ((SmtpConnector) endpoint.getConnector()).getSessionDetails(endpoint).getSession());

        email.setRecipients(Message.RecipientType.TO, MailUtils.stringToInternetAddresses(to));

        // sent date
        email.setSentDate(Calendar.getInstance().getTime());

        if (StringUtils.isNotBlank(from)) {
            email.setFrom(MailUtils.stringToInternetAddresses(from)[0]);
        }

        if (StringUtils.isNotBlank(cc)) {
            email.setRecipients(Message.RecipientType.CC, MailUtils.stringToInternetAddresses(cc));
        }

        if (StringUtils.isNotBlank(bcc)) {
            email.setRecipients(Message.RecipientType.BCC, MailUtils.stringToInternetAddresses(bcc));
        }

        if (StringUtils.isNotBlank(replyTo)) {
            email.setReplyTo(MailUtils.stringToInternetAddresses(replyTo));
        }

        email.setSubject(subject, outputEncoding);

        for (Iterator iterator = headers.entrySet().iterator(); iterator.hasNext();) {
            Map.Entry entry = (Map.Entry) iterator.next();
            email.setHeader(entry.getKey().toString(), entry.getValue().toString());
        }

        setContent(message.getPayload(), email, contentType, message);

        return email;
    } catch (Exception e) {
        throw new TransformerException(this, e);
    }
}

From source file:org.asqatasun.emailsender.EmailSender.java

/**
 *
 * @param emailFrom//from   w  ww .java 2 s  .  co  m
 * @param emailToSet
 * @param emailBccSet (can be null)
 * @param replyTo (can be null)
 * @param emailSubject
 * @param emailContent
 */
public void sendEmail(String emailFrom, Set<String> emailToSet, Set<String> emailBccSet, String replyTo,
        String emailSubject, String emailContent) {
    boolean debug = false;

    // Set the host smtp address
    Properties props = new Properties();
    props.put("mail.smtp.host", smtpHost);
    props.put("mail.smtp.auth", "true");
    props.put("mail.smtp.starttls.enable", "true");

    // create some properties and get the default Session
    Session session = Session.getInstance(props);
    session.setDebug(debug);
    try {
        Transport t = session.getTransport("smtp");
        t.connect(smtpHost, userName, password);

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

        // set the from and to address
        InternetAddress addressFrom;
        try {
            // Used default from address is passed one is null or empty or
            // blank
            addressFrom = (StringUtils.isNotBlank(emailFrom)) ? new InternetAddress(emailFrom)
                    : new InternetAddress(from);
            msg.setFrom(addressFrom);
            Address[] recipients = new InternetAddress[emailToSet.size()];
            int i = 0;
            for (String emailTo : emailToSet) {
                recipients[i] = new InternetAddress(emailTo);
                i++;
            }

            msg.setRecipients(Message.RecipientType.TO, recipients);

            if (CollectionUtils.isNotEmpty(emailBccSet)) {
                Address[] bccRecipients = new InternetAddress[emailBccSet.size()];
                i = 0;
                for (String emailBcc : emailBccSet) {
                    bccRecipients[i] = new InternetAddress(emailBcc);
                    i++;
                }
                msg.setRecipients(Message.RecipientType.BCC, bccRecipients);
            }

            if (StringUtils.isNotBlank(replyTo)) {
                Address[] replyToRecipients = { new InternetAddress(replyTo) };
                msg.setReplyTo(replyToRecipients);
            }

            // Setting the Subject
            msg.setSubject(emailSubject, CHARSET_KEY);

            // Setting content and charset (warning: both declarations of
            // charset are needed)
            msg.setHeader(CONTENT_TYPE_KEY, FULL_CHARSET_KEY);
            LOGGER.debug("emailContent  " + emailContent);
            msg.setContent(emailContent, FULL_CHARSET_KEY);
            try {
                LOGGER.debug("emailContent from message object " + msg.getContent().toString());
            } catch (IOException ex) {
                LOGGER.error(ex.getMessage());
            } catch (MessagingException ex) {
                LOGGER.error(ex.getMessage());
            }
            for (Address addr : msg.getAllRecipients()) {
                LOGGER.debug("addr " + addr);
            }
            t.sendMessage(msg, msg.getAllRecipients());
        } catch (AddressException ex) {
            LOGGER.warn("AddressException " + ex.getMessage());
            LOGGER.warn("AddressException " + ex.getStackTrace());
        }
    } catch (NoSuchProviderException e) {
        LOGGER.warn("NoSuchProviderException " + e.getMessage());
        LOGGER.warn("NoSuchProviderException " + e.getStackTrace());
    } catch (MessagingException e) {
        LOGGER.warn("MessagingException " + e.getMessage());
        LOGGER.warn("MessagingException " + e.getStackTrace());
    }
}

From source file:org.overlord.sramp.governance.services.NotificationResource.java

/**
 * POST to email a notification about an artifact.
 *
 * @param environment//from w ww.  j ava 2  s.com
 * @param uuid
 * @throws SrampAtomException
 */
@POST
@Path("email/{group}/{template}/{target}/{uuid}")
@Produces("application/xml")
public Map<String, ValueEntity> emailNotification(@Context HttpServletRequest request,
        @PathParam("group") String group, @PathParam("template") String template,
        @PathParam("target") String target, @PathParam("uuid") String uuid) throws Exception {

    Map<String, ValueEntity> results = new HashMap<String, ValueEntity>();
    try {
        // 0. run the decoder on the arguments, after replacing * by % (this so parameters can
        //    contain slashes (%2F)
        group = SlashDecoder.decode(group);
        template = SlashDecoder.decode(template);
        target = SlashDecoder.decode(target);
        uuid = SlashDecoder.decode(uuid);

        // 1. get the artifact from the repo
        SrampAtomApiClient client = SrampAtomApiClientFactory.createAtomApiClient();
        QueryResultSet queryResultSet = client.buildQuery("/s-ramp[@uuid = ?]").parameter(uuid).query(); //$NON-NLS-1$
        if (queryResultSet.size() == 0) {
            results.put(GovernanceConstants.STATUS, new ValueEntity("fail")); //$NON-NLS-1$
            results.put(GovernanceConstants.MESSAGE,
                    new ValueEntity("Could not obtain artifact from repository.")); //$NON-NLS-1$
            return results;
        }
        ArtifactSummary artifactSummary = queryResultSet.iterator().next();

        // 2. get the destinations for this group
        NotificationDestinations destinations = governance.getNotificationDestinations("email").get(group); //$NON-NLS-1$
        if (destinations == null) {
            destinations = new NotificationDestinations(group, governance.getDefaultEmailFromAddress(),
                    group + "@" + governance.getDefaultEmailDomain()); //$NON-NLS-1$
        }

        // 3. send the email notification
        try {
            MimeMessage m = new MimeMessage(mailSession);
            Address from = new InternetAddress(destinations.getFromAddress());
            Address[] to = new InternetAddress[destinations.getToAddresses().length];
            for (int i = 0; i < destinations.getToAddresses().length; i++) {
                to[i] = new InternetAddress(destinations.getToAddresses()[i]);
            }
            m.setFrom(from);
            m.setRecipients(Message.RecipientType.TO, to);

            String subject = "/governance-email-templates/" + template + ".subject.tmpl"; //$NON-NLS-1$ //$NON-NLS-2$
            URL subjectUrl = Governance.class.getClassLoader().getResource(subject);
            if (subjectUrl != null)
                subject = IOUtils.toString(subjectUrl);
            subject = subject.replaceAll("\\$\\{uuid}", uuid); //$NON-NLS-1$
            subject = subject.replaceAll("\\$\\{name}", artifactSummary.getName()); //$NON-NLS-1$
            subject = subject.replaceAll("\\$\\{target}", target); //$NON-NLS-1$
            m.setSubject(subject);

            m.setSentDate(new java.util.Date());
            String content = "/governance-email-templates/" + template + ".body.tmpl"; //$NON-NLS-1$ //$NON-NLS-2$
            URL contentUrl = Governance.class.getClassLoader().getResource(content);
            if (contentUrl != null)
                content = IOUtils.toString(contentUrl);
            content = content.replaceAll("\\$\\{uuid}", uuid); //$NON-NLS-1$
            content = content.replaceAll("\\$\\{name}", artifactSummary.getName()); //$NON-NLS-1$
            content = content.replaceAll("\\$\\{target}", target); //$NON-NLS-1$
            content = content.replaceAll("\\$\\{dtgovurl}", governance.getDTGovUiUrl()); //$NON-NLS-1$
            m.setContent(content, "text/plain"); //$NON-NLS-1$
            Transport.send(m);
        } catch (javax.mail.MessagingException e) {
            logger.error(e.getMessage(), e);
        }

        // 4. build the response
        results.put(GovernanceConstants.STATUS, new ValueEntity("success")); //$NON-NLS-1$

        return results;
    } catch (Exception e) {
        logger.error(Messages.i18n.format("NotificationResource.EmailError", e.getMessage(), e)); //$NON-NLS-1$
        throw new SrampAtomException(e);
    }
}