Example usage for javax.mail.internet InternetAddress getPersonal

List of usage examples for javax.mail.internet InternetAddress getPersonal

Introduction

In this page you can find the example usage for javax.mail.internet InternetAddress getPersonal.

Prototype

public String getPersonal() 

Source Link

Document

Get the personal name.

Usage

From source file:com.icegreen.greenmail.store.SimpleMessageAttributes.java

/**
 * Parses a String email address to an IMAP address string.
 *//*from w  w w . java 2  s.c  o  m*/
String parseAddress(String address) {
    int comma = address.indexOf(',');
    StringBuilder buf = new StringBuilder();
    if (comma == -1) { //single address
        buf.append(LB);
        InternetAddress netAddr;
        try {
            netAddr = new InternetAddress(address);
        } catch (AddressException ae) {
            return null;
        }
        String personal = netAddr.getPersonal();
        if (personal != null && (personal.length() != 0)) {
            buf.append(Q).append(personal).append(Q);
        } else {
            buf.append(NIL);
        }
        buf.append(SP);
        buf.append(NIL); // should add route-addr
        buf.append(SP);
        try {
            MailAddress mailAddr = new MailAddress(netAddr.getAddress());
            buf.append(Q).append(mailAddr.getUser()).append(Q);
            buf.append(SP);
            buf.append(Q).append(mailAddr.getHost()).append(Q);
        } catch (Exception pe) {
            buf.append(NIL + SP + NIL);
        }
        buf.append(RB);
    } else {
        buf.append(parseAddress(address.substring(0, comma)));
        buf.append(SP);
        buf.append(parseAddress(address.substring(comma + 1)));
    }
    return buf.toString();
}

From source file:com.duroty.application.files.manager.StoreManager.java

/**
 * DOCUMENT ME!//  w w  w  .  j  a v  a2  s.c o  m
 *
 * @param hsession DOCUMENT ME!
 * @param session DOCUMENT ME!
 * @param repositoryName DOCUMENT ME!
 * @param identity DOCUMENT ME!
 * @param to DOCUMENT ME!
 * @param cc DOCUMENT ME!
 * @param bcc DOCUMENT ME!
 * @param subject DOCUMENT ME!
 * @param body DOCUMENT ME!
 * @param attachments DOCUMENT ME!
 * @param isHtml DOCUMENT ME!
 * @param charset DOCUMENT ME!
 * @param headers DOCUMENT ME!
 * @param priority DOCUMENT ME!
 *
 * @throws MailException DOCUMENT ME!
 */
