Example usage for javax.mail Address toString

List of usage examples for javax.mail Address toString

Introduction

In this page you can find the example usage for javax.mail Address toString.

Prototype

@Override
public abstract String toString();

Source Link

Document

Return a String representation of this address object.

Usage

From source file:org.sourceforge.net.javamail4ews.transport.EwsTransport.java

private EmailAddress emailAddressFromInternetAddress(Address address) {
    String personalPart = "";
    String internetPart = "";
    if (isInternetAddress(address)) {
        personalPart = ((InternetAddress) address).getPersonal();
        internetPart = ((InternetAddress) address).getAddress();
    } else {/*  w w w.j ava 2  s. c om*/
        internetPart = address.toString();
    }
    if (personalPart != null && !personalPart.isEmpty()) {
        logger.info("creating address : personal part is '" + personalPart + "' internet part is '"
                + internetPart + "'");
        return new EmailAddress(personalPart, internetPart);
    }
    logger.info("creating address : internet part is '" + internetPart + "'");
    return new EmailAddress(internetPart);
}

From source file:org.mangelp.fakeSmtpWeb.httpServer.mailBrowser.MailFile.java

/**
 * Parse the file on disk using a MimeMessageParser and set all the instance
 * properties we will be using./*from   w  ww  . j av a 2 s  .  c  o  m*/
 *
 * @throws FileNotFoundException
 * @throws MessagingException
 * @throws ParseException
 * @throws IOException
 */
protected void parseEmail() throws FileNotFoundException, MessagingException, ParseException, IOException {

    InputStream inputStream = new BufferedInputStream(new FileInputStream(this.getFile()));

    try {
        final Session session = Session.getDefaultInstance(new Properties());

        MimeMessage message = new MimeMessage(session, inputStream);
        MimeMessageParser mimeParser = new MimeMessageParser(message);

        mimeParser.parse();

        this.setSubject(mimeParser.getSubject());
        this.setFrom(mimeParser.getFrom());
        this.setReplyTo(mimeParser.getReplyTo());

        ArrayList<String> toList = new ArrayList<String>();
        for (Address emailAddress : mimeParser.getTo()) {
            toList.add(emailAddress.toString());
        }

        this.setTo(toList.toArray(this.getTo()));

        ArrayList<String> ccList = new ArrayList<String>();
        for (Address emailAddress : mimeParser.getCc()) {
            ccList.add(emailAddress.toString());
        }

        this.setCc(ccList.toArray(this.getCc()));

        ArrayList<String> bccList = new ArrayList<String>();
        for (Address emailAddress : mimeParser.getBcc()) {
            bccList.add(emailAddress.toString());
        }

        this.setBcc(bccList.toArray(this.getBcc()));

        if (mimeParser.hasAttachments()) {
            attachments = new ArrayList<MailAttachment>(mimeParser.getAttachmentList().size());

            int index = 0;
            for (DataSource ds : mimeParser.getAttachmentList()) {
                attachments.add(new MailAttachment(++index, ds));
            }
        }

        if (mimeParser.hasHtmlContent()) {
            this.setHtmlContent(mimeParser.getHtmlContent());
        }

        if (mimeParser.hasPlainContent()) {
            this.setPlainContent(mimeParser.getPlainContent());
        }

    } catch (Exception e) {
        throw new ParseException("Failed to parse file " + this.getFile().toString() + ": " + e.getMessage());
    }

    this.setId(DigestUtils.sha1Hex(inputStream));

    inputStream.close();
}

From source file:org.pentaho.di.trans.steps.mailinput.ParseMailInputTest.java

