Example usage for javax.mail.internet MimeMessage getRecipients

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

Introduction

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

Prototype

@Override
public Address[] getRecipients(Message.RecipientType type) throws MessagingException 

Source Link

Document

Returns the recepients specified by the type.

Usage

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

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

    String str = "(with (new Task()) { priority = 55, taskData = (with( new TaskData()) { createdOn = now, createdBy = users['tony'], activationTime = now}), ";
    str += "peopleAssignments = (with ( new PeopleAssignments() ) {potentialOwners = [users['steve' ], users['tony' ]]}), ";
    str += "names = [ new I18NText( 'en-UK', 'This is my task name')],";
    str += "subjects = [ new I18NText( 'en-UK', 'This is my task subject')],";
    str += "descriptions = [ new I18NText( 'en-UK', 'This is my task description')],";
    str += "deadlines = (with (new Deadlines() ) {";
    str += "    startDeadlines = [ ";
    str += "       (with (new Deadline()) {";
    str += "           date = now";
    str += "       } ) ],";
    str += "    endDeadlines = [";
    str += "        (with (new Deadline()) {";
    str += "             date = new Date( now.time + ( 1000 * 60 * 60 * 24 ) )"; // set to tomorrow
    str += "        } ) ]";
    str += "} ) })";

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

    userInfo.getLanguages().put(users.get("tony"), "en-UK");
    userInfo.getLanguages().put(users.get("steve"), "en-UK");
    taskService.setUserinfo(userInfo);/* w  w w  .j a  v  a  2s  .  c om*/

    BlockingAddTaskResponseHandler addTaskResponseHandler = new BlockingAddTaskResponseHandler();
    Task task = (Task) eval(new StringReader(str), vars);
    client.addTask(task, null, addTaskResponseHandler);

    long taskId = addTaskResponseHandler.getTaskId();

    BlockingTaskOperationResponseHandler responseHandler = new BlockingTaskOperationResponseHandler();
    client.claim(taskId, users.get("steve").getId(), responseHandler);
    responseHandler.waitTillDone(5000);

    assertEquals(2, getWiser().getMessages().size());

    assertEquals("steve@domain.com", getWiser().getMessages().get(0).getEnvelopeReceiver());
    assertEquals("steve@domain.com", getWiser().getMessages().get(1).getEnvelopeReceiver());

    String subject = "Summary\n-------\n\nThis is my task subject\n\n";
    String description = "Description\n-----------\n\nThis is my task description";

    MimeMessage msg = ((WiserMessage) getWiser().getMessages().get(0)).getMimeMessage();
    assertEqualsIgnoreWhitespace("multipart/alternative;boundary=\"----=_Part_", msg.getContentType(), 0, 47);
    assertEquals("tony@domain.com", ((InternetAddress) msg.getFrom()[0]).getAddress());
    assertEquals("tony@domain.com", ((InternetAddress) msg.getReplyTo()[0]).getAddress());
    assertEquals("steve@domain.com", ((InternetAddress) msg.getRecipients(RecipientType.TO)[0]).getAddress());
    assertEquals("Task Assignment Start Event: This is my task name", msg.getSubject());

    MimeMultipart multiPart = (MimeMultipart) msg.getContent();

    BodyPart messageBodyPart = multiPart.getBodyPart(0);
    assertEquals("text/plain; charset=UTF8;", messageBodyPart.getDataHandler().getContentType());
    String content = new String(getBytes(messageBodyPart.getDataHandler().getInputStream()));
    assertEqualsIgnoreWhitespace(subject + description, content);

    messageBodyPart = multiPart.getBodyPart(1);
    assertEquals("text/calendar; charset=UTF8; name=ical-Start-1.ics",
            messageBodyPart.getDataHandler().getContentType());
    content = new String(getBytes(messageBodyPart.getDataHandler().getInputStream()));
    assertEqualsIgnoreWhitespace(
            "BEGIN:VCALENDARPRODID:-//iCal4j 1.0//ENCALSCALE:GREGORIANVERSION:2.0METHOD:REQUESTBEGIN:VEVENTDTSTART;TZID=UTC:",
            content.substring(0, 123));
    assertEqualsIgnoreWhitespace(
            "SUMMARY:\"Task Start : This is my task subject\"DESCRIPTION:\"This is my task description\"PRIORITY:55END:VEVENTEND:VCALENDAR",
            content.substring(content.length() - 131, content.length()));

    msg = ((WiserMessage) getWiser().getMessages().get(1)).getMimeMessage();
    assertEqualsIgnoreWhitespace("multipart/alternative;boundary=\"----=_Part_", msg.getContentType(), 0, 47);
    assertEquals("tony@domain.com", ((InternetAddress) msg.getFrom()[0]).getAddress());
    assertEquals("tony@domain.com", ((InternetAddress) msg.getReplyTo()[0]).getAddress());
    assertEquals("steve@domain.com", ((InternetAddress) msg.getRecipients(RecipientType.TO)[0]).getAddress());
    assertEquals("Task Assignment End Event: This is my task name", msg.getSubject());

    multiPart = (MimeMultipart) msg.getContent();

    messageBodyPart = multiPart.getBodyPart(0);
    assertEquals("text/plain; charset=UTF8;", messageBodyPart.getDataHandler().getContentType());
    content = new String(getBytes(messageBodyPart.getDataHandler().getInputStream()));
    assertEqualsIgnoreWhitespace(subject + description, content);

    messageBodyPart = multiPart.getBodyPart(1);
    assertEquals("text/calendar; charset=UTF8; name=ical-End-1.ics",
            messageBodyPart.getDataHandler().getContentType());
    content = new String(getBytes(messageBodyPart.getDataHandler().getInputStream()));
    assertEqualsIgnoreWhitespace(
            "BEGIN:VCALENDARPRODID:-//iCal4j 1.0//ENCALSCALE:GREGORIANVERSION:2.0METHOD:REQUESTBEGIN:VEVENTDTSTART;TZID=UTC:",
            content.substring(0, 123));
    assertEqualsIgnoreWhitespace(
            "SUMMARY:\"Task End : This is my task subject\"DESCRIPTION:\"This is my task description\"PRIORITY:55END:VEVENTEND:VCALENDAR",
            content.substring(content.length() - 131, content.length()));
}

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

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

    String str = "(with (new Task()) { priority = 55, taskData = (with( new TaskData()) { createdOn = now, createdBy = users['tony'], activationTime = now}), ";
    str += "peopleAssignments = (with ( new PeopleAssignments() ) {potentialOwners = [users['steve' ], users['tony' ]]}), ";
    str += "names = [ new I18NText( 'en-UK', 'This is my task name')],";
    str += "subjects = [ new I18NText( 'en-UK', 'This is my task subject')],";
    str += "descriptions = [ new I18NText( 'en-UK', 'This is my task description')],";
    str += "deadlines = (with (new Deadlines() ) {";
    str += "    startDeadlines = [ ";
    str += "       (with (new Deadline()) {";
    str += "           date = now";
    str += "       } ) ]";
    str += "} ) })";

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

    userInfo.getLanguages().put(users.get("tony"), "en-UK");
    userInfo.getLanguages().put(users.get("steve"), "en-UK");
    taskService.setUserinfo(userInfo);//  w ww .  ja va 2s.co  m

    BlockingAddTaskResponseHandler addTaskResponseHandler = new BlockingAddTaskResponseHandler();
    Task task = (Task) eval(new StringReader(str), vars);
    client.addTask(task, null, addTaskResponseHandler);

    long taskId = addTaskResponseHandler.getTaskId();

    BlockingTaskOperationResponseHandler responseHandler = new BlockingTaskOperationResponseHandler();
    client.claim(taskId, users.get("steve").getId(), responseHandler);
    responseHandler.waitTillDone(5000);

    assertEquals(1, getWiser().getMessages().size());

    assertEquals("steve@domain.com", getWiser().getMessages().get(0).getEnvelopeReceiver());

    String subject = "Summary\n-------\n\nThis is my task subject\n\n";
    String description = "Description\n-----------\n\nThis is my task description";

    MimeMessage msg = ((WiserMessage) getWiser().getMessages().get(0)).getMimeMessage();
    assertEqualsIgnoreWhitespace("multipart/alternative;boundary=\"----=_Part_", msg.getContentType(), 0, 47);
    assertEquals("tony@domain.com", ((InternetAddress) msg.getFrom()[0]).getAddress());
    assertEquals("tony@domain.com", ((InternetAddress) msg.getReplyTo()[0]).getAddress());
    assertEquals("steve@domain.com", ((InternetAddress) msg.getRecipients(RecipientType.TO)[0]).getAddress());
    assertEquals("Task Assignment Start Event: This is my task name", msg.getSubject());

    MimeMultipart multiPart = (MimeMultipart) msg.getContent();

    BodyPart messageBodyPart = multiPart.getBodyPart(0);
    assertEquals("text/plain; charset=UTF8;", messageBodyPart.getDataHandler().getContentType());
    String content = new String(getBytes(messageBodyPart.getDataHandler().getInputStream()));
    assertEqualsIgnoreWhitespace(subject + description, content);

    messageBodyPart = multiPart.getBodyPart(1);
    assertEquals("text/calendar; charset=UTF8; name=ical-Start-1.ics",
            messageBodyPart.getDataHandler().getContentType());
    content = new String(getBytes(messageBodyPart.getDataHandler().getInputStream()));
    assertEqualsIgnoreWhitespace(
            "BEGIN:VCALENDARPRODID:-//iCal4j 1.0//ENCALSCALE:GREGORIANVERSION:2.0METHOD:REQUESTBEGIN:VEVENTDTSTART;TZID=UTC:",
            content.substring(0, 123));
    assertEqualsIgnoreWhitespace(
            "SUMMARY:\"Task Start : This is my task subject\"DESCRIPTION:\"This is my task description\"PRIORITY:55END:VEVENTEND:VCALENDAR",
            content.substring(content.length() - 131, content.length()));
}

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

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

    String str = "(with (new Task()) { priority = 55, taskData = (with( new TaskData()) { createdOn = now, createdBy = users['tony'], activationTime = now}), ";
    str += "peopleAssignments = (with ( new PeopleAssignments() ) {potentialOwners = [users['steve' ], users['tony' ]]}), ";
    str += "names = [ new I18NText( 'en-UK', 'This is my task name')],";
    str += "subjects = [ new I18NText( 'en-UK', 'This is my task subject')],";
    str += "descriptions = [ new I18NText( 'en-UK', 'This is my task description')],";
    str += "deadlines = (with (new Deadlines() ) {";
    str += "    endDeadlines = [";
    str += "        (with (new Deadline()) {";
    str += "             date = new Date( now.time + ( 1000 * 60 * 60 * 24 ) )"; // set to tomorrow
    str += "        } ) ]";
    str += "} ) })";

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

    userInfo.getLanguages().put(users.get("tony"), "en-UK");
    userInfo.getLanguages().put(users.get("steve"), "en-UK");
    taskService.setUserinfo(userInfo);//from   w  w  w  .  j a  v  a2s.com

    BlockingAddTaskResponseHandler addTaskResponseHandler = new BlockingAddTaskResponseHandler();
    Task task = (Task) eval(new StringReader(str), vars);
    client.addTask(task, null, addTaskResponseHandler);

    long taskId = addTaskResponseHandler.getTaskId();

    BlockingTaskOperationResponseHandler responseHandler = new BlockingTaskOperationResponseHandler();
    client.claim(taskId, users.get("steve").getId(), responseHandler);

    responseHandler.waitTillDone(5000);

    assertEquals(1, getWiser().getMessages().size());

    assertEquals("steve@domain.com", getWiser().getMessages().get(0).getEnvelopeReceiver());

    String subject = "Summary\n-------\n\nThis is my task subject\n\n";
    String description = "Description\n-----------\n\nThis is my task description";

    MimeMessage msg = ((WiserMessage) getWiser().getMessages().get(0)).getMimeMessage();
    assertEqualsIgnoreWhitespace("multipart/alternative;boundary=\"----=_Part_", msg.getContentType(), 0, 47);
    assertEquals("tony@domain.com", ((InternetAddress) msg.getFrom()[0]).getAddress());
    assertEquals("tony@domain.com", ((InternetAddress) msg.getReplyTo()[0]).getAddress());
    assertEquals("steve@domain.com", ((InternetAddress) msg.getRecipients(RecipientType.TO)[0]).getAddress());
    assertEquals("Task Assignment End Event: This is my task name", msg.getSubject());

    MimeMultipart multiPart = (MimeMultipart) msg.getContent();

    BodyPart messageBodyPart = multiPart.getBodyPart(0);
    assertEquals("text/plain; charset=UTF8;", messageBodyPart.getDataHandler().getContentType());
    String content = new String(getBytes(messageBodyPart.getDataHandler().getInputStream()));
    assertEqualsIgnoreWhitespace(subject + description, content);

    messageBodyPart = multiPart.getBodyPart(1);
    assertEquals("text/calendar; charset=UTF8; name=ical-End-1.ics",
            messageBodyPart.getDataHandler().getContentType());
    content = new String(getBytes(messageBodyPart.getDataHandler().getInputStream()));
    assertEqualsIgnoreWhitespace(
            "BEGIN:VCALENDARPRODID:-//iCal4j 1.0//ENCALSCALE:GREGORIANVERSION:2.0METHOD:REQUESTBEGIN:VEVENTDTSTART;TZID=UTC:",
            content.substring(0, 123));
    assertEqualsIgnoreWhitespace(
            "SUMMARY:\"Task End : This is my task subject\"DESCRIPTION:\"This is my task description\"PRIORITY:55END:VEVENTEND:VCALENDAR",
            content.substring(content.length() - 131, content.length()));
}

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(//  ww w  .j av  a  2s .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.elasticsearch.river.email.EmailToJson.java

public static String getReceiveAddress(MimeMessage msg, Message.RecipientType type) throws MessagingException {
    StringBuilder receiveAddress = new StringBuilder();
    Address[] addresss = null;//from   w  w  w . j  av a 2  s  . co m
    if (type == null) {
        addresss = msg.getAllRecipients();
    } else {
        addresss = msg.getRecipients(type);
    }

    if (addresss == null || addresss.length < 1)
        return "";
    // throw new MessagingException("!");
    for (Address address : addresss) {
        InternetAddress internetAddress = (InternetAddress) address;
        receiveAddress.append(internetAddress.toUnicodeString()).append(",");
    }

    receiveAddress.deleteCharAt(receiveAddress.length() - 1); //??

    return receiveAddress.toString();
}

From source file:org.exjello.mail.Exchange2003Connection.java

public void send(MimeMessage message) throws Exception {
    Address[] bccRecipients = message.getRecipients(Message.RecipientType.BCC);
    if (bccRecipients == null || bccRecipients.length == 0) {
        bccRecipients = null;/*from w  w w .  j  a  v  a2  s .c o m*/
    }
    message.setRecipients(Message.RecipientType.BCC, (Address[]) null);
    synchronized (this) {
        if (!isConnected()) {
            throw new IllegalStateException("Not connected.");
        }
        if (!canSend()) {
            throw new IllegalStateException("Unable to access outbox.");
        }
        HttpClient client = getClient();
        String path = drafts;
        if (!path.endsWith("/"))
            path += "/";
        String messageName = generateMessageName();
        path += escape(messageName + ".eml");
        PutMethod op = new PutMethod(path);
        op.setRequestHeader("Content-Type", MESSAGE_CONTENT_TYPE);
        op.setRequestEntity(createMessageEntity(message));
        InputStream stream = null;
        try {
            int status = client.executeMethod(op);
            stream = op.getResponseBodyAsStream();
            if (status >= 300) {
                throw new IllegalStateException("Unable to post message to draft folder.");
            }
        } finally {
            try {
                if (stream != null) {
                    byte[] buf = new byte[65536];
                    try {
                        if (session.getDebug()) {
                            PrintStream log = session.getDebugOut();
                            log.println("Response Body:");
                            int count;
                            while ((count = stream.read(buf, 0, 65536)) != -1) {
                                log.write(buf, 0, count);
                            }
                            log.flush();
                            log.println();
                        } else {
                            while (stream.read(buf, 0, 65536) != -1)
                                ;
                        }
                    } catch (Exception ignore) {
                    } finally {
                        try {
                            stream.close();
                        } catch (Exception ignore2) {
                        }
                    }
                }
            } finally {
                op.releaseConnection();
            }
        }
        if (bccRecipients != null) {
            ExchangeMethod patch = new ExchangeMethod(PROPPATCH_METHOD, path);
            patch.setHeader("Content-Type", XML_CONTENT_TYPE);
            patch.addHeader("Depth", "0");
            patch.addHeader("Translate", "f");
            patch.addHeader("Brief", "t");
            patch.setRequestEntity(createAddBccEntity(bccRecipients));
            stream = null;
            try {
                int status = client.executeMethod(patch);
                stream = patch.getResponseBodyAsStream();
                if (status >= 300) {
                    throw new IllegalStateException("Unable to add BCC recipients. Status: " + status);
                }
            } finally {
                try {
                    if (stream != null) {
                        byte[] buf = new byte[65536];
                        try {
                            if (session.getDebug()) {
                                PrintStream log = session.getDebugOut();
                                log.println("Response Body:");
                                int count;
                                while ((count = stream.read(buf, 0, 65536)) != -1) {
                                    log.write(buf, 0, count);
                                }
                                log.flush();
                                log.println();
                            } else {
                                while (stream.read(buf, 0, 65536) != -1)
                                    ;
                            }
                        } catch (Exception ignore) {
                        } finally {
                            try {
                                stream.close();
                            } catch (Exception ignore2) {
                            }
                        }
                    }
                } finally {
                    patch.releaseConnection();
                }
            }
        }
        ExchangeMethod move = new ExchangeMethod(MOVE_METHOD, path);
        String destination = submissionUri;
        if (!destination.endsWith("/"))
            destination += "/";
        move.setHeader("Destination", destination);
        stream = null;
        try {
            int status = client.executeMethod(move);
            stream = move.getResponseBodyAsStream();
            if (status >= 300) {
                throw new IllegalStateException("Unable to move message to outbox: Status " + status);
            }
        } finally {
            try {
                if (stream != null) {
                    byte[] buf = new byte[65536];
                    try {
                        if (session.getDebug()) {
                            PrintStream log = session.getDebugOut();
                            log.println("Response Body:");
                            int count;
                            while ((count = stream.read(buf, 0, 65536)) != -1) {
                                log.write(buf, 0, count);
                            }
                            log.flush();
                            log.println();
                        } else {
                            while (stream.read(buf, 0, 65536) != -1)
                                ;
                        }
                    } catch (Exception ignore) {
                    } finally {
                        try {
                            stream.close();
                        } catch (Exception ignore2) {
                        }
                    }
                }
            } finally {
                move.releaseConnection();
            }
        }
        if (session.getDebug()) {
            session.getDebugOut().println("Sent successfully.");
        }
    }
}

From source file:org.nuxeo.ecm.core.convert.plugins.text.extractors.RFC822ToTextConverter.java

protected Blob extractTextFromMessage(Blob blob) {
    if (blob == null) {
        return null;
    }/* w ww. j  av a2 s. co m*/
    File f = null;
    OutputStream fo = null;
    try {
        MimeMessage msg = new MimeMessage((Session) null, blob.getStream());
        f = File.createTempFile("rfc822totext", ".txt");
        fo = new FileOutputStream(f);
        List<Part> parts = getAttachmentParts(msg);
        writeInfo(fo, msg.getSubject());
        writeInfo(fo, msg.getFrom());
        writeInfo(fo, msg.getRecipients(RecipientType.TO));
        writeInfo(fo, msg.getRecipients(RecipientType.CC));
        for (Part part : parts) {
            writeInfo(fo, part.getFileName());
            writeInfo(fo, part.getDescription());
            byte[] extracted = extractTextFromMessagePart(part);
            if (extracted != null) {
                writeInfo(fo, extracted);
            }
        }
        Blob outblob = new FileBlob(new FileInputStream(f));
        outblob.setMimeType(descriptor.getDestinationMimeType());
        return outblob;
    } catch (Exception e) {
        log.error(e);
    } finally {
        if (fo != null) {
            try {
                fo.close();
            } catch (IOException e) {
                log.error(e);
            }
        }
        if (f != null) {
            f.delete();
        }
    }
    return null;
}

From source file:org.restcomm.connect.email.EmailService.java

EmailResponse sendEmailSsL(final Mail mail) {
    try {//from   w w w. j  a v a2s  . c o  m
        InternetAddress from;
        if (mail.from() != null || !mail.from().equalsIgnoreCase("")) {
            from = new InternetAddress(mail.from());
        } else {
            from = new InternetAddress(user);
        }
        final InternetAddress to = new InternetAddress(mail.to());
        final MimeMessage email = new MimeMessage(session);
        email.setFrom(from);
        email.addRecipient(Message.RecipientType.TO, to);
        email.setSubject(mail.subject());
        email.setText(mail.body());
        email.addRecipients(Message.RecipientType.CC, InternetAddress.parse(mail.cc(), false));
        email.addRecipients(Message.RecipientType.BCC, InternetAddress.parse(mail.bcc(), false));
        //Transport.send(email);
        transport.connect(host, Integer.parseInt(port), user, password);
        transport.sendMessage(email, email.getRecipients(Message.RecipientType.TO));
        return new EmailResponse(mail);
    } catch (final MessagingException exception) {
        logger.error(exception.getMessage(), exception);
        return new EmailResponse(exception, exception.getMessage());
    }
}

From source file:org.silverpeas.core.mail.SmtpMailSendingTest.java

private void assertMailSent(MailToSend verifiedMailToSend, GreenMailOperations mail) throws Exception {
    assertThat("assertMailSent is compatible with one receiver only...", verifiedMailToSend.getTo(),
            hasSize(1));//  ww w .  jav  a  2  s  .c  om

    assertThat(verifiedMailToSend.getTo().getRecipientType().getTechnicalType(), is(Message.RecipientType.TO));

    MimeMessage[] messages = mail.getReceivedMessages();
    assertThat(messages, arrayWithSize(1));

    MimeMessage sentMessage = messages[0];
    MailAddress originalReceiverMailAddress = verifiedMailToSend.getTo().iterator().next();

    assertThat(sentMessage.getFrom().length, is(1));
    assertThat(sentMessage.getFrom()[0], instanceOf(InternetAddress.class));
    InternetAddress internetAddressFrom = (InternetAddress) sentMessage.getFrom()[0];
    assertThat(internetAddressFrom.getAddress(), is(verifiedMailToSend.getFrom().getEmail()));
    assertThat(internetAddressFrom.getPersonal(),
            is(StringUtil.defaultStringIfNotDefined(verifiedMailToSend.getFrom().getName(), null)));

    assertThat(sentMessage.getRecipients(Message.RecipientType.TO).length, is(1));
    assertThat(sentMessage.getRecipients(Message.RecipientType.CC), nullValue());
    assertThat(sentMessage.getRecipients(Message.RecipientType.BCC), nullValue());
    assertThat(sentMessage.getRecipients(Message.RecipientType.TO)[0], instanceOf(InternetAddress.class));
    InternetAddress internetAddressTo = (InternetAddress) sentMessage
            .getRecipients(Message.RecipientType.TO)[0];
    assertThat(internetAddressTo.getAddress(), is(originalReceiverMailAddress.getEmail()));
    assertThat(internetAddressTo.getPersonal(), nullValue());

    assertThat(sentMessage.getSubject(), is(verifiedMailToSend.getSubject()));
    if (verifiedMailToSend.getContent().getValue() instanceof Multipart) {
        assertThat(sentMessage.getContent(), instanceOf(verifiedMailToSend.getContent().getValue().getClass()));
    } else {
        assertThat(sentMessage.getContent().toString().replaceAll("[\n\r]*$", ""),
                is(verifiedMailToSend.getContent().getValue()));
    }

    assertThat(DateUtils.addSeconds(sentMessage.getSentDate(), 10), greaterThanOrEqualTo(new Date()));

    assertThat(sentMessage.getReplyTo().length, is(1));
    if (verifiedMailToSend.isReplyToRequired()) {
        assertThat(sentMessage.getHeader("Reply-To"), notNullValue());
        assertThat(sentMessage.getReplyTo()[0], instanceOf(InternetAddress.class));
        InternetAddress internetAddressReplyTo = (InternetAddress) sentMessage.getReplyTo()[0];
        assertThat(internetAddressReplyTo.getAddress(), is(verifiedMailToSend.getFrom().getEmail()));
        assertThat(internetAddressReplyTo.getPersonal(),
                is(StringUtil.defaultStringIfNotDefined(verifiedMailToSend.getFrom().getName(), null)));
    } else {
        assertThat(sentMessage.getHeader("Reply-To"), nullValue());
        assertThat(sentMessage.getReplyTo()[0].toString(), is(internetAddressFrom.toString()));
    }
}

From source file:org.silverpeas.core.mail.TestSmtpMailSending.java

private void assertMailSent(MailToSend verifiedMailToSend) throws Exception {
    assertThat("assertMailSent is compatible with one receiver only...", verifiedMailToSend.getTo(),
            hasSize(1));//from  ww  w  . j  ava  2s  .  c o m

    assertThat(verifiedMailToSend.getTo().getRecipientType().getTechnicalType(), is(Message.RecipientType.TO));

    MimeMessage[] messages = greenMailRule.getReceivedMessages();
    assertThat(messages, arrayWithSize(1));

    MimeMessage sentMessage = messages[0];
    MailAddress originalReceiverMailAddress = verifiedMailToSend.getTo().iterator().next();

    assertThat(sentMessage.getFrom().length, is(1));
    assertThat(sentMessage.getFrom()[0], instanceOf(InternetAddress.class));
    InternetAddress internetAddressFrom = (InternetAddress) sentMessage.getFrom()[0];
    assertThat(internetAddressFrom.getAddress(), is(verifiedMailToSend.getFrom().getEmail()));
    assertThat(internetAddressFrom.getPersonal(),
            is(StringUtil.defaultStringIfNotDefined(verifiedMailToSend.getFrom().getName(), null)));

    assertThat(sentMessage.getRecipients(Message.RecipientType.TO).length, is(1));
    assertThat(sentMessage.getRecipients(Message.RecipientType.CC), nullValue());
    assertThat(sentMessage.getRecipients(Message.RecipientType.BCC), nullValue());
    assertThat(sentMessage.getRecipients(Message.RecipientType.TO)[0], instanceOf(InternetAddress.class));
    InternetAddress internetAddressTo = (InternetAddress) sentMessage
            .getRecipients(Message.RecipientType.TO)[0];
    assertThat(internetAddressTo.getAddress(), is(originalReceiverMailAddress.getEmail()));
    assertThat(internetAddressTo.getPersonal(), nullValue());

    assertThat(sentMessage.getSubject(), is(verifiedMailToSend.getSubject()));
    if (verifiedMailToSend.getContent().getValue() instanceof Multipart) {
        assertThat(sentMessage.getContent(), instanceOf(verifiedMailToSend.getContent().getValue().getClass()));
    } else {
        assertThat(sentMessage.getContent().toString().replaceAll("[\n\r]*$", ""),
                is(verifiedMailToSend.getContent().getValue()));
    }

    assertThat(DateUtils.addSeconds(sentMessage.getSentDate(), 10), greaterThanOrEqualTo(new Date()));

    assertThat(sentMessage.getReplyTo().length, is(1));
    if (verifiedMailToSend.isReplyToRequired()) {
        assertThat(sentMessage.getHeader("Reply-To"), notNullValue());
        assertThat(sentMessage.getReplyTo()[0], instanceOf(InternetAddress.class));
        InternetAddress internetAddressReplyTo = (InternetAddress) sentMessage.getReplyTo()[0];
        assertThat(internetAddressReplyTo.getAddress(), is(verifiedMailToSend.getFrom().getEmail()));
        assertThat(internetAddressReplyTo.getPersonal(),
                is(StringUtil.defaultStringIfNotDefined(verifiedMailToSend.getFrom().getName(), null)));
    } else {
        assertThat(sentMessage.getHeader("Reply-To"), nullValue());
        assertThat(sentMessage.getReplyTo()[0].toString(), is(internetAddressFrom.toString()));
    }
}