Example usage for javax.mail.internet MimeMessage getReplyTo

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

Introduction

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

Prototype

@Override
public Address[] getReplyTo() throws MessagingException 

Source Link

Document

Return the value of the RFC 822 "Reply-To" header field.

Usage

From source file:it.ozimov.springboot.templating.mail.utils.EmailToMimeMessageTest.java

public static void validateReplyTo(final Email email, final MimeMessage sentMessage)
        throws MessagingException, IOException {
    final List<Address> replyTos = asList(sentMessage.getReplyTo());
    assertThat(replyTos, hasSize(1)); // redundant with contains
    assertThat(replyTos, contains((Address) email.getReplyTo()));
}

From source file:mitm.common.mail.EmailAddressUtils.java

/**
 * Returns the Reply-To not throwing any exception. If the Reply-To header cannot be retrieved, null will be
 * returned.//  w  w  w . j  a v  a  2  s .c o  m
 */
public static Address[] getReplyToQuietly(MimeMessage message) {
    Address[] replyTos = null;

    if (message != null) {
        try {
            replyTos = message.getReplyTo();
        } catch (Exception e) {
            logger.debug("Reply-To is not valid", e);
        }
    }

    return replyTos;
}

From source file:jenkins.plugins.mailer.tasks.MimeMessageBuilderTest.java

private void checkMultipleReplyToAddress(MimeMessageBuilder messageBuilder) throws Exception {
    MimeMessage mimeMessage = messageBuilder.buildMimeMessage();
    Address[] recipients = mimeMessage.getReplyTo();
    Assert.assertEquals(3, recipients.length);
    Assert.assertEquals(X, recipients[0].toString());
    Assert.assertEquals(Y, recipients[1].toString());
    Assert.assertEquals(Z, recipients[2].toString());
}

From source file:eu.openanalytics.rsb.component.EmailDepositHandler.java

@SuppressWarnings("unchecked")
public void handleJob(final Message<MimeMessage> message) throws MessagingException, IOException {
    final DepositEmailConfiguration depositEmailConfiguration = message.getHeaders()
            .get(EMAIL_CONFIG_HEADER_NAME, DepositEmailConfiguration.class);
    final String applicationName = depositEmailConfiguration.getApplicationName();
    final MimeMessage mimeMessage = message.getPayload();

    final Address[] replyTo = mimeMessage.getReplyTo();
    Validate.notEmpty(replyTo, "no reply address found for job emailed with headers:"
            + Collections.list(mimeMessage.getAllHeaders()));

    final Map<String, Serializable> meta = new HashMap<String, Serializable>();
    meta.put(EMAIL_SUBJECT_META_NAME, mimeMessage.getSubject());
    meta.put(EMAIL_ADDRESSEE_META_NAME, getPrimaryAddressee(mimeMessage));
    meta.put(EMAIL_REPLY_TO_META_NAME, replyTo[0].toString());
    meta.put(EMAIL_REPLY_CC_META_NAME, getCCAddressees(mimeMessage));
    meta.put(EMAIL_BODY_META_NAME, getResponseBody(depositEmailConfiguration));

    final MultiFilesJob job = new MultiFilesJob(Source.EMAIL, applicationName,
            ApplicationPermissionEvaluator.NO_AUTHENTICATED_USERNAME, UUID.randomUUID(),
            (GregorianCalendar) GregorianCalendar.getInstance(), meta);

    try {/*from w  w  w.j  av  a  2s . c o m*/
        addEmailAttachmentsToJob(depositEmailConfiguration, mimeMessage, job);
        getMessageDispatcher().dispatch(job);
    } catch (final Exception e) {
        final MultiFilesResult errorResult = job.buildErrorResult(e, getMessages());
        handleResult(errorResult);
    }
}

From source file:jenkins.plugins.mailer.tasks.MimeMessageBuilderTest.java