@Before
public void beforeTest() throws MessagingException, IOException, KettleException {
    message = Mockito.mock(Message.class);

    MailConnection conn = mock(MailConnection.class);
    when(conn.getMessageBody(any(Message.class))).thenReturn(MSG_BODY);
    when(conn.getFolderName()).thenReturn(FLD_NAME);
    when(conn.getAttachedFilesCount(any(Message.class), any(Pattern.class))).thenReturn(ATTCH_COUNT);
    when(conn.getMessageBodyContentType(any(Message.class))).thenReturn(CNTNT_TYPE);
    data = mock(MailInputData.class);
    data.mailConn = conn;//from   w  w  w  . j a v a  2  s  .c  o  m

    mailInput = new MailInput(stepMockHelper.stepMeta, data, 0, stepMockHelper.transMeta, stepMockHelper.trans);

    Address addrFrom1 = mock(Address.class);
    when(addrFrom1.toString()).thenReturn(FROM1);
    Address addrFrom2 = mock(Address.class);
    when(addrFrom2.toString()).thenReturn(FROM2);
    Address addrRep1 = mock(Address.class);
    when(addrRep1.toString()).thenReturn(REP1);
    Address addrRep2 = mock(Address.class);
    when(addrRep2.toString()).thenReturn(REP2);
    Address allRec1 = mock(Address.class);
    when(allRec1.toString()).thenReturn(REC1);
    Address allRec2 = mock(Address.class);
    when(allRec2.toString()).thenReturn(REC2);

    Address[] adrFr = { addrFrom1, addrFrom2 };
    Address[] adrRep = { addrRep1, addrRep2 };
    Address[] adrRecip = { allRec1, allRec2 };

    message = Mockito.mock(Message.class);
    when(message.getMessageNumber()).thenReturn(MSG_NUMB);
    when(message.getSubject()).thenReturn(SUBJ);

    when(message.getFrom()).thenReturn(adrFr);
    when(message.getReplyTo()).thenReturn(adrRep);
    when(message.getAllRecipients()).thenReturn(adrRecip);
    when(message.getDescription()).thenReturn(DESC);
    when(message.getReceivedDate()).thenReturn(DATE1);
    when(message.getSentDate()).thenReturn(DATE2);
    when(message.getContentType()).thenReturn(CNTNT_TYPE_EMAIL);
    when(message.getSize()).thenReturn(CNTNT_SIZE);

    Header ex1 = new Header(HDR_EX1, HDR_EX1V);
    Header ex2 = new Header(HDR_EX2, HDR_EX2V);

    // for fixed [PDI-6532]
    when(message.getMatchingHeaders(aryEq(new String[] { HDR_EX1 }))).thenReturn(getEnum(new Header[] { ex1 }));
    when(message.getMatchingHeaders(aryEq(new String[] { HDR_EX2 }))).thenReturn(getEnum(new Header[] { ex2 }));
    when(message.getMatchingHeaders(aryEq(new String[] { HDR_EX1, HDR_EX2 })))
            .thenReturn(getEnum(new Header[] { ex1, ex2 }));

    // for previous implementation
    when(message.getHeader(eq(HDR_EX1))).thenReturn(new String[] { ex1.getValue() });
    when(message.getHeader(eq(HDR_EX2))).thenReturn(new String[] { ex2.getValue() });
}

From source file:org.nuxeo.cm.mail.actionpipe.ExtractMessageInformation.java

