Example usage for javax.mail.internet MimeMessage setRecipient

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

Introduction

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

Prototype

public void setRecipient(RecipientType type, Address address) throws MessagingException 

Source Link

Document

Set the recipient address.

Usage

From source file:gov.nih.nci.cacis.nav.AbstractSendMail.java

/**
 * Creates MimeMessage with supplied values
 * //from   ww  w. ja  v a 2  s  .  c  om
 * @param to - to email address
 * @param docType - String value for the attached document type
 * @param subject - Subject for the email
 * @param instructions - email body
 * @param content - content to be sent as attachment
 * @return MimeMessage instance
 */
public MimeMessage createMessage(String to, String docType, String subject, String instructions, String content,
        String metadataXMl, String title, String indexBodyToken, String readmeToken) {
    final MimeMessage msg = mailSender.createMimeMessage();
    UUID uniqueID = UUID.randomUUID();
    tempZipFolder = new File(secEmailTempZipLocation + "/" + uniqueID);
    try {
        msg.setFrom(new InternetAddress(getFrom()));
        msg.setSubject(subject);
        msg.setSentDate(new Date());
        msg.setRecipient(Message.RecipientType.TO, new InternetAddress(to));

        // The readable part
        final MimeBodyPart mbp1 = new MimeBodyPart();
        mbp1.setText(instructions);
        mbp1.setHeader("Content-Type", "text/plain");

        // The notification
        final MimeBodyPart mbp2 = new MimeBodyPart();

        final String contentType = "application/xml; charset=UTF-8";

        String extension;

        // HL7 messages should be a txt file, otherwise xml
        if (StringUtils.contains(instructions, "HL7_V2_CLINICAL_NOTE")) {
            extension = TXT_EXT;
        } else {
            extension = XML_EXT;
        }

        final String fileName = docType + UUID.randomUUID() + extension;

        //            final DataSource ds = new AttachmentDS(fileName, content, contentType);
        //            mbp2.setDataHandler(new DataHandler(ds));

        /******** START NHIN COMPLIANCE CHANGES *****/

        boolean isTempZipFolderCreated = tempZipFolder.mkdirs();
        if (!isTempZipFolderCreated) {
            LOG.error("Error creating temp folder for NHIN zip file: " + tempZipFolder.getAbsolutePath());
            throw new ApplicationRuntimeException(
                    "Error creating temp folder for NHIN zip file: " + tempZipFolder.getAbsolutePath());
        }

        String indexFileString = FileUtils.readFileToString(new File(secEmailTempZipLocation + "/INDEX.HTM"));
        String readmeFileString = FileUtils.readFileToString(new File(secEmailTempZipLocation + "/README.TXT"));

        indexFileString = StringUtils.replace(indexFileString, "@document_title@", title);
        indexFileString = StringUtils.replace(indexFileString, "@indexBodyToken@", indexBodyToken);
        FileUtils.writeStringToFile(new File(tempZipFolder + "/INDEX.HTM"), indexFileString);

        readmeFileString = StringUtils.replace(readmeFileString, "@readmeToken@", readmeToken);
        FileUtils.writeStringToFile(new File(tempZipFolder + "/README.TXT"), readmeFileString);

        // move template files & replace tokens
        //            FileUtils.copyFileToDirectory(new File(secEmailTempZipLocation + "/INDEX.HTM"), tempZipFolder, false);
        //            FileUtils.copyFileToDirectory(new File(secEmailTempZipLocation + "/README.TXT"), tempZipFolder, false);

        // create sub-directories
        String nhinSubDirectoryPath = tempZipFolder + "/IHE_XDM/SUBSET01";
        File nhinSubDirectory = new File(nhinSubDirectoryPath);
        boolean isNhinSubDirectoryCreated = nhinSubDirectory.mkdirs();
        if (!isNhinSubDirectoryCreated) {
            LOG.error("Error creating NHIN sub-directory: " + nhinSubDirectory.getAbsolutePath());
            throw new ApplicationRuntimeException(
                    "Error creating NHIN sub-directory: " + nhinSubDirectory.getAbsolutePath());
        }
        FileOutputStream metadataStream = new FileOutputStream(
                new File(nhinSubDirectoryPath + "/METADATA.XML"));
        metadataStream.write(metadataXMl.getBytes());
        metadataStream.flush();
        metadataStream.close();
        FileOutputStream documentStream = new FileOutputStream(
                new File(nhinSubDirectoryPath + "/DOCUMENT" + extension));
        documentStream.write(content.getBytes());
        documentStream.flush();
        documentStream.close();

        String zipFile = secEmailTempZipLocation + "/" + tempZipFolder.getName() + ".ZIP";
        byte[] buffer = new byte[1024];
        //            FileOutputStream fos = new FileOutputStream(zipFile);
        //            ZipOutputStream zos = new ZipOutputStream(fos);

        List<String> fileList = generateFileList(tempZipFolder);
        ByteArrayOutputStream bout = new ByteArrayOutputStream(fileList.size());
        ZipOutputStream zos = new ZipOutputStream(bout);
        //            LOG.info("File List size: "+fileList.size());
        for (String file : fileList) {
            ZipEntry ze = new ZipEntry(file);
            zos.putNextEntry(ze);
            FileInputStream in = new FileInputStream(tempZipFolder + File.separator + file);
            int len;
            while ((len = in.read(buffer)) > 0) {
                zos.write(buffer, 0, len);
            }
            in.close();
        }
        zos.closeEntry();
        // remember close it
        zos.close();

        DataSource source = new ByteArrayDataSource(bout.toByteArray(), "application/zip");
        mbp2.setDataHandler(new DataHandler(source));
        mbp2.setFileName(docType + ".ZIP");

        /******** END NHIN COMPLIANCE CHANGES *****/

        //            mbp2.setFileName(fileName);
        //            mbp2.setHeader("Content-Type", contentType);

        final Multipart mp = new MimeMultipart();
        mp.addBodyPart(mbp1);
        mp.addBodyPart(mbp2);
        msg.setContent(mp);
        msg.setSentDate(new Date());

        //            FileUtils.deleteDirectory(tempZipFolder);
    } catch (AddressException e) {
        LOG.error("Error creating email message!");
        throw new ApplicationRuntimeException("Error creating message!", e);
    } catch (MessagingException e) {
        LOG.error("Error creating email message!");
        throw new ApplicationRuntimeException("Error creating message!", e);
    } catch (IOException e) {
        LOG.error(e.getMessage());
        throw new ApplicationRuntimeException(e.getMessage());
    } finally {
        //reset filelist contents
        fileList = new ArrayList<String>();
    }
    return msg;
}

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

