Example usage for javax.mail.internet MimeMessage getFrom

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

Introduction

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

Prototype

@Override
public Address[] getFrom() throws MessagingException 

Source Link

Document

Returns the value of the RFC 822 "From" header fields.

Usage

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);//from www .  j  av a2  s  . c  o 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  va  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(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.xsocket.connection.SimpleSmtpClient.java

public void send(MimeMessage message) throws IOException, MessagingException {

    IBlockingConnection con = new BlockingConnection(host, port);

    // read greeting
    readResponse(con);//from w w w .  ja v a2 s . c o  m

    sendCmd(con, "Helo mailserver");
    readResponse(con);

    if (username != null) {
        String userPassword = new String(
                Base64.encodeBase64(new String("\000" + username + "\000" + password).getBytes()));
        sendCmd(con, "AUTH PLAIN " + userPassword);
        readResponse(con);
    }

    Address sender = message.getFrom()[0];
    sendCmd(con, "Mail From: " + sender.toString());
    readResponse(con);

    Address[] tos = message.getRecipients(RecipientType.TO);
    for (Address to : tos) {
        sendCmd(con, "Rcpt To: " + to.toString());
        readResponse(con);
    }

    sendCmd(con, "Data");
    readResponse(con);

    ByteArrayOutputStream os = new ByteArrayOutputStream();
    message.writeTo(os);
    os.close();

    String s = new String(os.toByteArray());
    con.write(s);
    con.write("\r\n.\r\n");

    sendCmd(con, "Quit");
    readResponse(con);

    con.close();
}

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);//from w w  w  . ja  va  2  s. 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(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:mitm.common.tools.SendMail.java

private void sendMultiThreaded(final MailTransport mailSender, final MimeMessage message,
        final Address[] recipients) throws InterruptedException {
    ExecutorService threadPool = Executors.newCachedThreadPool();

    final Semaphore semaphore = new Semaphore(threads, true);

    final long startTime = System.currentTimeMillis();

    for (int i = 1; i <= count; i++) {
        long threadStart = System.currentTimeMillis();

        semaphore.acquireUninterruptibly();

        threadPool.execute(new Runnable() {
            @Override// www . j a v a 2  s. c o  m
            public void run() {
                try {
                    MimeMessage clone = MailUtils.cloneMessage(message);

                    int sent = sentCount.incrementAndGet();

                    if (uniqueFrom) {
                        Address[] froms = clone.getFrom();

                        if (froms != null && froms.length > 0) {
                            clone.setFrom(
                                    new InternetAddress(sent + EmailAddressUtils.getEmailAddress(froms[0])));
                        }
                    }

                    mailSender.sendMessage(clone, recipients);

                    long timePassed = DateTimeUtils
                            .millisecondsToSeconds(System.currentTimeMillis() - startTime);

                    StrBuilder sb = new StrBuilder();

                    sb.append("Message\t" + sent + "\tsent.");

                    if (timePassed > 0) {
                        float msgPerSec = (float) sent / timePassed;

                        sb.append("\tmessages/second\t" + String.format("%.2f", msgPerSec));
                    }

                    logger.info(sb.toString());
                } catch (MessagingException e) {
                    logger.error("Error sending message.", e);
                } finally {
                    semaphore.release();
                }
            }
        });

        if (forceQuit.get()) {
            break;
        }

        if (throtllingSemaphore != null) {
            /* for throttling the sending of emails */
            throtllingSemaphore.acquire();
        } else {
            /* no throttling so use delay */
            long sleepTime = delay - (System.currentTimeMillis() - threadStart);

            if (sleepTime > 0) {
                Thread.sleep(sleepTime);
            }
        }
    }

    threadPool.shutdown();
    threadPool.awaitTermination(30, TimeUnit.SECONDS);

    waitForReceiveThreads();

    logger.info("Total sent: " + sentCount.intValue() + ". Total time: "
            + DateTimeUtils.millisecondsToSeconds(System.currentTimeMillis() - startTime) + " (sec.)");
}

From source file:org.apache.solr.handler.dataimport.GmailServiceUserMailEntityProcessor.java

