Example usage for javax.mail Message getFrom

List of usage examples for javax.mail Message getFrom

Introduction

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

Prototype

public abstract Address[] getFrom() throws MessagingException;

Source Link

Document

Returns the "From" attribute.

Usage

From source file:org.apache.nifi.processors.standard.TestPutEmail.java

@Test
public void testOutgoingMessage() throws Exception {
    // verifies that are set on the outgoing Message correctly
    runner.setProperty(PutEmail.SMTP_HOSTNAME, "smtp-host");
    runner.setProperty(PutEmail.HEADER_XMAILER, "TestingNiFi");
    runner.setProperty(PutEmail.FROM, "test@apache.org");
    runner.setProperty(PutEmail.MESSAGE, "Message Body");
    runner.setProperty(PutEmail.TO, "recipient@apache.org");

    runner.enqueue("Some Text".getBytes());

    runner.run();// ww w.  j  ava2  s .  c  o m

    runner.assertQueueEmpty();
    runner.assertAllFlowFilesTransferred(PutEmail.REL_SUCCESS);

    // Verify that the Message was populated correctly
    assertEquals("Expected a single message to be sent", 1, processor.getMessages().size());
    Message message = processor.getMessages().get(0);
    assertEquals("test@apache.org", message.getFrom()[0].toString());
    assertEquals("X-Mailer Header", "TestingNiFi", message.getHeader("X-Mailer")[0]);
    assertEquals("Message Body", message.getContent());
    assertEquals("recipient@apache.org", message.getRecipients(RecipientType.TO)[0].toString());
    assertNull(message.getRecipients(RecipientType.BCC));
    assertNull(message.getRecipients(RecipientType.CC));
}

From source file:org.jahia.modules.gateway.decoders.BaseMailDecoder.java

protected String getSenderEmail(Message message) {
    String from = null;//from w  ww .j  a  v a2 s  .  c o m
    try {
        Address[] senders = message.getFrom();
        if (senders != null && senders.length > 0) {
            from = ((InternetAddress) senders[0]).getAddress();
        }
    } catch (MessagingException e) {
        logger.error(e.getMessage(), e);
    }
    return from;
}

From source file:org.apache.nifi.processors.standard.TestPutEmail.java

@Test
public void testOutgoingMessageAttachment() throws Exception {
    // verifies that are set on the outgoing Message correctly
    runner.setProperty(PutEmail.SMTP_HOSTNAME, "smtp-host");
    runner.setProperty(PutEmail.HEADER_XMAILER, "TestingNiFi");
    runner.setProperty(PutEmail.FROM, "test@apache.org");
    runner.setProperty(PutEmail.MESSAGE, "Message Body");
    runner.setProperty(PutEmail.ATTACH_FILE, "true");
    runner.setProperty(PutEmail.CONTENT_TYPE, "text/html");
    runner.setProperty(PutEmail.TO, "recipient@apache.org");

    runner.enqueue("Some text".getBytes());

    runner.run();//w w  w  .  j  a  va  2s .co  m

    runner.assertQueueEmpty();
    runner.assertAllFlowFilesTransferred(PutEmail.REL_SUCCESS);

    // Verify that the Message was populated correctly
    assertEquals("Expected a single message to be sent", 1, processor.getMessages().size());
    Message message = processor.getMessages().get(0);
    assertEquals("test@apache.org", message.getFrom()[0].toString());
    assertEquals("X-Mailer Header", "TestingNiFi", message.getHeader("X-Mailer")[0]);
    assertEquals("recipient@apache.org", message.getRecipients(RecipientType.TO)[0].toString());

    assertTrue(message.getContent() instanceof MimeMultipart);

    final MimeMultipart multipart = (MimeMultipart) message.getContent();
    final BodyPart part = multipart.getBodyPart(0);
    final InputStream is = part.getDataHandler().getInputStream();
    final String decodedText = StringUtils.newStringUtf8(Base64.decodeBase64(IOUtils.toString(is, "UTF-8")));
    assertEquals("Message Body", decodedText);

    final BodyPart attachPart = multipart.getBodyPart(1);
    final InputStream attachIs = attachPart.getDataHandler().getInputStream();
    final String text = IOUtils.toString(attachIs, "UTF-8");
    assertEquals("Some text", text);

    assertNull(message.getRecipients(RecipientType.BCC));
    assertNull(message.getRecipients(RecipientType.CC));
}

