Example usage for javax.mail.internet InternetAddress parse

List of usage examples for javax.mail.internet InternetAddress parse

Introduction

In this page you can find the example usage for javax.mail.internet InternetAddress parse.

Prototype

public static InternetAddress[] parse(String addresslist, boolean strict) throws AddressException 

Source Link

Document

Parse the given sequence of addresses into InternetAddress objects.

Usage

From source file:org.exoplatform.answer.webui.FAQUtils.java

public static boolean isValidEmailAddresses(String addressList) throws Exception {
    if (isFieldEmpty(addressList))
        return true;
    boolean isInvalid = true;
    try {/* w  ww  . ja  va  2  s .com*/
        InternetAddress[] iAdds = InternetAddress.parse(addressList, true);
        String emailRegex = "[_A-Za-z0-9-]+(\\.[_A-Za-z0-9-]+)*@[_A-Za-z0-9-.]+\\.[A-Za-z]{2,5}";
        for (int i = 0; i < iAdds.length; i++) {
            if (!iAdds[i].getAddress().matches(emailRegex))
                isInvalid = false;
        }
    } catch (AddressException e) {
        return false;
    }
    return isInvalid;
}

From source file:org.openmeetings.test.calendar.TestSendIcalMessage.java

private void sendIcalMessage() throws Exception {

    log.debug("sendIcalMessage");

    // Evaluating Configuration Data
    String smtpServer = cfgManagement.getConfKey(3, "smtp_server").getConf_value();
    String smtpPort = cfgManagement.getConfKey(3, "smtp_port").getConf_value();
    // String from = "openmeetings@xmlcrm.org";
    String from = cfgManagement.getConfKey(3, "system_email_addr").getConf_value();

    String emailUsername = cfgManagement.getConfKey(3, "email_username").getConf_value();
    String emailUserpass = cfgManagement.getConfKey(3, "email_userpass").getConf_value();

    Properties props = System.getProperties();

    props.put("mail.smtp.host", smtpServer);
    props.put("mail.smtp.port", smtpPort);

    Configuration conf = cfgManagement.getConfKey(3, "mail.smtp.starttls.enable");
    if (conf != null) {
        if (conf.getConf_value().equals("1")) {
            props.put("mail.smtp.starttls.enable", "true");
        }/*from  w  w  w  .j a va2s.  c o  m*/
    }

    // Check for Authentification
    Session session = null;
    if (emailUsername != null && emailUsername.length() > 0 && emailUserpass != null
            && emailUserpass.length() > 0) {
        // use SMTP Authentication
        props.put("mail.smtp.auth", "true");
        session = Session.getDefaultInstance(props, new SmtpAuthenticator(emailUsername, emailUserpass));
    } else {
        // not use SMTP Authentication
        session = Session.getDefaultInstance(props, null);
    }

    // Building MimeMessage
    MimeMessage mimeMessage = new MimeMessage(session);
    mimeMessage.setSubject(subject);
    mimeMessage.setFrom(new InternetAddress(from));
    mimeMessage.addRecipients(Message.RecipientType.TO, InternetAddress.parse(recipients, false));

    // -- Create a new message --
    BodyPart msg = new MimeBodyPart();
    msg.setDataHandler(new DataHandler(new ByteArrayDataSource(htmlBody, "text/html; charset=\"utf-8\"")));

    Multipart multipart = new MimeMultipart();

    BodyPart iCalAttachment = new MimeBodyPart();
    iCalAttachment.setDataHandler(new DataHandler(new javax.mail.util.ByteArrayDataSource(
            new ByteArrayInputStream(iCalMimeBody), "text/calendar;method=REQUEST;charset=\"UTF-8\"")));
    iCalAttachment.setFileName("invite.ics");

    multipart.addBodyPart(iCalAttachment);
    multipart.addBodyPart(msg);

    mimeMessage.setSentDate(new Date());
    mimeMessage.setContent(multipart);

    // -- Set some other header information --
    // mimeMessage.setHeader("X-Mailer", "XML-Mail");
    // mimeMessage.setSentDate(new Date());

    // Transport trans = session.getTransport("smtp");
    Transport.send(mimeMessage);

}

From source file:org.jahia.services.workflow.jbpm.JBPMMailProducer.java