@Override
public synchronized void send(Dispatch dispatch) throws MailException {

    Message message = dispatch.getMessage();

    String recipient = dispatch.getParams().get(MailChannel.RECIPIENT);
    String recipientName = dispatch.getParams().get(MailChannel.RECIPIENT_NAME);
    String subject = message.getSubject();

    try {/* w ww  . j  a v a2  s . c o m*/
        MimeMessage mm = new MimeMessage(getSmtpSession(recipient)) {
            @Override
            protected void updateMessageID() throws MessagingException {
                String domain = _from.getAddress();
                int idx = _from.getAddress().indexOf('@');
                if (idx >= 0) {
                    domain = domain.substring(idx + 1);
                }
                setHeader("Message-ID", "<" + UUID.randomUUID() + "@" + domain + ">");
            }
        };
        mm.setFrom(_from);
        mm.setSender(_from);

        InternetAddress replyTo = getReplyTo();
        if (replyTo != null) {
            mm.setReplyTo(new Address[] { replyTo });
        }
        mm.setHeader("X-Mailer", "molindo-notify");
        mm.setSentDate(new Date());

        mm.setRecipient(RecipientType.TO,
                new InternetAddress(recipient, recipientName, CharsetUtils.UTF_8.displayName()));
        mm.setSubject(subject, CharsetUtils.UTF_8.displayName());

        if (_format == Format.HTML) {
            if (message.getType() == Type.TEXT) {
                throw new MailException("can't send HTML mail from TEXT message", false);
            }
            mm.setText(message.getHtml(), CharsetUtils.UTF_8.displayName(), "html");
        } else if (_format == Format.TEXT || _format == Format.MULTI && message.getType() == Type.TEXT) {
            mm.setText(message.getText(), CharsetUtils.UTF_8.displayName());
        } else if (_format == Format.MULTI) {
            MimeBodyPart html = new MimeBodyPart();
            html.setText(message.getHtml(), CharsetUtils.UTF_8.displayName(), "html");

            MimeBodyPart text = new MimeBodyPart();
            text.setText(message.getText(), CharsetUtils.UTF_8.displayName());

            /*
             * The formats are ordered by how faithful they are to the
             * original, with the least faithful first and the most faithful
             * last. (http://en.wikipedia.org/wiki/MIME#Alternative)
             */
            MimeMultipart mmp = new MimeMultipart();
            mmp.setSubType("alternative");

            mmp.addBodyPart(text);
            mmp.addBodyPart(html);

            mm.setContent(mmp);
        } else {
            throw new NotifyRuntimeException(
                    "unexpected format (" + _format + ") or type (" + message.getType() + ")");
        }

        send(mm);

    } catch (final MessagingException e) {
        throw new MailException(
                "could not send mail from " + _from + " to " + recipient + " (" + toErrorMessage(e) + ")", e,
                isTemporary(e));
    } catch (UnsupportedEncodingException e) {
        throw new RuntimeException("utf8 unknown?", e);
    }
}