@Test
public void test_construction() throws Exception {
    MimeMessageBuilder messageBuilder = new MimeMessageBuilder();

    messageBuilder.addRecipients("tom.xxxx@gmail.com, tom.yyyy@gmail.com");
    MimeMessage mimeMessage = messageBuilder.buildMimeMessage();

    // check from and reply-to
    Address[] from = mimeMessage.getFrom();
    Assert.assertNotNull(from);// w  w w .j  a  v a 2s .com
    Assert.assertEquals(1, from.length);
    Assert.assertEquals(A, from[0].toString());
    Address[] replyTo = mimeMessage.getReplyTo();
    Assert.assertNotNull(from);
    Assert.assertEquals(1, replyTo.length);
    Assert.assertEquals(A, replyTo[0].toString());

    // check the recipient list...
    Address[] allRecipients = mimeMessage.getAllRecipients();
    Assert.assertNotNull(allRecipients);
    Assert.assertEquals(2, allRecipients.length);
    Assert.assertEquals(X, allRecipients[0].toString());
    Assert.assertEquals(Y, allRecipients[1].toString());

    // Make sure we can regen the instance identifier public key
    String encodedIdent = mimeMessage.getHeader("X-Instance-Identity")[0];
    byte[] image = Base64.decodeBase64(encodedIdent);
    PublicKey publicKey = KeyFactory.getInstance("RSA").generatePublic(new X509EncodedKeySpec(image));
    Assert.assertNotNull(publicKey);
}

From source file:org.drools.task.service.TaskServiceDeadlinesBaseTest.java

public void testDelayedEmailNotificationOnDeadline() throws Exception {
    Map vars = new HashedMap();
    vars.put("users", users);
    vars.put("groups", groups);
    vars.put("now", new Date());

    DefaultEscalatedDeadlineHandler notificationHandler = new DefaultEscalatedDeadlineHandler(getConf());
    WorkItemManager manager = new DefaultWorkItemManager(null);
    notificationHandler.setManager(manager);

    MockUserInfo userInfo = new MockUserInfo();
    userInfo.getEmails().put(users.get("tony"), "tony@domain.com");
    userInfo.getEmails().put(users.get("darth"), "darth@domain.com");

    userInfo.getLanguages().put(users.get("tony"), "en-UK");
    userInfo.getLanguages().put(users.get("darth"), "en-UK");
    notificationHandler.setUserInfo(userInfo);

    taskService.setEscalatedDeadlineHandler(notificationHandler);

    String string = toString(/*from  w  ww  . ja va 2 s.c o m*/
            new InputStreamReader(getClass().getResourceAsStream("../DeadlineWithNotification.mvel")));

    BlockingAddTaskResponseHandler addTaskResponseHandler = new BlockingAddTaskResponseHandler();
    Task task = (Task) eval(new StringReader(string), vars);
    client.addTask(task, null, addTaskResponseHandler);
    long taskId = addTaskResponseHandler.getTaskId();

    Content content = new Content();
    content.setContent("['subject' : 'My Subject', 'body' : 'My Body']".getBytes());
    BlockingSetContentResponseHandler setContentResponseHandler = new BlockingSetContentResponseHandler();
    client.setDocumentContent(taskId, content, setContentResponseHandler);
    long contentId = setContentResponseHandler.getContentId();
    BlockingGetContentResponseHandler getResponseHandler = new BlockingGetContentResponseHandler();
    client.getContent(contentId, getResponseHandler);
    content = getResponseHandler.getContent();
    assertEquals("['subject' : 'My Subject', 'body' : 'My Body']", new String(content.getContent()));

    // emails should not be set yet
    assertEquals(0, getWiser().getMessages().size());
    Thread.sleep(100);

    // nor yet
    assertEquals(0, getWiser().getMessages().size());

    long time = 0;
    while (getWiser().getMessages().size() != 2 && time < 15000) {
        Thread.sleep(500);
        time += 500;
    }

    // 1 email with two recipients should now exist
    assertEquals(2, getWiser().getMessages().size());

    List<String> list = new ArrayList<String>(2);
    list.add(getWiser().getMessages().get(0).getEnvelopeReceiver());
    list.add(getWiser().getMessages().get(1).getEnvelopeReceiver());

    assertTrue(list.contains("tony@domain.com"));
    assertTrue(list.contains("darth@domain.com"));

    MimeMessage msg = ((WiserMessage) getWiser().getMessages().get(0)).getMimeMessage();
    assertEquals("My Body", msg.getContent());
    assertEquals("My Subject", msg.getSubject());
    assertEquals("from@domain.com", ((InternetAddress) msg.getFrom()[0]).getAddress());
    assertEquals("replyTo@domain.com", ((InternetAddress) msg.getReplyTo()[0]).getAddress());
    assertEquals("tony@domain.com", ((InternetAddress) msg.getRecipients(RecipientType.TO)[0]).getAddress());
    assertEquals("darth@domain.com", ((InternetAddress) msg.getRecipients(RecipientType.TO)[1]).getAddress());
}