private boolean addEnvelopToDocument(Part part, Map<String, Object> row) throws MessagingException {
    MimeMessage mail = (MimeMessage) part;
    Address[] adresses;/*w w  w.j ava  2  s  . co  m*/
    if ((adresses = mail.getFrom()) != null && adresses.length > 0) {
        String from = adresses[0].toString();
        // check if we should ignore this sender
        for (String ignore : this.ignoreFrom) {
            if (from.toLowerCase().contains(ignore)) {
                LOG.info("Ignoring email from " + from);
                return false;
            }
        }
        row.put(FROM, from);
        row.put(FROM_CLEAN, cleanAddress(from));
    } else {
        return false;
    }

    List<String> to = new ArrayList<String>();
    if ((adresses = mail.getRecipients(Message.RecipientType.TO)) != null) {
        addAddressToList(adresses, to);
    }
    if ((adresses = mail.getRecipients(Message.RecipientType.CC)) != null) {
        addAddressToList(adresses, to);
    }
    if ((adresses = mail.getRecipients(Message.RecipientType.BCC)) != null) {
        addAddressToList(adresses, to);
    }
    if (!to.isEmpty()) {
        row.put(TO_CC_BCC, to);
        List<String> cleanAddresses = cleanAddresses(to);
        row.put(TO_CC_BCC_CLEAN, cleanAddresses);

        // save first TO address into separate field
        row.put(TO, to.get(0));
        row.put(TO_CLEAN, cleanAddresses.get(0));
    }

    row.put(MESSAGE_ID, mail.getMessageID());
    row.put(SUBJECT, mail.getSubject());

    {
        Date d = mail.getSentDate();
        if (d != null) {
            row.put(SENT_DATE, d);
        }
    }
    {
        Date d = mail.getReceivedDate();
        if (d != null) {
            row.put(RECEIVED_DATE, d);
        }
    }

    List<String> flags = new ArrayList<String>();
    for (Flags.Flag flag : mail.getFlags().getSystemFlags()) {
        if (flag == Flags.Flag.ANSWERED) {
            flags.add(FLAG_ANSWERED);
        } else if (flag == Flags.Flag.DELETED) {
            flags.add(FLAG_DELETED);
        } else if (flag == Flags.Flag.DRAFT) {
            flags.add(FLAG_DRAFT);
        } else if (flag == Flags.Flag.FLAGGED) {
            flags.add(FLAG_FLAGGED);
        } else if (flag == Flags.Flag.RECENT) {
            flags.add(FLAG_RECENT);
        } else if (flag == Flags.Flag.SEEN) {
            flags.add(FLAG_SEEN);
        }
    }
    flags.addAll(Arrays.asList(mail.getFlags().getUserFlags()));
    row.put(FLAGS, flags);

    String[] hdrs = mail.getHeader("X-Mailer");
    if (hdrs != null) {
        row.put(XMAILER, hdrs[0]);
    }
    return true;
}

From source file:org.alfresco.repo.content.transform.EMLParser.java

/**
 * Extracts properties and text from an EML Document input stream.
 *
 * @param stream//  w  w  w  . ja  va  2s.com
 *            the stream
 * @param handler
 *            the handler
 * @param metadata
 *            the metadata
 * @param context
 *            the context
 * @throws IOException
 *             Signals that an I/O exception has occurred.
 * @throws SAXException
 *             the sAX exception
 * @throws TikaException
 *             the tika exception
 */