From source file:org.jahia.modules.gateway.decoders.BaseMailDecoder.java

protected JahiaUser getSender(Message message) {
    JahiaUser user = null;//from ww w  .  j av a2  s .c o m
    try {
        Address[] senders = message.getFrom();
        String from = null;
        if (senders != null && senders.length > 0) {
            from = ((InternetAddress) senders[0]).getAddress();
        }
        if (StringUtils.isNotBlank(from)) {
            Properties userProperties = new Properties();
            userProperties.setProperty("j:email", from);
            Set<JCRUserNode> users = getUserManagerService().searchUsers(userProperties);
            user = users != null && !users.isEmpty() ? users.iterator().next().getJahiaUser() : null;
        }
    } catch (MessagingException e) {
        logger.warn("Unable to retrieve Jahia user that corresponds" + " to the e-mail sender. Cause: "
                + e.getMessage(), e);
    }

    return user;
}

From source file:org.apache.nifi.processors.standard.TestPutEmail.java

@Test
public void testOutgoingMessageWithOptionalProperties() throws Exception {
    // verifies that optional attributes are set on the outgoing Message correctly
    runner.setProperty(PutEmail.SMTP_HOSTNAME, "smtp-host");
    runner.setProperty(PutEmail.HEADER_XMAILER, "TestingNiFi");
    runner.setProperty(PutEmail.FROM, "${from}");
    runner.setProperty(PutEmail.MESSAGE, "${message}");
    runner.setProperty(PutEmail.TO, "${to}");
    runner.setProperty(PutEmail.BCC, "${bcc}");
    runner.setProperty(PutEmail.CC, "${cc}");

    Map<String, String> attributes = new HashMap<>();
    attributes.put("from", "test@apache.org <NiFi>");
    attributes.put("message", "the message body");
    attributes.put("to", "to@apache.org");
    attributes.put("bcc", "bcc@apache.org");
    attributes.put("cc", "cc@apache.org");
    runner.enqueue("Some Text".getBytes(), attributes);

    runner.run();//from w  ww . j  a  va 2  s .co  m

    runner.assertQueueEmpty();
    runner.assertAllFlowFilesTransferred(PutEmail.REL_SUCCESS);

    // Verify that the Message was populated correctly
    assertEquals("Expected a single message to be sent", 1, processor.getMessages().size());
    Message message = processor.getMessages().get(0);
    assertEquals("\"test@apache.org\" <NiFi>", message.getFrom()[0].toString());
    assertEquals("X-Mailer Header", "TestingNiFi", message.getHeader("X-Mailer")[0]);
    assertEquals("the message body", message.getContent());
    assertEquals(1, message.getRecipients(RecipientType.TO).length);
    assertEquals("to@apache.org", message.getRecipients(RecipientType.TO)[0].toString());
    assertEquals(1, message.getRecipients(RecipientType.BCC).length);
    assertEquals("bcc@apache.org", message.getRecipients(RecipientType.BCC)[0].toString());
    assertEquals(1, message.getRecipients(RecipientType.CC).length);
    assertEquals("cc@apache.org", message.getRecipients(RecipientType.CC)[0].toString());
}

From source file:org.jahia.modules.gateway.decoders.DefaultMailDecoder.java

