Example usage for javax.mail.internet InternetAddress getAddress

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

Introduction

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

Prototype

public String getAddress() 

Source Link

Document

Get the email address.

Usage

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

/**
 * Decode mail addresses into UTF strings.
 *
 * <p>/*from  w  w  w.java 2s  . 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>decodeAddresses
 *
 * @param addresses The list of addresses to decode
 *
 * @return String List of decoded addresses
 */
public static String decodeAddressesEmail(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];

                String email = xinet.getAddress();
                int idx = email.indexOf(",");
                String qStr = ((idx == -1) ? "" : "\"");
                xlist.append(qStr);
                xlist.append(email);
                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.application.chat.manager.ChatManager.java

/**
 * DOCUMENT ME!/*w  ww .j av a2s.  c  o 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

/**
 * ???(??????)??????????//from   www  .  j ava2s. c om
 *
 * @param mailFilter
 * @param subject
 * @param from
 * @param receivers
 * @return boolean
 */
public static boolean isMatchFilter(EipTMailFilter mailFilter, String subject, String from,
        Address[] receivers) {
    String filterType = mailFilter.getFilterType();
    String filterString = mailFilter.getFilterString();
    // int dstFolderId = mailFilter.getEipTMailFolder().getFolderId();

    if (FILTER_TYPE_DOMAIN.equals(filterType)) {
        // ?
        try {
            String[] domainArray = from.split("@");
            String domain = domainArray[domainArray.length - 1];
            return domain.toLowerCase().contains(filterString.toLowerCase());
        } catch (Exception e) {
            return false;
        }
    } else if (FILTER_TYPE_MAILADDRESS.equals(filterType)) {
        // ?
        String[] mailAddrArray = from.split("<");
        String mailAddr = mailAddrArray[mailAddrArray.length - 1];
        return mailAddr.toLowerCase().contains(filterString.toLowerCase());

    } else if (FILTER_TYPE_SUBJECT.equals(filterType)) {
        // ???
        return decodeSubject(subject).toLowerCase().contains(filterString.toLowerCase());
    } else if (FILTER_TYPE_TO.equals(filterType)) {
        for (Address address : receivers) {
            InternetAddress iadress = (InternetAddress) address;
            // String personal = iadress.getPersonal();
            String email = iadress.getAddress();
            if (email.toLowerCase().contains(filterString.toLowerCase())) {
                return true;
            }
        }
        return false;
    }

    return false;
}

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

/**
 * Decode mail addresses into UTF strings.
 *
 * <p>//from   ww w  .  j  a  v a  2 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>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>//from  w  ww  .j a v a 2 s. com
 * 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.aimluck.eip.mail.util.ALMailUtils.java

/**
 * ??1?????//from   w w  w. jav  a 2  s. com
 *
 * @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:ru.org.linux.user.UserDao.java

@Transactional(rollbackFor = Exception.class, propagation = Propagation.REQUIRED)
public int createUser(String name, String nick, String password, String url, InternetAddress mail, String town,
        String info) {//w  w  w.  j  a v a2s . c  o  m
    PasswordEncryptor encryptor = new BasicPasswordEncryptor();

    int userid = jdbcTemplate.queryForInt("select nextval('s_uid') as userid");

    jdbcTemplate.update(
            "INSERT INTO users " + "(id, name, nick, passwd, url, email, town, score, max_score,regdate) "
                    + "VALUES (?,?,?,?,?,?,?,45,45,current_timestamp)",
            userid, name, nick, encryptor.encryptPassword(password), url == null ? null : URLUtil.fixURL(url),
            mail.getAddress(), town);

    if (info != null) {
        setUserInfo(userid, info);
    }

    return userid;
}

From source file:org.agnitas.util.AgnUtils.java

/**
 * Sends the attachment of an email.//from w w  w. j  av  a2  s  . co  m
 */
public static boolean sendEmailAttachment(String from, String to_adrList, String cc_adrList, String subject,
        String txt, byte[] att_data, String att_name, String att_type) {
    boolean result = true;

    try {
        // Create the email message
        MultiPartEmail email = new MultiPartEmail();
        email.setCharset("UTF-8");
        email.setHostName(getSmtpMailRelayHostname());
        email.setFrom(from);
        email.setSubject(subject);
        email.setMsg(txt);

        // bounces and reply forwarded to assistance@agnitas.de
        email.addReplyTo("assistance@agnitas.de");
        email.setBounceAddress("assistance@agnitas.de");

        // Set to-recipient email addresses
        InternetAddress[] toAddresses = getEmailAddressesFromList(to_adrList);
        if (toAddresses != null && toAddresses.length > 0) {
            for (InternetAddress singleAdr : toAddresses) {
                email.addTo(singleAdr.getAddress());
            }
        }

        // Set cc-recipient email addresses
        InternetAddress[] ccAddresses = getEmailAddressesFromList(cc_adrList);
        if (ccAddresses != null && ccAddresses.length > 0) {
            for (InternetAddress singleAdr : ccAddresses) {
                email.addCc(singleAdr.getAddress());
            }
        }

        // Create and add the attachment
        ByteArrayDataSource attachment = new ByteArrayDataSource(att_data, att_type);
        email.attach(attachment, att_name, "EMM-Report");

        // send the email
        email.send();
    } catch (Exception e) {
        logger.error("sendEmailAttachment: " + e.getMessage(), e);
        result = false;
    }

    return result;
}

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

/**
 * Method for update an email-mailing./*w w  w  . jav a2s . c  o  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;
}