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:mitm.common.mail.repository.hibernate.MailRepositoryImplTest.java

@Test
public void testSearch() 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("test" + i + "@example.com, other@example.com", false),
                new InternetAddress("sender" + i + "@example.com", false), "127.0.0." + i, null, null);
    }//w w  w .  j  av  a 2 s . c o m

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

    // search from 
    List<? extends MailRepositoryItem> items = proxy.searchItems(DEFAULT_REPOSITORY,
            MailRepositorySearchField.FROM, "%linkedin%", 0, Integer.MAX_VALUE);
    assertEquals(10, items.size());

    // search from no hits
    items = proxy.searchItems(DEFAULT_REPOSITORY, MailRepositorySearchField.FROM, "linkedin", 0,
            Integer.MAX_VALUE);
    assertEquals(0, items.size());

    // search message ID
    items = proxy.searchItems(DEFAULT_REPOSITORY, MailRepositorySearchField.MESSAGE_ID,
            "<1266236208.59156794.1253209950952.JavaMail.app@ech3-cdn18.prod>", 3, 2);
    assertEquals(2, items.size());

    // search subject
    items = proxy.searchItems(DEFAULT_REPOSITORY, MailRepositorySearchField.SUBJECT, "%OPEN SOURCE GROUP%", 3,
            Integer.MAX_VALUE);
    assertEquals(7, items.size());

    // search sender
    items = proxy.searchItems(DEFAULT_REPOSITORY, MailRepositorySearchField.SENDER, "sender4@example.com", 0,
            Integer.MAX_VALUE);
    assertEquals(1, items.size());
    assertEquals("127.0.0.4", items.get(0).getRemoteAddress());

    // search recipients
    items = proxy.searchItems(DEFAULT_REPOSITORY, MailRepositorySearchField.RECIPIENTS, "test5@example.com", 0,
            Integer.MAX_VALUE);
    assertEquals(1, items.size());
    assertEquals("127.0.0.5", items.get(0).getRemoteAddress());

    // search recipients
    items = proxy.searchItems(DEFAULT_REPOSITORY, MailRepositorySearchField.RECIPIENTS, "other@example.com", 5,
            Integer.MAX_VALUE);
    assertEquals(5, items.size());
}

From source file:mitm.application.djigzo.james.mailets.Notify.java