private void fillRecipients(AddressTemplate addressTemplate, Message email, Message.RecipientType recipientType,
        Execution execution, JCRSessionWrapper session)
        throws MessagingException, RepositoryException, ScriptException {
    // resolve and parse addresses
    String addresses = addressTemplate.getAddresses();
    if (addresses != null) {
        addresses = evaluateExpression(execution, addresses, session);
        // non-strict parsing applies to a list of mail addresses entered by a human
        email.addRecipients(recipientType, InternetAddress.parse(addresses, false));
    }//from  w w  w  .  j  av a2 s  .c  om

    EnvironmentImpl environment = EnvironmentImpl.getCurrent();
    IdentitySession identitySession = environment.get(IdentitySession.class);
    AddressResolver addressResolver = environment.get(AddressResolver.class);

    // resolve and tokenize users
    String userList = addressTemplate.getUsers();
    if (userList != null) {
        String[] userIds = tokenizeActors(userList, execution, session);
        List<User> users = identitySession.findUsersById(userIds);
        email.addRecipients(recipientType, resolveAddresses(users, addressResolver));
    }

    // resolve and tokenize groups
    String groupList = addressTemplate.getGroups();
    if (groupList != null) {
        for (String groupId : tokenizeActors(groupList, execution, session)) {
            Group group = identitySession.findGroupById(groupId);
            email.addRecipients(recipientType, addressResolver.resolveAddresses(group));
        }
    }
}

From source file:com.cubusmail.gwtui.server.services.UserAccountService.java

/**
 * Parse out, the uncomplete Adresses//from   ww w  . ja  v  a  2 s  .c  o m
 * 
 * @param addressLine
 * @return
 * @throws MessagingException
 */
public String[] parsePreviousAndLastAddress(String addressLine) {

    String[] result = new String[] { "", "" };

    try {
        InternetAddress[] addresses = InternetAddress.parse(addressLine, false);

        if (addresses != null) {
            if (addresses.length > 1) {
                InternetAddress[] dest = new InternetAddress[addresses.length - 1];
                for (int i = 0; i < addresses.length - 1; i++) {
                    dest[i] = addresses[i];
                }
                result[0] = MessageUtils.getMailAdressString(dest, AddressStringType.COMPLETE);
            }
            result[1] = addresses[addresses.length - 1].toUnicodeString();
        }
    } catch (MessagingException e) {
        // should never happen
        log.error(e.getMessage());
    }

    return result;
}

From source file:org.jahia.services.workflow.jbpm.custom.email.JBPMMailProducer.java

protected void fillRecipients(AddressTemplate addressTemplate, Message email,
        Message.RecipientType recipientType, WorkItem workItem, JCRSessionWrapper session) throws Exception {
    // resolve and parse addresses
    String addresses = addressTemplate.getAddresses();
    if (addresses != null) {
        addresses = evaluateExpression(workItem, addresses, session);
        // non-strict parsing applies to a list of mail addresses entered by a human
        email.addRecipients(recipientType, InternetAddress.parse(addresses, false));
    }/*from   w  ww.jav a2s  . c o m*/

    // resolve and tokenize users
    String userList = addressTemplate.getUsers();
    if (userList != null) {
        String[] userIds = tokenizeActors(userList, workItem, session);
        List<User> users = new ArrayList<User>();
        for (String userId : userIds) {
            if (userId.startsWith("assignableFor(")) {
                String task = StringUtils.substringBetween(userId, "assignableFor(", ")");
                WorkflowDefinition definition = WorkflowService.getInstance()
                        .getWorkflow("jBPM", Long.toString(workItem.getProcessInstanceId()), null)
                        .getWorkflowDefinition();
                List<JahiaPrincipal> principals = WorkflowService.getInstance().getAssignedRole(definition,
                        task, Long.toString(workItem.getProcessInstanceId()), session);
                for (JahiaPrincipal principal : principals) {
                    if (principal instanceof JahiaUser) {
                        if (!UserPreferencesHelper.areEmailNotificationsDisabled((JahiaUser) principal)) {
                            users.add(taskIdentityService.getUserById(((JahiaUser) principal).getUserKey()));
                        }
                    } else if (principal instanceof JahiaGroup) {
                        JCRGroupNode groupNode = groupManagerService
                                .lookupGroupByPath(principal.getLocalPath());
                        if (groupNode != null) {
                            for (JCRUserNode user : groupNode.getRecursiveUserMembers()) {
                                if (!UserPreferencesHelper.areEmailNotificationsDisabled(user)) {
                                    users.add(taskIdentityService.getUserById(user.getPath()));
                                }
                            }
                        }
                    }
                }
            } else {
                User userById = taskIdentityService.getUserById(userId);
                if (userById instanceof JBPMTaskIdentityService.UserImpl
                        && !((JBPMTaskIdentityService.UserImpl) userById).areEmailNotificationsDisabled()) {
                    users.add(userById);
                }
            }
        }
        email.addRecipients(recipientType, getAddresses(users));
    }

    // resolve and tokenize groups
    String groupList = addressTemplate.getGroups();
    if (groupList != null) {
        for (String groupId : tokenizeActors(groupList, workItem, session)) {
            org.kie.api.task.model.Group group = taskIdentityService.getGroupById(groupId);
            email.addRecipients(recipientType, getAddresses(group));
        }
    }
}