public void send(org.hibernate.Session hsession, Session session, String repositoryName, Vector files,
        int label, String charset) throws FilesException {
    ByteArrayInputStream bais = null;
    FileOutputStream fos = null;

    try {
        if ((files == null) || (files.size() <= 0)) {
            return;
        }

        if (charset == null) {
            charset = MimeUtility.javaCharset(Charset.defaultCharset().displayName());
        }

        Users user = getUser(hsession, repositoryName);
        Identity identity = getDefaultIdentity(hsession, user);

        InternetAddress _returnPath = new InternetAddress(identity.getIdeEmail(), identity.getIdeName());
        InternetAddress _from = new InternetAddress(identity.getIdeEmail(), identity.getIdeName());
        InternetAddress _replyTo = new InternetAddress(identity.getIdeReplyTo(), identity.getIdeName());
        InternetAddress _to = new InternetAddress(identity.getIdeEmail(), identity.getIdeName());

        for (int i = 0; i < files.size(); i++) {
            MultiPartEmail email = email = new MultiPartEmail();
            email.setCharset(charset);

            if (_from != null) {
                email.setFrom(_from.getAddress(), _from.getPersonal());
            }

            if (_returnPath != null) {
                email.addHeader("Return-Path", _returnPath.getAddress());
                email.addHeader("Errors-To", _returnPath.getAddress());
                email.addHeader("X-Errors-To", _returnPath.getAddress());
            }

            if (_replyTo != null) {
                email.addReplyTo(_replyTo.getAddress(), _replyTo.getPersonal());
            }

            if (_to != null) {
                email.addTo(_to.getAddress(), _to.getPersonal());
            }

            MailPartObj obj = (MailPartObj) files.get(i);

            email.setSubject("Files-System " + obj.getName());

            Date now = new Date();
            email.setSentDate(now);

            File dir = new File(System.getProperty("user.home") + File.separator + "tmp");

            if (!dir.exists()) {
                dir.mkdir();
            }

            File file = new File(dir, obj.getName());

            bais = new ByteArrayInputStream(obj.getAttachent());
            fos = new FileOutputStream(file);
            IOUtils.copy(bais, fos);

            IOUtils.closeQuietly(bais);
            IOUtils.closeQuietly(fos);

            EmailAttachment attachment = new EmailAttachment();
            attachment.setPath(file.getPath());
            attachment.setDisposition(EmailAttachment.ATTACHMENT);
            attachment.setDescription("File Attachment: " + file.getName());
            attachment.setName(file.getName());

            email.attach(attachment);

            String mid = getId();
            email.addHeader(RFC2822Headers.IN_REPLY_TO, "<" + mid + ".JavaMail.duroty@duroty" + ">");
            email.addHeader(RFC2822Headers.REFERENCES, "<" + mid + ".JavaMail.duroty@duroty" + ">");

            email.addHeader("X-DBox", "FILES");

            email.addHeader("X-DRecent", "false");

            //email.setMsg(body);
            email.setMailSession(session);

            email.buildMimeMessage();

            MimeMessage mime = email.getMimeMessage();

            int size = MessageUtilities.getMessageSize(mime);

            if (!controlQuota(hsession, user, size)) {
                throw new MailException("ErrorMessages.mail.quota.exceded");
            }

            messageable.storeMessage(mid, mime, user);
        }
    } catch (FilesException e) {
        throw e;
    } catch (Exception e) {
        throw new FilesException(e);
    } catch (java.lang.OutOfMemoryError ex) {
        System.gc();
        throw new FilesException(ex);
    } catch (Throwable e) {
        throw new FilesException(e);
    } finally {
        GeneralOperations.closeHibernateSession(hsession);
        IOUtils.closeQuietly(bais);
        IOUtils.closeQuietly(fos);
    }
}

From source file:com.duroty.service.Mailet.java

/**
 * DOCUMENT ME!//from ww w .  jav  a  2  s .  c o m
 *
 * @param hfactory DOCUMENT ME!
 * @param username DOCUMENT ME!
 * @param mime DOCUMENT ME!
 */