private void addEmails(Object input, Collection<MailAddress> target) {
    if (input == null) {
        return;//  w ww . j  av  a2 s. c om
    }

    if (input instanceof String) {
        String addresses = StringUtils.trimToNull((String) input);

        if (addresses != null) {
            try {
                InternetAddress[] emails = InternetAddress.parse(addresses, false);

                if (emails != null) {
                    for (InternetAddress email : emails) {
                        if (email == null) {
                            continue;
                        }

                        /*
                         * We never want the invalid@invalid.tld address
                         */
                        if (EmailAddressUtils.isInvalidDummyAddress(email)) {
                            continue;
                        }

                        try {
                            target.add(new MailAddress(email));
                        } catch (ParseException e) {
                            getLogger().warn("Email address is invalid. Skipping address: " + email);
                        }
                    }
                }
            } catch (AddressException e) {
                getLogger().warn("Email address(s) are invalid " + addresses);
            }
        }
    } else if (input instanceof MailAddress) {
        MailAddress mailAddress = (MailAddress) input;
        /*
         * We never want the invalid@invalid.tld address
         */
        if (!EmailAddressUtils.isInvalidDummyAddress(mailAddress.toInternetAddress())) {
            target.add(mailAddress);
        }
    } else if (input instanceof InternetAddress) {
        InternetAddress inetAddress = (InternetAddress) input;
        /*
         * We never want the invalid@invalid.tld address
         */
        if (!EmailAddressUtils.isInvalidDummyAddress(inetAddress)) {
            try {
                target.add(new MailAddress(inetAddress));
            } catch (ParseException e) {
                getLogger().warn("Email address is invalid. Skipping address: " + input);
            }
        }
    } else if (input instanceof Collection) {
        for (Object o : (Collection<?>) input) {
            addEmails(o, target);
        }
    } else if (input instanceof Object[]) {
        for (Object o : (Object[]) input) {
            addEmails(o, target);
        }
    } else {
        /*
         * Fallback to #toString
         */
        addEmails(input.toString(), target);
    }
}

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));
    }/*from w w  w  .j a v  a  2 s .c  o 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:mitm.common.mail.repository.hibernate.MailRepositoryImplTest.java

@Test
public void testSearchCount() 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("test" + i + "@example.com, other@example.com", false),
                new InternetAddress("sender" + i + "@example.com", false), "127.0.0." + i, null, null);
    }//from   w  w  w.  j  a v  a 2s.c om

    assertEquals(nrOfItems, proxy.getItemCount(DEFAULT_REPOSITORY));
    // search from 
    assertEquals(10, proxy.getSearchCount(DEFAULT_REPOSITORY, MailRepositorySearchField.FROM, "%linkedin%"));

    // search from no hits
    assertEquals(0, proxy.getSearchCount(DEFAULT_REPOSITORY, MailRepositorySearchField.FROM, "linkedin"));

    // search message ID
    assertEquals(10, proxy.getSearchCount(DEFAULT_REPOSITORY, MailRepositorySearchField.MESSAGE_ID,
            "<1266236208.59156794.1253209950952.JavaMail.app@ech3-cdn18.prod>"));

    // search subject
    assertEquals(10,
            proxy.getSearchCount(DEFAULT_REPOSITORY, MailRepositorySearchField.SUBJECT, "%OPEN SOURCE GROUP%"));

    // search sender
    assertEquals(1,
            proxy.getSearchCount(DEFAULT_REPOSITORY, MailRepositorySearchField.SENDER, "sender4@example.com"));

    // search recipients
    assertEquals(1, proxy.getSearchCount(DEFAULT_REPOSITORY, MailRepositorySearchField.RECIPIENTS,
            "test5@example.com"));

    // search recipients
    assertEquals(10, proxy.getSearchCount(DEFAULT_REPOSITORY, MailRepositorySearchField.RECIPIENTS,
            "other@example.com"));
}

From source file:net.sourceforge.msscodefactory.cfasterisk.v2_4.CFAsteriskSMWar.CFAsteriskSMWarRequestResetPasswordHtml.java

protected void sendPasswordResetEMail(HttpServletRequest request, ICFSecuritySecUserObj resetUser,
        ICFSecurityClusterObj cluster) throws AddressException, MessagingException, NamingException {

    final String S_ProcName = "sendPasswordResetEMail";

    Properties props = System.getProperties();
    String clusterDescription = cluster.getRequiredDescription();

    Context ctx = new InitialContext();

    String smtpEmailFrom = (String) ctx.lookup("java:comp/env/CFAsterisk24SmtpEmailFrom");
    if ((smtpEmailFrom == null) || (smtpEmailFrom.length() <= 0)) {
        throw CFLib.getDefaultExceptionFactory().newNullArgumentException(getClass(), S_ProcName, 0,
                "JNDI lookup for CFAsterisk24SmtpEmailFrom");
    }/*from  w  w w . j  a va  2 s .  com*/

    smtpUsername = (String) ctx.lookup("java:comp/env/CFAsterisk24SmtpUsername");
    if ((smtpUsername == null) || (smtpUsername.length() <= 0)) {
        throw CFLib.getDefaultExceptionFactory().newNullArgumentException(getClass(), S_ProcName, 0,
                "JNDI lookup for CFAsterisk24SmtpUsername");
    }

    smtpPassword = (String) ctx.lookup("java:comp/env/CFAsterisk24SmtpPassword");
    if ((smtpPassword == null) || (smtpPassword.length() <= 0)) {
        throw CFLib.getDefaultExceptionFactory().newNullArgumentException(getClass(), S_ProcName, 0,
                "JNDI lookup for CFAsterisk24SmtpPassword");
    }

    Session emailSess = Session.getInstance(props, new Authenticator() {
        protected PasswordAuthentication getPasswordAuthentication() {
            return new PasswordAuthentication(smtpUsername, smtpPassword);
        }
    });

    String thisURI = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort()
            + request.getRequestURI().toString();
    int lastSlash = thisURI.lastIndexOf('/');
    String baseURI = thisURI.substring(0, lastSlash);
    UUID resetUUID = resetUser.getOptionalPasswordResetUuid();

    String msgBody = "<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01//EN\">\n" + "<HTML>\n" + "<BODY>\n"
            + "<p>\n" + "You requested a password reset for " + resetUser.getRequiredEMailAddress()
            + " used for accessing " + clusterDescription + ".\n" + "<p>"
            + "Please click on the following link to reset your password:<br>\n" + "<A HRef=\"" + baseURI
            + "/CFAsteriskSMWarResetPasswordHtml?ResetUUID=" + resetUUID.toString() + "\">" + baseURI
            + "/CFAsteriskSMWarResetPasswordHtml?ResetUUID=" + resetUUID.toString() + "</A>\n" + "<p>"
            + "Or click on the following link to cancel the reset request:<br>\n" + "<A HRef=\"" + baseURI
            + "/CFAsteriskSMWarCancelResetPasswordHtml?ResetUUID=" + resetUUID.toString() + "\">" + baseURI
            + "/CFAsteriskSMWarCancelResetPasswordHtml?ResetUUID=" + resetUUID.toString() + "</A>\n"
            + "</BODY>\n" + "</HTML>\n";

    MimeMessage msg = new MimeMessage(emailSess);
    msg.setFrom(new InternetAddress(smtpEmailFrom));
    InternetAddress mailTo[] = InternetAddress.parse(resetUser.getRequiredEMailAddress(), false);
    msg.setRecipient(Message.RecipientType.TO, mailTo[0]);
    msg.setSubject("You requested a password reset for your account with " + clusterDescription + "?");
    msg.setContent(msgBody, "text/html");
    msg.setSentDate(new Date());
    msg.saveChanges();

    Transport.send(msg);
}