From source file:org.pentaho.platform.util.Emailer.java

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

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

    try {//from   ww w. j  av  a 2s  .c  o  m
        // Get a Session object
        Session session;

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

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

        final MimeMessage msg;

        if (EMBEDDED_HTML.equals(attachmentMimeType)) {

            //Message is ready
            msg = new MimeMessage(session, attachment);

            if (body != null) {
                //We need to add message to the top of the email body
                final MimeMultipart oldMultipart = (MimeMultipart) msg.getContent();
                final MimeMultipart newMultipart = new MimeMultipart("related");

                for (int i = 0; i < oldMultipart.getCount(); i++) {
                    BodyPart bodyPart = oldMultipart.getBodyPart(i);

                    final Object content = bodyPart.getContent();
                    //Main HTML body
                    if (content instanceof String) {
                        final String newContent = body + "<br/><br/>" + content;
                        final MimeBodyPart part = new MimeBodyPart();
                        part.setText(newContent, "UTF-8", "html");
                        newMultipart.addBodyPart(part);
                    } else {
                        //CID attachments
                        newMultipart.addBodyPart(bodyPart);
                    }
                }

                msg.setContent(newMultipart);
            }
        } else {

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

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

            ByteArrayDataSource dataSource = new ByteArrayDataSource(attachment, attachmentMimeType);

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

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

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

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

        if ((to != null) && (to.trim().length() > 0)) {
            msg.setRecipients(Message.RecipientType.TO, InternetAddress.parse(to, false));
        }
        if ((cc != null) && (cc.trim().length() > 0)) {
            msg.setRecipients(Message.RecipientType.CC, InternetAddress.parse(cc, false));
        }
        if ((bcc != null) && (bcc.trim().length() > 0)) {
            msg.setRecipients(Message.RecipientType.BCC, InternetAddress.parse(bcc, false));
        }

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

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

        Transport.send(msg);

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

From source file:mitm.common.mail.repository.hibernate.MailRepositoryImplTest.java

@Test
public void testGetItem() throws Exception {
    MimeMessage message = loadMessage("html-alternative.eml");

    assertEquals(0, proxy.getItemCount(DEFAULT_REPOSITORY));

    MailRepositoryItem item = proxy.addItem(DEFAULT_REPOSITORY, message,
            InternetAddress.parse("test1@example.com, test2@example.com", false),
            new InternetAddress("sender@example.com"), "127.0.0.1", new Date(123456), new byte[] { 1, 2, 3 });

    MailRepositoryItem item2 = proxy.getItem(DEFAULT_REPOSITORY, item.getID());

    assertNotNull(item2);/*from  w  w w  .j a  v  a2s .  c  o m*/

    assertEquals("Open Source Group Members <group-digests@linkedin.com>", item2.getFromHeader());
    assertEquals("From Joshua Barger and other Open Source group members on LinkedIn", item2.getSubject());
    assertEquals("<1266236208.59156794.1253209950952.JavaMail.app@ech3-cdn18.prod>", item2.getMessageID());
    assertEquals("sender@example.com", item2.getSender().getAddress());
    assertEquals("127.0.0.1", item2.getRemoteAddress());
    assertEquals(123456, item2.getLastUpdated().getTime());
    assertTrue(Arrays.equals(new byte[] { 1, 2, 3 }, item2.getAdditionalData()));

    assertEquals("[test1@example.com, test2@example.com]",
            proxy.getRecipients(DEFAULT_REPOSITORY, item2.getID()).toString());

    proxy.assertMessage(DEFAULT_REPOSITORY, item2.getID(), message);
}

From source file:org.exoplatform.contact.CalendarUtils.java

public static boolean isValidEmailAddresses(String value) {
    if (isEmpty(value))
        return true;
    value = StringUtils.remove(value, " ");
    value = StringUtils.replace(value, SEMICOLON, COMMA);
    try {/*from w w  w  .  j a v a 2s .  com*/
        InternetAddress[] iAdds = InternetAddress.parse(value, true);
        String emailRegex = "[_A-Za-z0-9-]+(\\.[_A-Za-z0-9-]+)*@[_A-Za-z0-9-.]+\\.[A-Za-z]{2,6}";
        for (int i = 0; i < iAdds.length; i++) {
            if (!iAdds[i].getAddress().matches(emailRegex))
                return false;
        }
    } catch (AddressException e) {
        return false;
    }
    return true;
}

From source file:org.pentaho.platform.plugin.action.builtin.EmailComponent.java

@Override
public boolean executeAction() {
    EmailAction emailAction = (EmailAction) getActionDefinition();

    String messagePlain = emailAction.getMessagePlain().getStringValue();
    String messageHtml = emailAction.getMessageHtml().getStringValue();
    String subject = emailAction.getSubject().getStringValue();
    String to = emailAction.getTo().getStringValue();
    String cc = emailAction.getCc().getStringValue();
    String bcc = emailAction.getBcc().getStringValue();
    String from = emailAction.getFrom().getStringValue(defaultFrom);
    if (from.trim().length() == 0) {
        from = defaultFrom;//from  w w w.  j  ava  2 s  .  c o m
    }

    /*
     * if( context.getInputNames().contains( "attach" ) ) { //$NON-NLS-1$ Object attachParameter =
     * context.getInputParameter( "attach" ).getValue(); //$NON-NLS-1$ // We have a list of attachments, each element of
     * the list is the name of the parameter containing the attachment // Use the parameter filename portion as the
     * attachment name. if ( attachParameter instanceof String ) { String attachName = context.getInputParameter(
     * "attach-name" ).getStringValue(); //$NON-NLS-1$ AttachStruct attachData = getAttachData( context,
     * (String)attachParameter, attachName ); if ( attachData != null ) { attachments.add( attachData ); } } else if (
     * attachParameter instanceof List ) { for ( int i = 0; i < ((List)attachParameter).size(); ++i ) { AttachStruct
     * attachData = getAttachData( context, ((List)attachParameter).get( i ).toString(), null ); if ( attachData != null
     * ) { attachments.add( attachData ); } } } else if ( attachParameter instanceof Map ) { for ( Iterator it =
     * ((Map)attachParameter).entrySet().iterator(); it.hasNext(); ) { Map.Entry entry = (Map.Entry)it.next();
     * AttachStruct attachData = getAttachData( context, (String)entry.getValue(), (String)entry.getKey() ); if (
     * attachData != null ) { attachments.add( attachData ); } } } }
     * 
     * int maxSize = Integer.MAX_VALUE; try { maxSize = new Integer( props.getProperty( "mail.max.attach.size" )
     * ).intValue(); } catch( Throwable t ) { //ignore if not set to a valid value }
     * 
     * if ( totalAttachLength > maxSize ) { // Sort them in order TreeMap tm = new TreeMap(); for( int idx=0;
     * idx<attachments.size(); idx++ ) { // tm.put( new Integer( )) } }
     */

    if (ComponentBase.debug) {
        debug(Messages.getInstance().getString("Email.DEBUG_TO_FROM", to, from)); //$NON-NLS-1$
        debug(Messages.getInstance().getString("Email.DEBUG_CC_BCC", cc, bcc)); //$NON-NLS-1$
        debug(Messages.getInstance().getString("Email.DEBUG_SUBJECT", subject)); //$NON-NLS-1$
        debug(Messages.getInstance().getString("Email.DEBUG_PLAIN_MESSAGE", messagePlain)); //$NON-NLS-1$
        debug(Messages.getInstance().getString("Email.DEBUG_HTML_MESSAGE", messageHtml)); //$NON-NLS-1$
    }

    if ((to == null) || (to.trim().length() == 0)) {

        // Get the output stream that the feedback is going into
        OutputStream feedbackStream = getFeedbackOutputStream();
        if (feedbackStream != null) {
            createFeedbackParameter("to", Messages.getInstance().getString("Email.USER_ENTER_EMAIL_ADDRESS"), //$NON-NLS-1$//$NON-NLS-2$
                    "", "", true); //$NON-NLS-1$ //$NON-NLS-2$
            setFeedbackMimeType("text/html"); //$NON-NLS-1$
            return true;
        } else {
            return false;
        }
    }
    if (subject == null) {
        error(Messages.getInstance().getErrorString("Email.ERROR_0005_NULL_SUBJECT", getActionName())); //$NON-NLS-1$
        return false;
    }
    if ((messagePlain == null) && (messageHtml == null)) {
        error(Messages.getInstance().getErrorString("Email.ERROR_0006_NULL_BODY", getActionName())); //$NON-NLS-1$
        return false;
    }

    if (getRuntimeContext().isPromptPending()) {
        return true;
    }

    try {
        Properties props = new Properties();
        final IEmailService service = PentahoSystem.get(IEmailService.class, "IEmailService",
                PentahoSessionHolder.getSession());
        props.put("mail.smtp.host", service.getEmailConfig().getSmtpHost());
        props.put("mail.smtp.port", ObjectUtils.toString(service.getEmailConfig().getSmtpPort()));
        props.put("mail.transport.protocol", service.getEmailConfig().getSmtpProtocol());
        props.put("mail.smtp.starttls.enable", ObjectUtils.toString(service.getEmailConfig().isUseStartTls()));
        props.put("mail.smtp.auth", ObjectUtils.toString(service.getEmailConfig().isAuthenticate()));
        props.put("mail.smtp.ssl", ObjectUtils.toString(service.getEmailConfig().isUseSsl()));
        props.put("mail.smtp.quitwait", ObjectUtils.toString(service.getEmailConfig().isSmtpQuitWait()));
        props.put("mail.from.default", service.getEmailConfig().getDefaultFrom());
        String fromName = service.getEmailConfig().getFromName();
        if (StringUtils.isEmpty(fromName)) {
            fromName = Messages.getInstance().getString("schedulerEmailFromName");
        }
        props.put("mail.from.name", fromName);
        props.put("mail.debug", ObjectUtils.toString(service.getEmailConfig().isDebug()));

        Session session;
        if (service.getEmailConfig().isAuthenticate()) {
            props.put("mail.userid", service.getEmailConfig().getUserId());
            props.put("mail.password", service.getEmailConfig().getPassword());
            Authenticator authenticator = new EmailAuthenticator();
            session = Session.getInstance(props, authenticator);
        } else {
            session = Session.getInstance(props);
        }

        // debugging is on if either component (xaction) or email config debug is on
        if (service.getEmailConfig().isDebug() || ComponentBase.debug) {
            session.setDebug(true);
        }

        // construct the message
        MimeMessage msg = new MimeMessage(session);
        if (from != null) {
            msg.setFrom(new InternetAddress(from));
        } else {
            // There should be no way to get here
            error(Messages.getInstance().getString("Email.ERROR_0012_FROM_NOT_DEFINED")); //$NON-NLS-1$
        }

        if ((to != null) && (to.trim().length() > 0)) {
            msg.setRecipients(Message.RecipientType.TO, InternetAddress.parse(to, false));
        }
        if ((cc != null) && (cc.trim().length() > 0)) {
            msg.setRecipients(Message.RecipientType.CC, InternetAddress.parse(cc, false));
        }
        if ((bcc != null) && (bcc.trim().length() > 0)) {
            msg.setRecipients(Message.RecipientType.BCC, InternetAddress.parse(bcc, false));
        }

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

        EmailAttachment[] emailAttachments = emailAction.getAttachments();
        if ((messagePlain != null) && (messageHtml == null) && (emailAttachments.length == 0)) {
            msg.setText(messagePlain, LocaleHelper.getSystemEncoding());
        } else if (emailAttachments.length == 0) {
            if (messagePlain != null) {
                msg.setContent(messagePlain, "text/plain; charset=" + LocaleHelper.getSystemEncoding()); //$NON-NLS-1$          
            }
            if (messageHtml != null) {
                msg.setContent(messageHtml, "text/html; charset=" + LocaleHelper.getSystemEncoding()); //$NON-NLS-1$
            }
        } else {
            // need to create a multi-part message...
            // create the Multipart and add its parts to it
            Multipart multipart = new MimeMultipart();
            // create and fill the first message part
            if (messageHtml != null) {
                // create and fill the first message part
                MimeBodyPart htmlBodyPart = new MimeBodyPart();
                htmlBodyPart.setContent(messageHtml, "text/html; charset=" + LocaleHelper.getSystemEncoding()); //$NON-NLS-1$
                multipart.addBodyPart(htmlBodyPart);
            }

            if (messagePlain != null) {
                MimeBodyPart textBodyPart = new MimeBodyPart();
                textBodyPart.setContent(messagePlain,
                        "text/plain; charset=" + LocaleHelper.getSystemEncoding()); //$NON-NLS-1$
                multipart.addBodyPart(textBodyPart);
            }

            for (EmailAttachment element : emailAttachments) {
                IPentahoStreamSource source = element.getContent();
                if (source == null) {
                    error(Messages.getInstance().getErrorString("Email.ERROR_0015_ATTACHMENT_FAILED")); //$NON-NLS-1$
                    return false;
                }
                DataSource dataSource = new ActivationHelper.PentahoStreamSourceWrapper(source);
                String attachmentName = element.getName();
                if (ComponentBase.debug) {
                    debug(Messages.getInstance().getString("Email.DEBUG_ADDING_ATTACHMENT", attachmentName)); //$NON-NLS-1$
                }

                // create the second message part
                MimeBodyPart attachmentBodyPart = new MimeBodyPart();

                // attach the file to the message
                attachmentBodyPart.setDataHandler(new DataHandler(dataSource));
                attachmentBodyPart.setFileName(attachmentName);
                if (ComponentBase.debug) {
                    debug(Messages.getInstance().getString("Email.DEBUG_ATTACHMENT_SOURCE", //$NON-NLS-1$
                            dataSource.getName()));
                }
                multipart.addBodyPart(attachmentBodyPart);
            }

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

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

        Transport.send(msg);

        if (ComponentBase.debug) {
            debug(Messages.getInstance().getString("Email.DEBUG_EMAIL_SUCCESS")); //$NON-NLS-1$
        }
        return true;
        // TODO: persist the content set for a while...
    } catch (SendFailedException e) {
        error(Messages.getInstance().getErrorString("Email.ERROR_0011_SEND_FAILED", to), e); //$NON-NLS-1$
        /*
         * Exception ne; MessagingException sfe = e; while ((ne = sfe.getNextException()) != null && ne instanceof
         * MessagingException) { sfe = (MessagingException) ne;
         * error(Messages.getInstance().getErrorString("Email.ERROR_0011_SEND_FAILED", sfe.toString()), sfe);
         * //$NON-NLS-1$ }
         */

    } catch (AuthenticationFailedException e) {
        error(Messages.getInstance().getString("Email.ERROR_0014_AUTHENTICATION_FAILED", to), e); //$NON-NLS-1$
    } catch (Throwable e) {
        error(Messages.getInstance().getErrorString("Email.ERROR_0011_SEND_FAILED", to), e); //$NON-NLS-1$
    }
    return false;
}

From source file:mitm.common.mail.repository.hibernate.MailRepositoryImplTest.java

@Test
public void testGetItems() throws Exception {
    MimeMessage message = loadMessage("html-alternative.eml");

    assertEquals(0, proxy.getItemCount(DEFAULT_REPOSITORY));

    int nrOfItems = 10;

    for (int i = 0; i < nrOfItems; i++) {
        proxy.addItem(DEFAULT_REPOSITORY, message,
                InternetAddress.parse("test1@example.com, test2@example.com", false), null, Integer.toString(i),
                null, null);/*from w  w w . j a v  a  2 s  . c  om*/
    }

    assertEquals(nrOfItems, proxy.getItemCount(DEFAULT_REPOSITORY));

    List<? extends MailRepositoryItem> items = proxy.getItems(DEFAULT_REPOSITORY, 0, Integer.MAX_VALUE);

    assertEquals(nrOfItems, items.size());

    for (int i = 0; i < nrOfItems; i++) {
        MailRepositoryItem item = items.get(i);

        assertEquals(Integer.toString(i), item.getRemoteAddress());
    }

    items = proxy.getItems(DEFAULT_REPOSITORY, 0, 1);

    assertEquals(1, items.size());

    items = proxy.getItems(DEFAULT_REPOSITORY, 8, 100);

    assertEquals(2, items.size());

    assertEquals("8", items.get(0).getRemoteAddress());
    assertEquals("9", items.get(1).getRemoteAddress());
}