private void parseContacts(Session hsession, Users user, MimeMessage mime, String box) {
    try {
        Address[] addresses = null;

        Date sentDate = null;
        Date receivedDate = null;

        if (box.equals("SENT")) {
            addresses = mime.getAllRecipients();
            sentDate = mime.getSentDate();

            if (sentDate == null) {
                sentDate = new Date();
            }
        } else {
            addresses = mime.getFrom();
            receivedDate = mime.getReceivedDate();

            if (receivedDate == null) {
                receivedDate = new Date();
            }
        }

        if ((addresses != null) && (addresses.length > 0)) {
            String name = null;
            String email = null;

            for (int i = 0; i < addresses.length; i++) {
                if (addresses[i] instanceof InternetAddress) {
                    InternetAddress xinet = (InternetAddress) addresses[i];

                    name = xinet.getPersonal();

                    if ((name != null) && (name.length() > 49)) {
                        name = name.substring(0, 49);
                    }

                    email = xinet.getAddress();
                } else {
                    email = addresses[i].toString();
                }

                Criteria crit1 = hsession.createCriteria(Contact.class);
                crit1.add(Restrictions.eq("users", user));
                crit1.add(Restrictions.eq("conEmail", email));

                Contact contact = (Contact) crit1.uniqueResult();

                if (contact != null) {
                    if (receivedDate != null) {
                        contact.setConReceivedDate(receivedDate);
                    }

                    if (sentDate != null) {
                        contact.setConSentDate(sentDate);
                    }

                    int freq = contact.getConCount();

                    contact.setConCount(freq + 1);

                    if (!StringUtils.isBlank(name)) {
                        name = name.replaceAll(",", " ");
                        name = name.replaceAll(";", " ");
                        contact.setConName(name);
                    }

                    hsession.update(contact);
                } else {
                    contact = new Contact();
                    contact.setConEmail(email);
                    contact.setConName(name);
                    contact.setConReceivedDate(receivedDate);
                    contact.setConSentDate(sentDate);
                    contact.setConCount(new Integer(1));
                    contact.setUsers(user);

                    hsession.save(contact);
                }

                hsession.flush();

                try {
                    if ((contact.getConSentDate() != null) && (contact.getConReceivedDate() != null)) {
                        Criteria crit2 = hsession.createCriteria(Identity.class);
                        crit2.add(Restrictions.eq("ideEmail", email));
                        crit2.add(Restrictions.eq("ideActive", new Boolean(true)));

                        List list = crit2.list();

                        if (list != null) {
                            Iterator scroll = list.iterator();

                            while (scroll.hasNext()) {
                                Identity identity = (Identity) scroll.next();
                                Users buddy = identity.getUsers();

                                if ((buddy != null) && (user.getUseIdint() != buddy.getUseIdint())) {
                                    Criteria auxCrit = hsession.createCriteria(BuddyList.class);
                                    auxCrit.add(Restrictions.eq("usersByBuliOwnerIdint", user));
                                    auxCrit.add(Restrictions.eq("usersByBuliBuddyIdint", buddy));

                                    BuddyList buddyList = (BuddyList) auxCrit.uniqueResult();

                                    if (buddyList != null) {
                                        buddyList.setBuliActive(true);
                                        buddyList.setBuliLastDate(new Date());
                                        hsession.update(buddyList);
                                    } else {
                                        buddyList = new BuddyList();
                                        buddyList.setBuliActive(true);
                                        buddyList.setBuliLastDate(new Date());
                                        buddyList.setUsersByBuliBuddyIdint(buddy);
                                        buddyList.setUsersByBuliOwnerIdint(user);
                                        hsession.save(buddyList);
                                    }
                                }
                            }
                        }

                        hsession.flush();
                    }
                } catch (Exception e) {
                }
            }
        }
    } catch (Exception e) {
    } finally {
    }
}

From source file:lucee.runtime.net.smtp.SMTPClient.java

private void checkAddress(InternetAddress ia, String charset) { // DIFF 23
    try {//from   w  w  w  .j  a  v  a2s  . co  m
        if (!StringUtil.isEmpty(ia.getPersonal())) {
            String personal = MailUtil.encode(ia.getPersonal(), charset);
            if (!personal.equals(ia.getPersonal()))
                ia.setPersonal(personal);
        }
    } catch (UnsupportedEncodingException e) {
    }
}

From source file:com.duroty.utils.mail.MessageUtilities.java

/**
 * Decode mail addresses into UTF strings.
 *
 * <p>//  w ww . ja va2 s.  c om
 * This routine is necessary because Java Mail Address.toString() routines
 * convert into MIME encoded strings (ASCII C and B encodings), not UTF.
 * Of course, the returned string is in the same format as MIME, but
 * converts to UTF character encodings.
 * </p>decodeAddresses
 *
 * @param addresses The list of addresses to decode
 *
 * @return String List of decoded addresses
 */
public static String decodeAddressesName(Address[] addresses) {
    StringBuffer xlist = new StringBuffer();

    if (addresses != null) {
        for (int xindex = 0; xindex < addresses.length; xindex++) {
            // at this time, only internet addresses can be decoded
            if (xlist.length() > 0) {
                xlist.append(", ");
            }

            if (addresses[xindex] instanceof InternetAddress) {
                InternetAddress xinet = (InternetAddress) addresses[xindex];

                if (xinet.getPersonal() == null) {
                    xlist.append(xinet.getAddress());
                } else {
                    // If the address has a ',' in it, we must
                    // wrap it in quotes, or it will confuse the
                    // code that parses addresses separated by commas.
                    String personal = xinet.getPersonal();
                    int idx = personal.indexOf(",");
                    String qStr = ((idx == -1) ? "" : "\"");
                    xlist.append(qStr);
                    xlist.append(personal);
                    xlist.append(qStr);
                }
            } else {
                // generic, and probably not portable,
                // but what's a man to do...
                xlist.append(addresses[xindex].toString());
            }
        }
    }

    return xlist.toString();
}

From source file:com.duroty.utils.mail.MessageUtilities.java