@Override
@SuppressWarnings("deprecation")
public boolean execute(ExecutionContext context) throws MessagingException {
    File tmpOutput = null;/*from   w ww.j av  a2  s  .  c o  m*/
    OutputStream out = null;
    try {
        Message originalMessage = context.getMessage();
        if (log.isDebugEnabled()) {
            log.debug("Transforming message, original subject: " + originalMessage.getSubject());
        }

        // fully load the message before trying to parse to
        // override most of server bugs, see
        // http://java.sun.com/products/javamail/FAQ.html#imapserverbug
        Message message;
        if (originalMessage instanceof MimeMessage) {
            message = new MimeMessage((MimeMessage) originalMessage);
            if (log.isDebugEnabled()) {
                log.debug("Transforming message after full load: " + message.getSubject());
            }
        } else {
            // stuck with the original one
            message = originalMessage;
        }

        Address[] from = message.getFrom();
        if (from != null) {
            Address addr = from[0];
            if (addr instanceof InternetAddress) {
                InternetAddress iAddr = (InternetAddress) addr;
                context.put(SENDER_KEY, iAddr.getPersonal());
                context.put(SENDER_EMAIL_KEY, iAddr.getAddress());
            } else {
                context.put(SENDER_KEY, addr.toString());
            }
        }
        Date receivedDate = message.getReceivedDate();
        if (receivedDate == null) {
            // try to get header manually
            String[] dateHeader = message.getHeader("Date");
            if (dateHeader != null) {
                try {
                    long time = Date.parse(dateHeader[0]);
                    receivedDate = new Date(time);
                } catch (IllegalArgumentException e) {
                    // nevermind
                }
            }
        }

        if (receivedDate != null) {
            Calendar date = Calendar.getInstance();
            date.setTime(receivedDate);
            context.put(RECEPTION_DATE_KEY, date);
        }
        String subject = message.getSubject();
        if (subject != null) {
            subject = subject.trim();
        }
        if (subject == null || "".equals(subject)) {
            subject = "<Unknown>";
        }
        context.put(SUBJECT_KEY, subject);
        String[] messageIdHeader = message.getHeader("Message-ID");
        if (messageIdHeader != null) {
            context.put(MESSAGE_ID_KEY, messageIdHeader[0]);
        }

        // TODO: pass it through initial context
        MimetypeRegistry mimeService = (MimetypeRegistry) context.getInitialContext().get(MIMETYPE_SERVICE_KEY);
        if (mimeService == null) {
            log.error("Could not retrieve mimetype service");
        }

        // add all content as first blob
        tmpOutput = File.createTempFile("injectedEmail", ".eml");
        Framework.trackFile(tmpOutput, tmpOutput);
        out = new FileOutputStream(tmpOutput);
        message.writeTo(out);
        Blob blob = Blobs.createBlob(tmpOutput, MESSAGE_RFC822_MIMETYPE, null, subject + ".eml");

        List<Blob> blobs = new ArrayList<>();
        blobs.add(blob);
        context.put(ATTACHMENTS_KEY, blobs);

        // process content
        getAttachmentParts(message, subject, mimeService, context);
        return true;
    } catch (IOException e) {
        log.error(e);
    } finally {
        IOUtils.closeQuietly(out);
    }
    return false;
}

From source file:TIG055st2014.mailmaster.Activities.ComposeActivity.java