public String decode(Pattern matchingPattern, MailContent parsedMailContent, Message originalMessage)
        throws Exception {
    String subject = originalMessage.getSubject();
    JahiaUser sender = getSender(originalMessage);
    if (sender == null) {
        Address[] from = originalMessage.getFrom();
        logger.warn(/*from   w w w .  j ava  2 s .  c  o  m*/
                "Unable to find the Jahia user with the e-mail corresponding to the sender of the e-mail message: {}",
                (from != null && from.length > 0 ? from[0] : null));
        return null;
    }

    JSONObject jsonObject = new JSONObject();

    jsonObject.put("nodetype", "jnt:privateNote");
    jsonObject.put("name", subject);
    jsonObject.put("locale", "en");
    jsonObject.put("workspace", Constants.EDIT_WORKSPACE);
    jsonObject.put("saveFileUnderNewlyCreatedNode", Boolean.TRUE);

    Map<String, String> properties = new LinkedHashMap<String, String>();
    properties.put("note", parsedMailContent.getBody());
    properties.put("jcr:title", subject);
    properties.put("date", DateFormatUtils.ISO_DATETIME_TIME_ZONE_FORMAT.format(System.currentTimeMillis()));
    jsonObject.put("properties", properties);

    jsonObject.put("path",
            getUserManagerService().getUserSplittingRule().getPathForUsername(sender.getName()) + "/contents");

    if (!parsedMailContent.getFiles().isEmpty()) {
        jsonObject.put("files", BaseMailDecoder.toJSON(parsedMailContent.getFiles()));
    }

    return jsonObject.toString();
}

From source file:com.intuit.tank.mail.TankMailer.java

private void logMsg(String host, Message m) {
    try {/* w w w.j av  a2s  .  c o m*/
        StringBuilder sb = new StringBuilder();
        sb.append("To: ").append(StringUtils.join(m.getAllRecipients(), ',')).append('\n');
        sb.append("From: ").append(StringUtils.join(m.getFrom(), ',')).append('\n');
        sb.append("Subject: ").append(m.getSubject()).append('\n');
        sb.append("Body: ").append(m.getContent()).append('\n');
        LOG.info("Sending email to server (" + host + "):\n" + sb.toString());
    } catch (Exception e) {
        LOG.error("Error generating log msg: " + e);
    }

}

From source file:nz.net.orcon.kanban.automation.actions.EmailReceiverAction.java

public void downloadEmails(String mailStoreProtocol, String mailStoreHost, String mailStoreUserName,
        String mailStorePassword) throws IOException {

    Session session = getMailStoreSession(mailStoreProtocol, mailStoreHost, mailStoreUserName,
            mailStorePassword);/*  www. j  ava 2s  .co  m*/
    try {
        // connects to the message store
        Store store = session.getStore(mailStoreProtocol);
        store.connect(mailStoreHost, mailStoreUserName, mailStorePassword);

        logger.info("connected to message store");

        // opens the inbox folder
        Folder folderInbox = store.getFolder("INBOX");
        folderInbox.open(Folder.READ_ONLY);

        // fetches new messages from server
        Message[] messages = folderInbox.getMessages();

        for (int i = 0; i < messages.length; i++) {
            Message msg = messages[i];
            Address[] fromAddress = msg.getFrom();
            String from = fromAddress[0].toString();
            String subject = msg.getSubject();
            String toList = parseAddresses(msg.getRecipients(RecipientType.TO));
            String ccList = parseAddresses(msg.getRecipients(RecipientType.CC));
            String sentDate = msg.getSentDate().toString();

            String contentType = msg.getContentType();
            String messageContent = "";

            if (contentType.contains("text/plain") || contentType.contains("text/html")) {
                try {
                    Object content = msg.getContent();
                    if (content != null) {
                        messageContent = content.toString();
                    }
                } catch (Exception ex) {
                    messageContent = "[Error downloading content]";
                    ex.printStackTrace();
                }
            }

            // print out details of each message
            System.out.println("Message #" + (i + 1) + ":");
            System.out.println("\t From: " + from);
            System.out.println("\t To: " + toList);
            System.out.println("\t CC: " + ccList);
            System.out.println("\t Subject: " + subject);
            System.out.println("\t Sent Date: " + sentDate);
            System.out.println("\t Message: " + messageContent);
        }

        // disconnect
        folderInbox.close(false);
        store.close();
    } catch (NoSuchProviderException ex) {
        logger.warn("No provider for protocol: " + mailStoreProtocol + " " + ex);
    } catch (MessagingException ex) {
        logger.error("Could not connect to the message store" + ex);
    }
}