From source file:org.apache.james.transport.mailets.HeadersToHTTP.java

private HashSet<NameValuePair> getNameValuePairs(MimeMessage message)
        throws UnsupportedEncodingException, MessagingException {

    // to_address
    // from/*from  ww w  .  j  av  a 2s.com*/
    // reply to
    // subject

    HashSet<NameValuePair> pairs = new HashSet<NameValuePair>();

    if (message != null) {
        if (message.getSender() != null) {
            pairs.add(new BasicNameValuePair("from", message.getSender().toString()));
        }
        if (message.getReplyTo() != null) {
            pairs.add(new BasicNameValuePair("reply_to", Arrays.toString(message.getReplyTo())));
        }
        if (message.getMessageID() != null) {
            pairs.add(new BasicNameValuePair("message_id", message.getMessageID()));
        }
        if (message.getSubject() != null) {
            pairs.add(new BasicNameValuePair("subject", message.getSubject()));
        }
        pairs.add(new BasicNameValuePair("size", Integer.toString(message.getSize())));
    }

    pairs.add(new BasicNameValuePair(parameterKey, parameterValue));

    return pairs;
}

From source file:org.craftercms.commons.mail.impl.EmailFactoryImplTest.java

@Test
public void testGetEmailWithBodyParam() throws Exception {
    EmailImpl email = (EmailImpl) emailFactory.getEmail(FROM, TO, CC, BCC, REPLY_TO, SUBJECT, BODY, false);

    assertNotNull(email);/*from   w w w. j a  v  a  2s . c  om*/

    MimeMessage msg = email.message;

    assertArrayEquals(InternetAddress.parse(FROM), msg.getFrom());
    assertArrayEquals(InternetAddress.parse(StringUtils.join(TO)), msg.getRecipients(Message.RecipientType.TO));
    assertArrayEquals(InternetAddress.parse(StringUtils.join(CC)), msg.getRecipients(Message.RecipientType.CC));
    assertArrayEquals(InternetAddress.parse(StringUtils.join(BCC)),
            msg.getRecipients(Message.RecipientType.BCC));
    assertArrayEquals(InternetAddress.parse(REPLY_TO), msg.getReplyTo());
    assertEquals(SUBJECT, msg.getSubject());
    assertEquals(BODY, msg.getContent());
}

From source file:org.craftercms.commons.mail.impl.EmailFactoryImplTest.java

@Test
public void testGetEmailWithBodyTemplate() throws Exception {
    Map<String, Object> model = Collections.<String, Object>singletonMap("name", "John Doe");
    String body = processTemplate(TEMPLATE_NAME, model);

    EmailImpl email = (EmailImpl) emailFactory.getEmail(FROM, TO, CC, BCC, REPLY_TO, SUBJECT, TEMPLATE_NAME,
            model, false);//from   www.  jav a  2  s  .  c  o  m

    assertNotNull(email);

    MimeMessage msg = email.message;

    assertArrayEquals(InternetAddress.parse(FROM), msg.getFrom());
    assertArrayEquals(InternetAddress.parse(StringUtils.join(TO)), msg.getRecipients(Message.RecipientType.TO));
    assertArrayEquals(InternetAddress.parse(StringUtils.join(CC)), msg.getRecipients(Message.RecipientType.CC));
    assertArrayEquals(InternetAddress.parse(StringUtils.join(BCC)),
            msg.getRecipients(Message.RecipientType.BCC));
    assertArrayEquals(InternetAddress.parse(REPLY_TO), msg.getReplyTo());
    assertEquals(SUBJECT, msg.getSubject());
    assertEquals(body, msg.getContent());
}

From source file:com.riq.MailHandlerServlet.java