/**
 * Decode mail addresses into UTF strings.
 *
 * <p>// w w w  . j av  a2  s.c o m
 * This routine is necessary because Java Mail Address.toString() routines
 * convert into MIME encoded strings (ASCII C and B encodings), not UTF.
 * Of course, the returned string is in the same format as MIME, but
 * converts to UTF character encodings.
 * </p>
 *
 * @param addresses The list of addresses to decode
 *
 * @return String List of decoded addresses
 */
public static String decodeAddresses(Address[] addresses) throws Exception {
    StringBuffer xlist = new StringBuffer();

    if (addresses != null) {
        for (int xindex = 0; xindex < addresses.length; xindex++) {
            // at this time, only internet addresses can be decoded
            if (xlist.length() > 0) {
                xlist.append(", ");
            }

            if (addresses[xindex] instanceof InternetAddress) {
                InternetAddress xinet = (InternetAddress) addresses[xindex];

                if (xinet.getPersonal() == null) {
                    xlist.append(xinet.getAddress());
                } else {
                    // If the address has a ',' in it, we must
                    // wrap it in quotes, or it will confuse the
                    // code that parses addresses separated by commas.
                    String personal = xinet.getPersonal();
                    int idx = personal.indexOf(",");
                    String qStr = ((idx == -1) ? "" : "\"");
                    xlist.append(qStr);
                    xlist.append(personal);
                    xlist.append(qStr);
                    xlist.append(" <");
                    xlist.append(xinet.getAddress());
                    xlist.append(">");
                }
            } else {
                // generic, and probably not portable,
                // but what's a man to do...
                xlist.append(addresses[xindex].toString());
            }
        }
    }

    return xlist.toString();
}

From source file:com.duroty.application.chat.manager.ChatManager.java

/**
 * DOCUMENT ME!//from w w  w.  jav  a2s.co m
 *
 * @param hsession DOCUMENT ME!
 * @param userSender DOCUMENT ME!
 * @param userRecipient DOCUMENT ME!
 */
private void sendMail(Session hsession, javax.mail.Session msession, Users userSender, Users userRecipient,
        String message) {
    try {
        String sender = userSender.getUseUsername();
        String recipient = userRecipient.getUseUsername();

        Identity identitySender = getIdentity(hsession, userSender);
        Identity identityRecipient = getIdentity(hsession, userRecipient);

        HtmlEmail email = new HtmlEmail();
        InternetAddress _from = new InternetAddress(identitySender.getIdeEmail(), identitySender.getIdeName());
        InternetAddress _replyTo = new InternetAddress(identitySender.getIdeReplyTo(),
                identitySender.getIdeName());
        InternetAddress[] _to = MessageUtilities.encodeAddresses(identityRecipient.getIdeEmail(), null);

        if (_from != null) {
            email.setFrom(_from.getAddress(), _from.getPersonal());
        }

        if (_replyTo != null) {
            email.addReplyTo(_replyTo.getAddress(), _replyTo.getPersonal());
        }

        if ((_to != null) && (_to.length > 0)) {
            HashSet aux = new HashSet(_to.length);
            Collections.addAll(aux, _from);
            Collections.addAll(aux, _to);
            email.setTo(aux);
        }

        email.setCharset(charset);
        email.setSubject("Chat " + sender + " >> " + recipient);
        email.setHtmlMsg(message);

        calendar.setTime(new Date());

        String minute = "30";

        if (calendar.get(Calendar.MINUTE) >= 30) {
            minute = "60";
        }

        String value = String.valueOf(calendar.get(Calendar.YEAR))
                + String.valueOf(calendar.get(Calendar.MONTH)) + String.valueOf(calendar.get(Calendar.DATE))
                + String.valueOf(calendar.get(Calendar.HOUR_OF_DAY)) + minute
                + String.valueOf(userSender.getUseIdint() + userRecipient.getUseIdint());
        String reference = "<" + value + ".JavaMail.duroty@duroty" + ">";
        email.addHeader(RFC2822Headers.IN_REPLY_TO, reference);
        email.addHeader(RFC2822Headers.REFERENCES, reference);

        email.addHeader("X-DBox", "CHAT");

        Date now = new Date();
        email.setSentDate(now);

        email.setMailSession(msession);
        email.buildMimeMessage();

        MimeMessage mime = email.getMimeMessage();

        int size = MessageUtilities.getMessageSize(mime);

        if (controlQuota(hsession, userSender, size)) {
            //messageable.saveSentMessage(null, mime, userSender);
            Thread thread = new Thread(new SendMessageThread(email));
            thread.start();
        }
    } catch (UnsupportedEncodingException e) {
    } catch (MessagingException e) {
    } catch (EmailException e) {
    } catch (Exception e) {
    }
}