@Override
protected void onStart() {
    super.onStart();
    AppVariablesSingleton apv = AppVariablesSingleton.getInstance();
    TextView sender;/*from   w  w w  .j a v  a  2 s  .  c om*/
    TextView from;
    TextView result;

    /*
     * If message is a reply then certain fields are instantiated based on
     * fields from the message that is being replied to. BCC is not filled
     * (unless replying on one's own message) since they're supposed to be secret.
     */
    if (apv.getIsReply()) {
        getActionBar().setTitle(R.string.composing_rp);
        result = (TextView) findViewById(R.id.totalsizeReply);
        sender = (TextView) findViewById(R.id.sendAccReply);
        sender.setText(currentAcc);
        sender.setEnabled(false);
        sender.setVisibility(View.GONE);
        from = (TextView) findViewById(R.id.senderReply);
        from.setEnabled(false);
        from.setVisibility(View.GONE);
        TextView to = (TextView) findViewById(R.id.receiveAccsReply);
        TextView subject = (TextView) findViewById(R.id.subjectReply);
        EditText cc = (EditText) findViewById(R.id.ccAccsReply);
        EditText bcc = ((EditText) findViewById(R.id.bccAccsReply));
        to.setText("");
        cc.setText("");
        bcc.setText("");

        try {
            subject.setText(apv.getReply().getSubject());
            //Used if replying to email sent by yourself (basically using sent email as draft).
            if (apv.getFolderName(currentAcc).contains("Sent")) {
                Address[] tempTo = apv.getEmail().getRecipients(RecipientType.TO);
                if (tempTo != null) {
                    for (Address a : tempTo) {
                        if (to.getText().toString().equals("")) {
                            to.setText(a.toString());
                        } else {
                            to.setText(to.getText() + "," + a.toString());
                        }
                    }
                }
                this.addAddresses(apv.getEmail().getRecipients(Message.RecipientType.BCC), bcc);
            }
            //Used for "normal" reply.
            else {
                to.setText(apv.getEmail().getFrom()[0].toString());
            }
            this.addAddresses(apv.getEmail().getRecipients(Message.RecipientType.CC), cc);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    /* If not reply, app attempts to load all fields since message might be
       based on draft. **/
    else {
        getActionBar().setTitle(R.string.composing);
        result = (TextView) findViewById(R.id.totalsize);
        sender = (TextView) findViewById(R.id.sendAcc);
        sender.setText(currentAcc);
        sender.setEnabled(false);
        sender.setVisibility(View.GONE);
        from = (TextView) findViewById(R.id.sender);
        from.setEnabled(false);
        from.setVisibility(View.GONE);
        if (apv.getFolderName(currentAcc).contains("Drafts")) {
            try {
                MailFunctionality mf = new MailFunctionality(currentAcc, accounts.getString(currentAcc, ""),
                        (currentAcc.split("@"))[1]);
                EditText recipients = ((EditText) findViewById(R.id.receiveAccs));
                EditText cc = ((EditText) findViewById(R.id.ccAccs));
                EditText bcc = ((EditText) findViewById(R.id.bccAccs));
                EditText subject = ((EditText) findViewById(R.id.subject));
                if (apv.getEmail().getSubject() != null) {
                    subject.setText(apv.getEmail().getSubject().toString());
                }
                recipients.setText("");
                cc.setText("");
                bcc.setText("");

                mf.getContents(this);
                addAddresses(apv.getEmail().getRecipients(Message.RecipientType.TO), recipients);
                addAddresses(apv.getEmail().getRecipients(Message.RecipientType.CC), cc);
                addAddresses(apv.getEmail().getRecipients(Message.RecipientType.BCC), bcc);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
    if (listView.getAdapter() == null) {
        listView.setAdapter(new AttachmentsAdapter(getApplicationContext(), R.layout.attachments_item,
                R.id.attachments_text, attachments, result));
    }
}

From source file:edu.stanford.muse.index.EmailDocument.java

/** returns a sorted list of strings based on given addresses.
 * none of the addresses should be null!
 * x itself can be null in which case an empty list is returned. */
private List<String> addressesToList(Address[] x) {
    List<String> result = new ArrayList<String>();
    if (x != null)
        for (Address a : x)
            result.add(a.toString()); // should not be null
    Collections.sort(result);//  www . j  ava  2  s  .c  o  m
    return result;
}

From source file:edu.stanford.muse.index.EmailDocument.java

@Override
public int hashCode() {
    int result = super.hashCode();
    if (messageID != null)
        result = result * 37 ^ messageID.hashCode();
    if (to != null)
        for (Address x : to)
            result = result * 37 ^ x.toString().hashCode(); // ^ 1
    if (cc != null)
        for (Address x : cc)
            result = result * 37 ^ x.toString().hashCode(); // ^ 2
    if (bcc != null)
        for (Address x : bcc)
            result = result * 37 ^ x.toString().hashCode(); // ^ 4
    if (from != null)
        for (Address x : from)
            result = result * 37 ^ x.toString().hashCode();
    // without ^ 1,2,4 above a single email addr in either to/cc/bcc will result in same hash value.
    // but changing the code here now will affect existing archives.

    return result;
}

From source file:org.nuxeo.ecm.platform.mail.listener.action.ExtractMessageInformationAction.java

@Override
public boolean execute(ExecutionContext context) {
    bodyContent = "";

    boolean copyMessage = Boolean.parseBoolean(Framework.getProperty(COPY_MESSAGE, "false"));

    try {/*from w w  w  .  jav a2 s  .co  m*/
        Message originalMessage = context.getMessage();
        if (log.isDebugEnabled()) {
            log.debug("Transforming message, original subject: " + originalMessage.getSubject());
        }

        // fully load the message before trying to parse to
        // override most of server bugs, see
        // http://java.sun.com/products/javamail/FAQ.html#imapserverbug
        Message message;
        if (originalMessage instanceof MimeMessage && copyMessage) {
            message = new MimeMessage((MimeMessage) originalMessage);
            if (log.isDebugEnabled()) {
                log.debug("Transforming message after full load: " + message.getSubject());
            }
        } else {
            // stuck with the original one
            message = originalMessage;
        }

        // Subject
        String subject = message.getSubject();
        if (subject != null) {
            subject = subject.trim();
        }
        if (subject == null || "".equals(subject)) {
            subject = "<Unknown>";
        }
        context.put(SUBJECT_KEY, subject);

        // Sender
        try {
            Address[] from = message.getFrom();
            String sender = null;
            String senderEmail = null;
            if (from != null) {
                Address addr = from[0];
                if (addr instanceof InternetAddress) {
                    InternetAddress iAddr = (InternetAddress) addr;
                    senderEmail = iAddr.getAddress();
                    sender = iAddr.getPersonal() + " <" + senderEmail + ">";
                } else {
                    sender += addr.toString();
                    senderEmail = sender;
                }
            }
            context.put(SENDER_KEY, sender);
            context.put(SENDER_EMAIL_KEY, senderEmail);
        } catch (AddressException ae) {
            // try to parse sender from header instead
            String[] values = message.getHeader("From");
            if (values != null) {
                context.put(SENDER_KEY, values[0]);
            }
        }
        // Sending date
        context.put(SENDING_DATE_KEY, message.getSentDate());

        // Recipients
        try {
            Address[] to = message.getRecipients(Message.RecipientType.TO);
            Collection<String> recipients = new ArrayList<String>();
            if (to != null) {
                for (Address addr : to) {
                    if (addr instanceof InternetAddress) {
                        InternetAddress iAddr = (InternetAddress) addr;
                        if (iAddr.getPersonal() != null) {
                            recipients.add(iAddr.getPersonal() + " <" + iAddr.getAddress() + ">");
                        } else {
                            recipients.add(iAddr.getAddress());
                        }
                    } else {
                        recipients.add(addr.toString());
                    }
                }
            }
            context.put(RECIPIENTS_KEY, recipients);
        } catch (AddressException ae) {
            // try to parse recipient from header instead
            Collection<String> recipients = getHeaderValues(message, Message.RecipientType.TO.toString());
            context.put(RECIPIENTS_KEY, recipients);
        }

        // CC recipients

        try {
            Address[] toCC = message.getRecipients(Message.RecipientType.CC);
            Collection<String> ccRecipients = new ArrayList<String>();
            if (toCC != null) {
                for (Address addr : toCC) {
                    if (addr instanceof InternetAddress) {
                        InternetAddress iAddr = (InternetAddress) addr;
                        ccRecipients.add(iAddr.getPersonal() + " " + iAddr.getAddress());
                    } else {
                        ccRecipients.add(addr.toString());
                    }
                }
            }
            context.put(CC_RECIPIENTS_KEY, ccRecipients);

        } catch (AddressException ae) {
            // try to parse ccRecipient from header instead
            Collection<String> ccRecipients = getHeaderValues(message, Message.RecipientType.CC.toString());
            context.put(CC_RECIPIENTS_KEY, ccRecipients);
        }
        String[] messageIdHeader = message.getHeader("Message-ID");
        if (messageIdHeader != null) {
            context.put(MailCoreConstants.MESSAGE_ID_KEY, messageIdHeader[0]);
        }

        MimetypeRegistry mimeService = (MimetypeRegistry) context.getInitialContext().get(MIMETYPE_SERVICE_KEY);

        List<Blob> blobs = new ArrayList<Blob>();
        context.put(ATTACHMENTS_KEY, blobs);

        // String[] cte = message.getHeader("Content-Transfer-Encoding");

        // process content
        getAttachmentParts(message, subject, mimeService, context);

        context.put(TEXT_KEY, bodyContent);

        return true;
    } catch (MessagingException | IOException e) {
        log.error(e, e);
    }
    return false;
}

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

private void copyAddresses(Address[] source, Collection<Address> target) {
    if (source != null) {
        for (Address address : source) {
            if (address == null) {
                continue;
            }//w w  w.j  av a2  s  . c  om

            String email;

            if (address instanceof InternetAddress) {
                email = ((InternetAddress) address).getAddress();
            } else {
                email = address.toString();
            }

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

            target.add(address);
        }
    }
}

From source file:org.jasig.portlet.emailpreview.dao.javamail.JavamailAccountDaoImpl.java

private String getFormattedAddresses(Address[] addresses) {
    List<String> recipientsList = new ArrayList<String>();
    String receiver = null;/*from  w w  w.  ja  va 2  s  .  co m*/
    if (addresses != null && addresses.length != 0) {
        for (Address adress : addresses) {
            if (INTERNET_ADDRESS_TYPE.equals(adress.getType())) {
                InternetAddress inet = (InternetAddress) adress;
                receiver = inet.toUnicodeString();
            } else {
                receiver = adress.toString();
            }
            recipientsList.add(receiver);
        }
    }
    return StringUtils.join(recipientsList, "; ").replaceAll("<", "&lt;").replaceAll(">", "&gt;");
}