From source file:org.nuxeo.ecm.user.invite.UserInvitationComponent.java

protected void generateMail(String destination, String copy, String title, String content)
        throws NamingException, MessagingException {

    InitialContext ic = new InitialContext();
    Session session = (Session) ic.lookup(getJavaMailJndiName());

    MimeMessage msg = new MimeMessage(session);
    msg.setFrom(new InternetAddress(session.getProperty("mail.from")));
    msg.setRecipients(Message.RecipientType.TO, InternetAddress.parse(destination, false));
    if (!isBlank(copy)) {
        msg.addRecipient(Message.RecipientType.CC, new InternetAddress(copy, false));
    }/*ww  w  .j a va  2 s  .co  m*/

    msg.setSubject(title, "UTF-8");
    msg.setSentDate(new Date());
    msg.setContent(content, "text/html; charset=utf-8");

    Transport.send(msg);
}

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

@Test
public void testPerformance() throws Exception {
    MimeMessage message = new MimeMessage(MailSession.getDefaultSession());

    int messageSize = 50 * SizeUtils.MB;

    byte[] content = new byte[messageSize];

    Arrays.fill(content, (byte) 'A');

    message.setContent(content, "application/octet-stream");
    message.saveChanges();//from   ww w.  j av a  2  s . com
    MailUtils.validateMessage(message);

    long start = System.currentTimeMillis();

    int nrOfItems = 10;

    for (int i = 0; i < nrOfItems; i++) {
        proxy.addItem(DEFAULT_REPOSITORY, message,
                InternetAddress.parse("test" + i + "@example.com, other@example.com", false),
                new InternetAddress("sender" + i + "@example.com", false), "127.0.0." + i, null, null);
    }

    double msec = (double) (System.currentTimeMillis() - start) / nrOfItems;

    System.out.println("msec / add:" + msec);

    assertTrue("Can fail on slower systems", msec < 10000);

    start = System.currentTimeMillis();

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

    for (MailRepositoryItem item : items) {
        System.out.println(item.getID());
    }

    msec = (double) (System.currentTimeMillis() - start) / nrOfItems;

    System.out.println("msec / get:" + msec);

    assertTrue("Can fail on slower systems", msec < 100);
}

From source file:net.sourceforge.msscodefactory.cfasterisk.v2_2.CFAstSMWar.CFAstSMWarRequestResetPasswordHtml.java