@Override
public void doGet(HttpServletRequest req, HttpServletResponse resp)

        throws IOException {

    log.info("Inside MailServlet doPost");

    // TODO get path information to determine target Department for this email

    PersistenceManager pm = PMF.get().getPersistenceManager();
    Properties props = new Properties();
    Session session = Session.getDefaultInstance(props, null);

    try {//from   ww w.  j  a va 2  s.co  m

        MimeMessage msg = new MimeMessage(session, req.getInputStream());
        Address sender = msg.getFrom()[0];
        Address replyTo = msg.getReplyTo()[0];

        //      DEBUG
        //       log.info("Message Class: " + msg.getClass());
        //       log.info("Message Stream: " + msg.getInputStream());
        //       log.info("Message RawStream: " + msg.getRawInputStream());
        //       log.info("Message Flags: " + msg.getFlags());
        //       log.info("Message Content: " + msg.getContent().toString());
        //       log.info("Message ContentID: " + msg.getContentID());
        //       log.info("Message ContentMD: " + msg.getContentMD5());
        //       log.info("Message ContentType: " + msg.getContentType());
        //       log.info("Message Description: " + msg.getDescription());
        //       log.info("Message Disposition: " + msg.getDisposition());
        //       log.info("Message Encoding: " + msg.getEncoding());
        //       log.info("Message Filename: " + msg.getFileName());
        //       log.info("Message Line Count: " + msg.getLineCount());
        //       log.info("Message ID: " + msg.getMessageID());
        //       log.info("Message Number: " + msg.getMessageNumber());
        //       log.info("Message Size: " + msg.getSize());
        //       log.info("Message Subject: " + msg.getSubject());
        //       log.info("Message RawInputStream: " + msg.getRawInputStream().toString());
        //       log.info("Message ReplyTo: " + replyTo);
        //       log.info("Message Sender: " + sender.toString());
        //       log.info("Request URL TO: " +  getServletContext());      

        String alertMsgString = getText(msg);

        alertMsgString = alertMsgString.replaceAll("Begin forwarded message:", "");
        alertMsgString = alertMsgString.replaceAll("Forwarded message", "");
        alertMsgString = alertMsgString.replaceAll("Dispatch@co.morris.nj.us", "");
        alertMsgString = alertMsgString.replaceAll("Date:", "");
        alertMsgString = alertMsgString.replaceAll(">", "");
        alertMsgString = alertMsgString.replaceAll("::", "-");
        alertMsgString = alertMsgString.replaceAll("< ", "");
        alertMsgString = alertMsgString.replaceAll("----------", "");
        alertMsgString = alertMsgString.replaceAll("Subject:", "");
        alertMsgString = alertMsgString.replaceAll("To:", "");
        alertMsgString = alertMsgString.replaceAll("From:", "");

        //  Added to grab gmail confirmations
        //  alertMsgString = alertMsgString.substring(50, 300);

        try {

            String queryDept = "select from " + Department.class.getName() +
            // TODO: johnreilly workaround for getting allRecipients... 
            // " where dispatchId == '" + toAddressDigitsOnly + "' " + 
                    " where dispatchId == '2599' " + " && fromEmail == '" + sender + "' ";
            log.info("queryDept: " + queryDept);
            List<Department> depts = (List<Department>) pm.newQuery(queryDept).execute();

            if (depts.size() != 0) {

                for (Department d : depts) {

                    // need to filter further e.g. last two hours
                    String queryAlert = "select from " + Alert.class.getName() + " where deptId == "
                            + depts.get(0).getid() + " && messageId == '" + msg.getMessageID() + "' ";
                    log.info("queryAlert: " + queryAlert);
                    List<Alert> alerts = (List<Alert>) pm.newQuery(queryAlert).execute();
                    log.info("queryAlert Result Qty: " + alerts.size());

                    if (alerts.size() == 0) {

                        riqGeocode(alertMsgString);

                        // geocode the address from the Alert
                        Map<String, String> geoResults = riqGeocode(alertMsgString);
                        log.info("lat print: " + geoResults.get("lat"));
                        log.info("lng print: " + geoResults.get("lng"));

                        // create the alert
                        Long deptId = depts.get(0).getid();
                        Long timeStamp = System.currentTimeMillis();
                        Alert a = new Alert(deptId, timeStamp, alertMsgString.trim(), sender.toString(),
                                "Active", "", geoResults.get("lat"), geoResults.get("lng"), msg.getMessageID());
                        pm.makePersistent(a);

                        // query to get id of this alert
                        String queryThisAlert = "select from " + Alert.class.getName() + " where deptId == "
                                + deptId + " " + " && timeStamp == " + timeStamp;
                        log.info("queryThisAlert: " + queryThisAlert);
                        List<Alert> thisAlert = (List<Alert>) pm.newQuery(queryThisAlert).execute();
                        log.info("queryCurrentAlert Result Qty: " + thisAlert.size());

                        // create Tracking records for "special" Locations
                        String querySpecialLocs = "select from " + Location.class.getName()
                                + " where special == 'yes' && deptId == " + deptId;
                        log.info("querySpecialLocs: " + querySpecialLocs);
                        List<Location> specialLocs = (List<Location>) pm.newQuery(querySpecialLocs).execute();
                        log.info("querySpecialLocs qty: " + specialLocs.size());

                        for (Location specL : specialLocs) {
                            Tracking tSL = new Tracking(deptId, thisAlert.get(0).getid(), specL.getid(),
                                    System.currentTimeMillis(), null, // TODO: johnreilly authorId tbd
                                    "location", specL.getid(), null, "autoAddLocation");
                            pm.makePersistent(tSL);
                        }

                        // search Dept for Location where distant Members presumed not to be responding are set
                        String queryFarawayLocs = "select from " + Location.class.getName()
                                + " where vru == '2' && deptId == " + deptId;
                        log.info("querySpecialLocs: " + queryFarawayLocs);
                        List<Location> farawayLoc = (List<Location>) pm.newQuery(queryFarawayLocs).execute();
                        log.info("queryFarawayLocs qty: " + farawayLoc.size());

                        // create Tracking records for Members presumed not to be responder due to fresh ETA
                        String queryFarAwayResponders = "select from " + Member.class.getName()
                                + " where distGroup == '4' ";
                        log.info("queryFarAwayResponders: " + queryFarAwayResponders);
                        List<Member> farawayMembers = (List<Member>) pm.newQuery(queryFarAwayResponders)
                                .execute();
                        log.info("queryFarAwayResponders qty: " + farawayMembers.size());

                        if (farawayMembers.size() != 0) {
                            for (Member far : farawayMembers) {
                                Tracking tMFAR = new Tracking(deptId, thisAlert.get(0).getid(),
                                        farawayLoc.get(0).getid(), System.currentTimeMillis(), null, // TODO: johnreilly authorId tbd
                                        "farawayAddMember", far.getid(), null, responseType);
                                pm.makePersistent(tMFAR);
                            }
                        }

                        // TODO: testing restriction HACKER - remove at launch
                        // send alert email
                        String queryMember = "select from " + Member.class.getName() + " where deptId == "
                                + deptId + " && type == 'Hacker' ";
                        List<Member> members = (List<Member>) pm.newQuery(queryMember).execute();

                        //TODO Geocode address to insure easy navigation
                        //TODO johnreilly: add street and town fields to Alert
                        msg.setFrom(
                                new InternetAddress("admin@responderiq05.appspotmail.com", "FirstResponder"));
                        msg.setSubject("Alert!");
                        msg.setText(" Y=" + d.getinboundVRU1() + "&N=" + d.getinboundVRU2() +
                        // "&3=" + d.getinboundVRU3() +  
                                "&A=" + thisAlert.get(0).getalertMsgString());

                        // send message to all dept members who permit tracking (and sending email alerts)
                        for (Member m : members) {
                            msg.addRecipient(Message.RecipientType.TO, new InternetAddress(m.getsmsAddress(),
                                    m.getfirstName() + "" + m.getlastName()));
                            log.info("Member: " + m.getsmsAddress() + "|" + m.getlastName());
                        }
                    }
                    // only process for one department - should only be one department
                    break;
                }
            }
        } catch (MessagingException me) {
            log.info("Error: Messaging");
        } catch (IndexOutOfBoundsException mi) {
            log.info("Error: Out of Bounds");
        }

        // Do not send alert notification if email is a Google Confirmation
        //      if (! sender.toString().contains("mail-noreply@google.com")) {
        //        Transport.send(msg);
        //      }

    } catch (MessagingException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();

    } finally {
        pm.close();
    }

}