From source file:com.aimluck.eip.mail.util.ALMailUtils.java

/**
 * ??1?????//w ww  .  ja v  a2 s . c om
 *
 * @param addresses
 * @return
 */
public static String getAddressString(Address[] addresses) {
    if (addresses == null || addresses.length <= 0) {
        return "";
    }
    HashSet<String> foundAddress = new HashSet<String>();

    StringBuffer sb = new StringBuffer();
    InternetAddress addr = null;
    int length = addresses.length;
    for (int i = 0; i < length; i++) {
        addr = (InternetAddress) addresses[i];
        if (foundAddress.contains(addr.getAddress())) {
            continue;
        }
        foundAddress.add(addr.getAddress());

        if (addr.getPersonal() != null) {
            String personaladdr = getOneString(getTokens(addr.getPersonal(), "\r\n"), "");
            sb.append(personaladdr).append(" <").append(addr.getAddress()).append(">, ");
        } else {
            sb.append(addr.getAddress()).append(", ");
        }
    }
    String addressStr = sb.toString();
    return addressStr.substring(0, addressStr.length() - 2);
}

From source file:org.agnitas.webservice.EmmWebservice.java

/**
 * Method for update an email-mailing.//www.ja  v  a2  s  .co  m
 * This only creates the mailing, use "link insertContent" to fill in the text and "link sendMailing" to send out the email
 * @param username Username from ws_admin_tbl
 * @param password Password from ws_admin_tbl
 * @param mailingID Id of mailing which should be changed
 * @param shortname Name for the mailing, visible in OpenEMM
 * Not visible to the recipients of the mailing
 * @param description Description (max. 1000 Chars) for the mailing, visible in OpenEMM
 * Not visible to the recipients of the mailing
 * @param mailinglistID Mailinglist-id, must exist in OpenEMM
 * @param targetID Target group id.
 * Possible values:
 * ==0: All subscribers from given mailinglist
 * >0: An existing target group id
 * @param mailingType Type of mailing.
 *
 * Possible values:
 * 0 == normal mailing
 * 1 == Event-based mailing
 * 2 == Rule-based mailing (like automated birthday-mailings)
 *
 * If unsure, say: "0"
 * @param emailSubject Subject-line for the email
 * @param emailSender Sender-address for email.
 * Can be a simple email-address like <CODE>info@agnitas.de</CODE> or with a given realname on the form:
 * <CODE>"AGNITAS AG" <info@agnitas.de></CODE>
 * @param emailReply Reply-to-address for the email
 * @param emailCharset Charater-set to be used for encoding the email.
 * Any character-set JDK 1.4 knows is allowed.
 * Common value is "iso-8859-1"
 * @param emailLinefeed Automated linefeed in text-version of the email.
 * @param emailFormat Format of email.
 *
 * Possible values:
 * 0 == only text
 * 1 == Online-HTML (Multipart)
 * 2 == Offline-HTML (Multipart+embedded graphics)
 * If unsure, say "2"
 * @return true if success
 * @throws java.rmi.RemoteException necessary for Apache Axis
 */