@Override
public void parse(InputStream stream, ContentHandler handler, Metadata metadata, ParseContext context)
        throws IOException, SAXException, TikaException {

    XHTMLContentHandler xhtml = new XHTMLContentHandler(handler, metadata);
    xhtml.startDocument();

    Properties props = System.getProperties();
    Session mailSession = Session.getDefaultInstance(props, null);

    try {
        MimeMessage message = new MimeMessage(mailSession, stream);

        String subject = message.getSubject();
        String from = this.convertAddressesToString(message.getFrom());
        // Recipients :
        String messageException = "";
        String to = "";
        String cc = "";
        String bcc = "";
        try {
            // QVIDMS-2004 Added because of bug in Mail Api
            to = this.convertAddressesToString(message.getRecipients(Message.RecipientType.TO));
            cc = this.convertAddressesToString(message.getRecipients(Message.RecipientType.CC));
            bcc = this.convertAddressesToString(message.getRecipients(Message.RecipientType.BCC));
        } catch (AddressException e) {
            e.printStackTrace();
            messageException = e.getRef();
            if (messageException.indexOf("recipients:") != -1) {
                to = messageException.substring(0, messageException.indexOf(":"));
            }
        }
        metadata.set(Office.AUTHOR, from);
        metadata.set(DublinCore.TITLE, subject);
        metadata.set(DublinCore.SUBJECT, subject);

        xhtml.element("h1", subject);

        xhtml.startElement("dl");
        header(xhtml, "From", MimeUtility.decodeText(from));
        header(xhtml, "To", MimeUtility.decodeText(to.toString()));
        header(xhtml, "Cc", MimeUtility.decodeText(cc.toString()));
        header(xhtml, "Bcc", MimeUtility.decodeText(bcc.toString()));

        // // Parse message
        // if (message.getContent() instanceof MimeMultipart) {
        // // Multipart message, call matching method
        // MimeMultipart multipart = (MimeMultipart) message.getContent();
        // this.extractMultipart(xhtml, multipart, context);

        List<String> attachmentList = new ArrayList<String>();
        // prepare attachments
        prepareExtractMultipart(xhtml, message, null, context, attachmentList);
        if (attachmentList.size() > 0) {
            // TODO internationalization
            header(xhtml, "Attachments", attachmentList.toString());
        }
        xhtml.endElement("dl");

        // a supprimer si pb et a remplacer par ce qui est commenT
        adaptedExtractMultipart(xhtml, message, null, context);

        xhtml.endDocument();
    } catch (Exception e) {
        throw new TikaException("Error while processing message", e);
    }
}

From source file:org.apereo.portal.portlets.account.EmailPasswordResetNotificationImpl.java

@Override
public void sendNotification(URL resetUrl, ILocalAccountPerson account, Locale locale) {
    log.debug("Sending password reset instructions to user with url {}", resetUrl.toString());

    try {//from w w  w.j  a v a  2s.c o m
        MimeMessage message = mailSender.createMimeMessage();
        MimeMessageHelper helper = new MimeMessageHelper(message, true);
        String email = (String) account.getAttributeValue(ILocalAccountPerson.ATTR_MAIL);
        String subject = messageSource.getMessage(subjectMessageKey, new Object[] {}, locale);
        String body = formatBody(resetUrl, account, locale);

        helper.addTo(email);
        helper.setText(body, true);
        helper.setSubject(subject);
        helper.setFrom(portalEmailAddress, messageSource.getMessage("portal.name", new Object[] {}, locale));

        log.debug("Sending message to {} from {} subject {}", email, Arrays.toString(message.getFrom()),
                message.getSubject());
        this.mailSender.send(helper.getMimeMessage());

    } catch (Exception e) {
        log.error("Unable to send password reset email", e);
    }
}

From source file:org.apache.james.James.java

/**
 * Place a mail on the spool for processing
 *
 * @param message the message to send//from  ww w  .  j av a  2s.com
 *
 * @throws MessagingException if an exception is caught while placing the mail
 *                            on the spool
 */
public void sendMail(MimeMessage message) throws MessagingException {
    MailAddress sender = new MailAddress((InternetAddress) message.getFrom()[0]);
    Collection recipients = new HashSet();
    Address addresses[] = message.getAllRecipients();
    if (addresses != null) {
        for (int i = 0; i < addresses.length; i++) {
            // Javamail treats the "newsgroups:" header field as a
            // recipient, so we want to filter those out.
            if (addresses[i] instanceof InternetAddress) {
                recipients.add(new MailAddress((InternetAddress) addresses[i]));
            }
        }
    }
    sendMail(sender, recipients, message);
}

From source file:org.alfresco.repo.security.authentication.ResetPasswordServiceImplTest.java