From source file:EmailBean.java

private void displayMessage(Message msg, PrintWriter out) throws MessagingException, IOException {

    if (msg != null && msg.getContent() instanceof String) {

        if (msg.getFrom()[0] instanceof InternetAddress) {
            out.println(//from   ww  w  . ja  v  a2  s . com
                    "Message received from: " + ((InternetAddress) msg.getFrom()[0]).getAddress() + "<br />");
        }
        out.println("Message received on: " + msg.getReceivedDate() + "<br />");
        out.println("Message content type: " + msg.getContentType() + "<br />");
        out.println("Message content type: " + (String) msg.getContent());
    } else {

        out.println("<h2>The received email message was not of a text content type.</h2>");

    }

}

From source file:com.jlgranda.fede.ejb.mail.reader.FacturaElectronicaMailReader.java

/**
 * Leer el inbox de <tt>Subject</tt>
 *
 * @param _subject la instancia <tt>Subject</tt> para la cual ingresar al
 * inbox y cargar las facturas/*from  ww w  .  j av  a 2s  .co  m*/
 * @param folder
 * @return Lista de objetos <tt>FacturaReader</tt>
 * @throws javax.mail.MessagingException
 * @throws java.io.IOException
 */
public List<FacturaReader> read(Subject _subject, String folder) throws MessagingException, IOException {

    List<FacturaReader> result = new ArrayList<>();
    String server = settingService.findByName("mail.imap.host").getValue();
    //Todo definir una mejor forma de manejar la cuenta de correo
    String username = _subject.getFedeEmail();
    String password = _subject.getFedeEmailPassword();
    //String port = settingService.findByName("mail.imap.port").getValue();

    //String proto = "true".equalsIgnoreCase(settingService.findByName("mail.smtp.starttls.enable").getValue()) ? "TLS" : null;

    ///logger.info("Conectanto a servidor de correo # {}:\n\t Username: {}\n\t Password: {}\n\t ", server, username, password);
    IMAPClient client = new IMAPClient(server, username, password);

    Address[] fromAddress = null;
    String from = "";
    String subject = "";
    String sentDate = "";
    FacturaReader facturaReader = null;
    String[] token = null;
    List<String> urls = new ArrayList<>(); //Guardar enlaces a factura si es el caso
    boolean facturaEncontrada = false;
    Factura factura = null;
    EmailHelper emailHelper = new EmailHelper();
    MessageBuilder builder = new DefaultMessageBuilder();
    ByteArrayOutputStream os = null;
    for (Message message : client.getMessages(folder, false)) {
        //attachFiles = "";
        fromAddress = message.getFrom();
        from = fromAddress[0].toString();
        subject = message.getSubject();
        sentDate = message.getSentDate() != null ? message.getSentDate().toString() : "";

        facturaEncontrada = false;

        try {
            org.apache.james.mime4j.dom.Message mime4jMessage = builder
                    .parseMessage(new ByteArrayInputStream(emailHelper.fullMail(message).getBytes()));
            result.addAll(handleMessage(mime4jMessage));
        } catch (org.apache.james.mime4j.MimeIOException | org.apache.james.mime4j.MimeException ex) {
            logger.error("Fail to read message: " + subject, ex);
        } catch (Exception ex) {
            logger.error("Fail to read message with General Exception: " + subject, ex);
        }
    }

    client.close();

    logger.info("Readed {} email messages!", result.size());

    return result;
}