public boolean updateEmailMailing(java.lang.String username, java.lang.String password, int mailingID,
        java.lang.String shortname, java.lang.String description, int mailinglistID, StringArrayType targetID,
        int mailingType, java.lang.String emailSubject, java.lang.String emailSender,
        java.lang.String emailReply, java.lang.String emailCharset, int emailLinefeed, int emailFormat)
        throws java.rmi.RemoteException {
    ApplicationContext con = getWebApplicationContext();
    boolean result = false;
    MailingDao mDao = (MailingDao) con.getBean("MailingDao");
    Mailing aMailing = (Mailing) mDao.getMailing(mailingID, 1);
    MediatypeEmail paramEmail = null;
    MessageContext msct = MessageContext.getCurrentContext();

    if (!authenticateUser(msct, username, password, 1)) {
        return result;
    }

    aMailing.setDescription(description);
    aMailing.setShortname(shortname);
    aMailing.setMailinglistID(mailinglistID);

    Collection targetGroup = new ArrayList();
    for (int i = 0; i < targetID.getX().length; i++) {
        int target = Integer.valueOf(targetID.getX(i)).intValue();
        targetGroup.add(target);
    }

    aMailing.setTargetGroups(targetGroup);
    aMailing.setMailingType(mailingType);
    paramEmail = aMailing.getEmailParam();
    if (paramEmail == null) {
        paramEmail = (MediatypeEmail) con.getBean("MediatypeEmail");
        paramEmail.setCompanyID(1);
        paramEmail.setMailingID(aMailing.getId());
    }
    paramEmail.setStatus(Mediatype.STATUS_ACTIVE);
    paramEmail.setSubject(emailSubject);
    try {
        InternetAddress adr = new InternetAddress(emailSender);

        paramEmail.setFromEmail(adr.getAddress());
        paramEmail.setFromFullname(adr.getPersonal());
    } catch (Exception e) {
        AgnUtils.logger().error("Error in sender address");
    }
    try {
        if (aMailing.getMailTemplateID() == 0 && !emailReply.trim().equalsIgnoreCase("")) {
            InternetAddress adr = new InternetAddress(emailReply);

            paramEmail.setReplyEmail(adr.getAddress());
            paramEmail.setReplyFullname(adr.getPersonal());
        }
    } catch (Exception e) {
        AgnUtils.logger().error("Error in reply address");
    }
    paramEmail.setCharset(emailCharset);
    paramEmail.setMailFormat(emailFormat);
    paramEmail.setLinefeed(emailLinefeed);
    paramEmail.setPriority(1);
    Map mediatypes = aMailing.getMediatypes();

    mediatypes.put(new Integer(0), paramEmail);
    aMailing.setMediatypes(mediatypes);

    try {
        aMailing.buildDependencies(true, con);
        mDao.saveMailing(aMailing);
        result = true;
    } catch (Exception e) {
        AgnUtils.logger().info("Error in create mailing id: " + aMailing.getId() + " msg: " + e);
        result = false;
    }
    return result;
}

From source file:com.duroty.service.Mailet.java

/**
 * DOCUMENT ME!//  w ww .jav a2 s. c  o  m
 *
 * @param username DOCUMENT ME!
 * @param to DOCUMENT ME!
 */
private void sendVacationMessage(String username, String to) {
    SessionFactory hfactory = null;
    Session hsession = null;
    javax.mail.Session msession = null;

    try {
        hfactory = (SessionFactory) ctx.lookup(hibernateSessionFactory);
        hsession = hfactory.openSession();
        msession = (javax.mail.Session) ctx.lookup(smtpSessionFactory);

        Users user = getUser(hsession, username);

        Criteria crit = hsession.createCriteria(Identity.class);
        crit.add(Restrictions.eq("users", getUser(hsession, username)));
        crit.add(Restrictions.eq("ideActive", new Boolean(true)));
        crit.add(Restrictions.eq("ideDefault", new Boolean(true)));

        Identity identity = (Identity) crit.uniqueResult();

        if (identity != null) {
            InternetAddress _from = new InternetAddress(identity.getIdeEmail(), identity.getIdeName());
            InternetAddress _to = InternetAddress.parse(to)[0];

            if (_from.getAddress().equals(_to.getAddress())) {
                return;
            }

            HtmlEmail email = new HtmlEmail();
            email.setMailSession(msession);

            email.setFrom(_from.getAddress(), _from.getPersonal());
            email.addTo(_to.getAddress(), _to.getPersonal());

            Iterator it = user.getMailPreferenceses().iterator();
            MailPreferences mailPreferences = (MailPreferences) it.next();

            email.setSubject(mailPreferences.getMaprVacationSubject());
            email.setHtmlMsg("<p>" + mailPreferences.getMaprVacationBody() + "</p><p>"
                    + mailPreferences.getMaprSignature() + "</p>");

            email.setCharset(Charset.defaultCharset().displayName());

            email.send();
        }
    } catch (Exception e) {
    } finally {
    }
}