protected void sendPasswordResetEMail(HttpServletRequest request, ICFAstSecUserObj resetUser,
        ICFAstClusterObj cluster) throws AddressException, MessagingException, NamingException {

    final String S_ProcName = "sendPasswordResetEMail";

    Properties props = System.getProperties();
    String clusterDescription = cluster.getRequiredDescription();

    Context ctx = new InitialContext();

    String smtpEmailFrom = (String) ctx.lookup("java:comp/env/CFAst22SmtpEmailFrom");
    if ((smtpEmailFrom == null) || (smtpEmailFrom.length() <= 0)) {
        throw CFLib.getDefaultExceptionFactory().newNullArgumentException(getClass(), S_ProcName, 0,
                "JNDI lookup for CFAst22SmtpEmailFrom");
    }/*from  ww w  . j  av  a  2s.  c om*/

    smtpUsername = (String) ctx.lookup("java:comp/env/CFAst22SmtpUsername");
    if ((smtpUsername == null) || (smtpUsername.length() <= 0)) {
        throw CFLib.getDefaultExceptionFactory().newNullArgumentException(getClass(), S_ProcName, 0,
                "JNDI lookup for CFAst22SmtpUsername");
    }

    smtpPassword = (String) ctx.lookup("java:comp/env/CFAst22SmtpPassword");
    if ((smtpPassword == null) || (smtpPassword.length() <= 0)) {
        throw CFLib.getDefaultExceptionFactory().newNullArgumentException(getClass(), S_ProcName, 0,
                "JNDI lookup for CFAst22SmtpPassword");
    }

    Session emailSess = Session.getInstance(props, new Authenticator() {
        protected PasswordAuthentication getPasswordAuthentication() {
            return new PasswordAuthentication(smtpUsername, smtpPassword);
        }
    });

    String thisURI = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort()
            + request.getRequestURI().toString();
    int lastSlash = thisURI.lastIndexOf('/');
    String baseURI = thisURI.substring(0, lastSlash);
    UUID resetUUID = resetUser.getOptionalPasswordResetUuid();

    String msgBody = "<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01//EN\">\n" + "<HTML>\n" + "<BODY>\n"
            + "<p>\n" + "You requested a password reset for " + resetUser.getRequiredEMailAddress()
            + " used for accessing " + clusterDescription + ".\n" + "<p>"
            + "Please click on the following link to reset your password:<br>\n" + "<A HRef=\"" + baseURI
            + "/CFAstSMWarResetPasswordHtml?ResetUUID=" + resetUUID.toString() + "\">" + baseURI
            + "/CFAstSMWarResetPasswordHtml?ResetUUID=" + resetUUID.toString() + "</A>\n" + "<p>"
            + "Or click on the following link to cancel the reset request:<br>\n" + "<A HRef=\"" + baseURI
            + "/CFAstSMWarCancelResetPasswordHtml?ResetUUID=" + resetUUID.toString() + "\">" + baseURI
            + "/CFAstSMWarCancelResetPasswordHtml?ResetUUID=" + resetUUID.toString() + "</A>\n" + "</BODY>\n"
            + "</HTML>\n";

    MimeMessage msg = new MimeMessage(emailSess);
    msg.setFrom(new InternetAddress(smtpEmailFrom));
    InternetAddress mailTo[] = InternetAddress.parse(resetUser.getRequiredEMailAddress(), false);
    msg.setRecipient(Message.RecipientType.TO, mailTo[0]);
    msg.setSubject("You requested a password reset for your account with " + clusterDescription + "?");
    msg.setContent(msgBody, "text/html");
    msg.setSentDate(new Date());
    msg.saveChanges();

    Transport.send(msg);
}

From source file:com.liferay.mail.imap.IMAPAccessor.java

protected InternetAddress[] getRecipients(long messageId) throws PortalException {

    try {/*from w w  w  . j a  va 2  s .  c om*/
        com.liferay.mail.model.Message message = MessageLocalServiceUtil.getMessage(messageId);

        StringBundler sb = new StringBundler(6);

        sb.append(message.getTo());
        sb.append(StringPool.COMMA);
        sb.append(message.getCc());
        sb.append(StringPool.COMMA);
        sb.append(message.getBcc());
        sb.append(StringPool.COMMA);

        return InternetAddress.parse(sb.toString(), true);
    } catch (AddressException ae) {
        throw new MailException(MailException.MESSAGE_INVALID_ADDRESS, ae);
    }
}

From source file:org.j2free.email.EmailService.java

/**
 * Sends a HTML e-mail based on a template
 *
 * @param from The "from" e-mail address
 * @param to The recipient's e-mail address
 * @param subject The subject of the e-mail
 * @param templateKey The key to look up the e-mail template
 * @param priority The priority this message should take if there are other queued messages
 * @param ccSender If true, cc's the from address on the e-mail sent, otherwise does not.
 * @param params An array of pairs of dynamic attributes for the template; i.e. for a template with dynamic section "body", <code>new KeyValuePair&lt;String,String&gt;("body",body);</code>
 * @throws javax.mail.internet.AddressException if the FROM or TO address is invalid
 * @throws MessagingException//w ww . j  a  v a2 s . c  om
 * @throws TemplateException if the specified template has not been registered, or there are unreplaced tokens
 * @throws RejectedExecutionException if <tt>EmailService</tt> has already been shutdown
 */
public void sendTemplate(KeyValuePair<String, String> from, String to, String subject, String templateKey,
        Priority priority, boolean ccSender, KeyValuePair<String, String>... params)
        throws AddressException, MessagingException, TemplateException, RejectedExecutionException {
    sendTemplate(from, InternetAddress.parse(to, false), subject, templateKey, priority, ccSender, params);
}