@Test
public void testResetPassword() throws Exception {
    // Try the credential before change of password
    authenticateUser(testPerson.userName, testPerson.password);

    // Make sure to run as system
    AuthenticationUtil.clearCurrentSecurityContext();
    AuthenticationUtil.setRunAsUserSystem();

    // Request password reset
    resetPasswordService.requestReset(testPerson.userName, "share");
    assertEquals("A reset password email should have been sent.", 1, emailUtil.getSentCount());
    // Check the email
    MimeMessage msg = emailUtil.getLastEmail();
    assertNotNull("There should be an email.", msg);
    assertEquals("Should've been only one email recipient.", 1, msg.getAllRecipients().length);
    // Check the recipient is the person who requested the reset password
    assertEquals(testPerson.email, msg.getAllRecipients()[0].toString());
    //Check the sender is what we set as default
    assertEquals(DEFAULT_SENDER, msg.getFrom()[0].toString());
    // There should be a subject
    assertNotNull("There should be a subject.", msg.getSubject());
    // Check the default email subject - (check that we are sending the right email)
    String emailSubjectKey = getDeclaredField(SendResetPasswordEmailDelegate.class, "EMAIL_SUBJECT_KEY");
    assertNotNull(emailSubjectKey);// ww w . j  ava 2  s  .  co  m
    assertEquals(msg.getSubject(), I18NUtil.getMessage(emailSubjectKey));

    // Check the reset password url.
    String resetPasswordUrl = (String) emailUtil.getLastEmailTemplateModelValue("reset_password_url");
    assertNotNull("Wrong email is sent.", resetPasswordUrl);
    // Get the workflow id and key
    Pair<String, String> pair = getWorkflowIdAndKeyFromUrl(resetPasswordUrl);
    assertNotNull("Workflow Id can't be null.", pair.getFirst());
    assertNotNull("Workflow Key can't be null.", pair.getSecond());

    emailUtil.reset();
    // Now that we have got the email, try to reset the password
    ResetPasswordDetails passwordDetails = new ResetPasswordDetails().setUserId(testPerson.userName)
            .setPassword("newPassword").setWorkflowId(pair.getFirst()).setWorkflowKey(pair.getSecond());

    resetPasswordService.initiateResetPassword(passwordDetails);
    assertEquals("A reset password confirmation email should have been sent.", 1, emailUtil.getSentCount());
    // Check the email
    msg = emailUtil.getLastEmail();
    assertNotNull("There should be an email.", msg);
    assertEquals("Should've been only one email recipient.", 1, msg.getAllRecipients().length);
    // Check the recipient is the person who requested the reset password
    assertEquals(testPerson.email, msg.getAllRecipients()[0].toString());
    // Check the sender is what we set as default
    assertEquals(DEFAULT_SENDER, msg.getFrom()[0].toString());
    // There should be a subject
    assertNotNull("There should be a subject.", msg.getSubject());
    // Check the default email subject - (check that we are sending the right email)
    emailSubjectKey = getDeclaredField(SendResetPasswordConfirmationEmailDelegate.class, "EMAIL_SUBJECT_KEY");
    assertNotNull(emailSubjectKey);
    assertEquals(msg.getSubject(), I18NUtil.getMessage(emailSubjectKey));

    // Try the old credential
    TestHelper.assertThrows(() -> authenticateUser(testPerson.userName, testPerson.password),
            AuthenticationException.class,
            "As the user changed her password, the authentication should have failed.");

    // Try the new credential
    authenticateUser(testPerson.userName, "newPassword");

    // Make sure to run as system
    AuthenticationUtil.clearCurrentSecurityContext();
    AuthenticationUtil.setRunAsUserSystem();
    emailUtil.reset();
    // Try reset again with the used workflow
    TestHelper.assertThrows(() -> resetPasswordService.initiateResetPassword(passwordDetails),
            InvalidResetPasswordWorkflowException.class,
            "The workflow instance is not active (it has already been used).");
    assertEquals("No email should have been sent.", 0, emailUtil.getSentCount());
}