From source file:org.apache.james.transport.mailets.managesieve.ManageSieveMailetTestCase.java

private MimeMessage prepareMimeMessage(String subject) throws MessagingException {
    MimeMessage message = new MimeMessage(Session.getDefaultInstance(new Properties()));
    message.setSubject(subject);//from   w  w w .  jav a2 s .  c o  m
    message.setSender(new InternetAddress(USER));
    message.setRecipient(RecipientType.TO, new InternetAddress(SIEVE_LOCALHOST));
    message.saveChanges();
    return message;
}

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  .java  2s. c  o  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.exoplatform.extension.social.notifications.SocialNotificationService.java

/**
 * //from ww  w .  j  ava2s .  c  o m
 * @param invitedUsersList 
 */
private void invitedUserNotification(Map<String, List<Space>> invitedUsersList) {

    for (Map.Entry<String, List<Space>> entry : invitedUsersList.entrySet()) {

        try {
            String userId = entry.getKey();
            List<Space> spacesList = entry.getValue();
            Locale locale = Locale.getDefault();

            // get default locale of the manager
            String userLocale = this.getOrganizationService().getUserProfileHandler()
                    .findUserProfileByName(userId).getAttribute("user.language");
            Profile userProfile = getIdentityManager()
                    .getOrCreateIdentity(OrganizationIdentityProvider.NAME, userId, false).getProfile();

            if (userLocale != null && !userLocale.trim().isEmpty()) {
                locale = new Locale(userLocale);
            }

            // getMessageTemplate
            MessageTemplate messageTemplate = this.getMailMessageTemplate(
                    SocialNotificationConfiguration.MAIL_TEMPLATE_SPACE_PENDING_INVITATIONS, locale);

            GroovyTemplate g = new GroovyTemplate(messageTemplate.getSubject());

            Map binding = new HashMap();
            binding.put("userProfile", userProfile);
            binding.put("portalUrl", this.getPortalUrl());
            binding.put("invitationUrl", this.getPortalUrl() + "/portal/intranet/invitationSpace");
            binding.put("spacesList", spacesList);

            String subject = g.render(binding);

            g = new GroovyTemplate(messageTemplate.getHtmlContent());
            String htmlContent = g.render(binding);

            g = new GroovyTemplate(messageTemplate.getPlainTextContent());
            String textContent = g.render(binding);

            MailService mailService = this.getMailService();
            Session mailSession = mailService.getMailSession();
            MimeMessage message = new MimeMessage(mailSession);
            message.setFrom(this.getSenderAddress());

            // send email to invited user
            message.setRecipient(RecipientType.TO,
                    new InternetAddress(userProfile.getEmail(), userProfile.getFullName()));
            message.setSubject(subject);
            MimeMultipart content = new MimeMultipart("alternative");
            MimeBodyPart text = new MimeBodyPart();
            MimeBodyPart html = new MimeBodyPart();
            text.setText(textContent);
            html.setContent(htmlContent, "text/html; charset=ISO-8859-1");
            content.addBodyPart(text);
            content.addBodyPart(html);
            message.setContent(content);

            log.info("Sending mail to : " + userProfile.getEmail() + " : " + subject + "\n" + html);

            mailService.sendMessage(message);

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}

From source file:org.exoplatform.extension.social.notifications.SocialNotificationService.java

/**
 * /*from w  ww  .  j  a  v a 2 s .c  om*/
 * @param space
 * @param managers
 * @param pendingUsers 
 */
private void pendingUserNotification(Space space, List<Profile> managerList, List<Profile> pendingUsers) {
    //TODO : use groovy template stored in JCR for mail information (cleaner, real templating)

    log.info("Sending mail to space manager : pending users");

    try {

        // loop on each manager and send mail
        // like that each manager will have the mail in its preferred language
        // ideally should be done in a different executor
        // TODO: see if we can optimize this to avoid do it for all user
        //       - send a mail to all the users in the same time (what about language)
        //       - cache the template result and send mail

        for (Profile manager : managerList) {
            Locale locale = Locale.getDefault();

            // get default locale of the manager
            String userId = manager.getIdentity().getRemoteId();
            String userLocale = this.getOrganizationService().getUserProfileHandler()
                    .findUserProfileByName(userId).getAttribute("user.language");
            if (userLocale != null && !userLocale.trim().isEmpty()) {
                locale = new Locale(userLocale);
            }

            // getMessageTemplate
            MessageTemplate messageTemplate = this.getMailMessageTemplate(
                    SocialNotificationConfiguration.MAIL_TEMPLATE_SPACE_PENDING_USERS, locale);

            GroovyTemplate g = new GroovyTemplate(messageTemplate.getSubject());

            String spaceUrl = this.getPortalUrl() + "/portal/g/:spaces:" + space.getUrl() + "/" + space.getUrl()
                    + "/settings"; //TODO: see which API to use
            String spaceAvatarUrl = null;
            if (space.getAvatarUrl() != null) {
                spaceAvatarUrl = this.getPortalUrl() + space.getAvatarUrl();
            }

            Map binding = new HashMap();
            binding.put("space", space);
            binding.put("portalUrl", this.getPortalUrl());
            binding.put("spaceSettingUrl", spaceUrl);
            binding.put("spaceAvatarUrl", spaceAvatarUrl);
            binding.put("userPendingList", pendingUsers);

            String subject = g.render(binding);

            g = new GroovyTemplate(messageTemplate.getHtmlContent());
            String htmlContent = g.render(binding);

            g = new GroovyTemplate(messageTemplate.getPlainTextContent());
            String textContent = g.render(binding);

            MailService mailService = this.getMailService();
            Session mailSession = mailService.getMailSession();
            MimeMessage message = new MimeMessage(mailSession);
            message.setFrom(this.getSenderAddress());

            // send email to manager
            message.setRecipient(RecipientType.TO,
                    new InternetAddress(manager.getEmail(), manager.getFullName()));
            message.setSubject(subject);
            MimeMultipart content = new MimeMultipart("alternative");
            MimeBodyPart text = new MimeBodyPart();
            MimeBodyPart html = new MimeBodyPart();
            text.setText(textContent);
            html.setContent(htmlContent, "text/html; charset=ISO-8859-1");
            content.addBodyPart(text);
            content.addBodyPart(html);
            message.setContent(content);

            log.info("Sending mail to" + manager.getEmail() + " : " + subject + " : " + subject + "\n" + html);

            //mailService.sendMessage(message);
        }

    } catch (Exception ex) {
        ex.printStackTrace();
    }
}

From source file:org.hyperic.hq.bizapp.server.session.EmailManagerImpl.java

public void sendEmail(EmailRecipient[] addresses, String subject, String[] body, String[] htmlBody,
        Integer priority) {/*from w w  w.jav  a 2  s  . c  o  m*/
    MimeMessage mimeMessage = mailSender.createMimeMessage();
    final StopWatch watch = new StopWatch();

    try {
        InternetAddress from = getFromAddress();
        if (from == null) {
            mimeMessage.setFrom();
        } else {
            mimeMessage.setFrom(from);
        }

        // HHQ-5708
        // remove any possible new line from the subject
        // the subject can be render form 'subject.gsp' file
        mimeMessage.setSubject(subject.replace("\r", "").replace("\n", ""));

        // If priority not null, set it in body 
        if (priority != null) {
            switch (priority.intValue()) {
            case EventConstants.PRIORITY_HIGH:
                mimeMessage.addHeader("X-Priority", "1");
                break;
            case EventConstants.PRIORITY_MEDIUM:
                mimeMessage.addHeader("X-Priority", "2");
                break;
            default:
                break;
            }
        }

        // Send to each recipient individually (for D.B. SMS)
        for (int i = 0; i < addresses.length; i++) {
            mimeMessage.setRecipient(Message.RecipientType.TO, addresses[i].getAddress());

            if (addresses[i].useHtml()) {
                mimeMessage.setContent(htmlBody[i], "text/html; charset=UTF-8");
                if (log.isDebugEnabled()) {
                    log.debug("Sending HTML Alert notification: " + subject + " to "
                            + addresses[i].getAddress().getAddress() + "\n" + htmlBody[i]);
                }
            } else {
                if (log.isDebugEnabled()) {
                    log.debug("Sending Alert notification: " + subject + " to "
                            + addresses[i].getAddress().getAddress() + "\n" + body[i]);
                }
                mimeMessage.setContent(body[i], "text/plain; charset=UTF-8");
            }

            mailSender.send(mimeMessage);
        }
    } catch (MessagingException e) {
        log.error("MessagingException in sending email: [" + subject + "]\nmailServer = ["
                + mailSession.getProperties() + "]", e);
    } catch (MailException me) {
        log.error("MailException in sending email: [" + subject + "]\nmailServer = ["
                + mailSession.getProperties() + "]", me);
    } catch (Exception ex) {
        log.error(
                "Error in sending email: [" + subject + "]\nmailServer = [" + mailSession.getProperties() + "]",
                ex);
    } finally {
        if (log.isDebugEnabled()) {
            log.debug("Sending email using mailServer=" + mailSession.getProperties() + " took "
                    + watch.getElapsed() + " ms.");
        }
        if (watch.getElapsed() >= mailSmtpConnectiontimeout || (watch.getElapsed() >= mailSmtpTimeout)) {
            log.warn("Sending email using mailServer=" + mailSmtpHost + " took " + watch.getElapsed()
                    + " ms.  Please check with your mail administrator.");
        }
    }
}

From source file:org.josso.selfservices.password.EMailPasswordDistributor.java

protected void sendMail(final String mailTo, final String mailFrom, final String text)
        throws PasswordManagementException {

    MimeMessagePreparator preparator = new MimeMessagePreparator() {

        public void prepare(MimeMessage mimeMessage) throws Exception {
            mimeMessage.setRecipient(Message.RecipientType.TO, new InternetAddress(mailTo));
            mimeMessage.setFrom(new InternetAddress(mailFrom));
            mimeMessage.setSubject(getMailSubject());
            mimeMessage.setText(text);/*from w w  w. jav a2s.c  om*/
        }
    };

    try {
        this.mailSender.send(preparator);
    } catch (MailException e) {
        throw new PasswordManagementException(
                "Cannot distribute password to [" + mailTo + "] " + e.getMessage(), e);
    }
}

From source file:org.liveSense.service.email.EmailSendJobEventHandler.java

@SuppressWarnings("static-access")
public boolean sendMail(Session session, String path) throws RepositoryException, Exception {
    ResourceResolver resourceResolver = null;
    ByteArrayOutputStream debugPrintOut = null;

    try {//from   www .ja v  a2s  .co m
        log.info("Sending email: " + path);

        Map<String, Object> authInfo = new HashMap<String, Object>();
        authInfo.put(JcrResourceConstants.AUTHENTICATION_INFO_SESSION, session);
        try {
            resourceResolver = resourceResolverFactory.getResourceResolver(authInfo);
        } catch (LoginException e) {
            log.error("Authentication error");
            throw new RepositoryException();
        }

        Resource res = resourceResolver.getResource(path);
        Node node = res.adaptTo(Node.class);

        if (node != null) {
            // Sending mail to SMTP
            try {
                log.info("Sending email: " + node.getName());
                javax.mail.Session mailSession = getMailSession();

                PrintStream debugPrintStream = null;

                if (smtpDebug) {
                    debugPrintOut = new ByteArrayOutputStream();
                    debugPrintStream = new PrintStream(debugPrintOut);
                    mailSession.setDebug(true);
                    mailSession.setDebugOut(debugPrintStream);
                }

                MimeMessage msg = new MimeMessage(mailSession,
                        node.getNode("jcr:content").getProperty("jcr:data").getBinary().getStream());
                if (StringUtils.isNotEmpty(testMailAddress)) {
                    msg.setRecipient(RecipientType.TO, new InternetAddress(testMailAddress));
                    //                  msg.setRecipient(RecipientType.BCC, (InternetAddress)null);
                    //                  msg.setRecipient(RecipientType.CC, (InternetAddress)null);
                }
                if (msg.getAllRecipients() != null) {
                    log.info("  --> Transporting to: " + msg.getAllRecipients()[0].toString());
                    if (smtpSslEnable)
                        mailSession.getTransport("smtps").send(msg);
                    else
                        mailSession.getTransport("smtp").send(msg);
                    try {
                        node.remove();
                    } catch (RepositoryException ex) {
                        log.error("Could not remove mail from spool folder: " + node.getName(), ex);
                        return true;
                    }
                } else {
                    log.warn("  --> No recepients, removing " + node.getName());
                    try {
                        node.remove();
                    } catch (RepositoryException ex) {
                        log.error("Could not remove mail from spool folder: " + node.getName(), ex);
                        return true;
                    }

                }
            } catch (MessagingException ex) {
                log.error("Message could not be send: " + node.getName(), ex);
                updateFailedMailJob(node);
                return true;
            } catch (PathNotFoundException ex) {
                log.error("Path not found - maybe not a nt:file node?: " + node.getName(), ex);
                try {
                    node.remove();
                } catch (Throwable e) {
                }
                return true;
            } catch (RepositoryException ex) {
                log.error("Repository error: " + node.getName(), ex);
                updateFailedMailJob(node);
                return true;
            }
            return true;
        }
        updateFailedMailJob(node);
        return true;
    } finally {
        if (debugPrintOut != null) {
            log.info(debugPrintOut.toString());
        }

        if (resourceResolver != null)
            resourceResolver.close();
    }
}

From source file:org.masukomi.aspirin.core.Bouncer.java

/**
 * This generates a response to the Return-Path address, or the address of
 * the message's sender if the Return-Path is not available. Note that this
 * is different than a mail-client's reply, which would use the Reply-To or
 * From header.//from   ww  w .  j  av a2s.c om
 * 
 * @param mail
 *            DOCUMENT ME!
 * @param message
 *            DOCUMENT ME!
 * @param bouncer
 *            DOCUMENT ME!
 * 
 * @throws MessagingException
 *             DOCUMENT ME!
 */
static public void bounce(MailQue que, Mail mail, String message, MailAddress bouncer)
        throws MessagingException {
    if (bouncer != null) {
        if (log.isDebugEnabled()) {
            log.debug("bouncing message to postmaster");
        }
        MimeMessage orig = mail.getMessage();
        //Create the reply message
        MimeMessage reply = (MimeMessage) orig.reply(false);
        //If there is a Return-Path header,
        if (orig.getHeader(RFC2822Headers.RETURN_PATH) != null) {
            //Return the message to that address, not to the Reply-To
            // address
            reply.setRecipient(MimeMessage.RecipientType.TO,
                    new InternetAddress(orig.getHeader(RFC2822Headers.RETURN_PATH)[0]));
        }
        //Create the list of recipients in our MailAddress format
        Collection recipients = new HashSet();
        Address[] addresses = reply.getAllRecipients();
        for (int i = 0; i < addresses.length; i++) {
            recipients.add(new MailAddress((InternetAddress) addresses[i]));
        }
        //Change the sender...
        reply.setFrom(bouncer.toInternetAddress());
        try {
            //Create the message body
            MimeMultipart multipart = new MimeMultipart();
            //Add message as the first mime body part
            MimeBodyPart part = new MimeBodyPart();
            part.setContent(message, "text/plain");
            part.setHeader(RFC2822Headers.CONTENT_TYPE, "text/plain");
            multipart.addBodyPart(part);
            //Add the original message as the second mime body part
            part = new MimeBodyPart();
            part.setContent(orig.getContent(), orig.getContentType());
            part.setHeader(RFC2822Headers.CONTENT_TYPE, orig.getContentType());
            multipart.addBodyPart(part);
            reply.setHeader(RFC2822Headers.DATE, rfc822DateFormat.format(new Date()));
            reply.setContent(multipart);
            reply.setHeader(RFC2822Headers.CONTENT_TYPE, multipart.getContentType());
        } catch (IOException ioe) {
            throw new MessagingException("Unable to create multipart body", ioe);
        }
        //Send it off...
        //sendMail( bouncer, recipients, reply );
        que.queMail(reply);
    }
}