Java Code Examples for javax.mail.internet.InternetAddress#getAddress()

The following examples show how to use javax.mail.internet.InternetAddress#getAddress() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: MailUtils.java    From tmxeditor8 with GNU General Public License v2.0 6 votes vote down vote up
/**
 * 用来取得 Email 地址。
 * @param emailAddress
 *            the email address
 * @return String
 * 				例如: emailAddress="John <[email protected]>" 就返回 [email protected]
 */
public static String getAddress(String emailAddress) {
	String result = "";
	if (emailAddress == null) {
		return result;
	}
	try {
		InternetAddress address = new InternetAddress(emailAddress);
		String text = address.getAddress();
		if (text == null) {
			result = emailAddress;
		} else {
			result = text;
		}
	} catch (AddressException e) {
		e.printStackTrace();
		return emailAddress;
	}
	return result;
}
 
Example 2
Source File: MimePackage.java    From ats-framework with Apache License 2.0 6 votes vote down vote up
/**
 * This method resturns only the email address portion of the sender
 * contained in the first From header
 *
 * @return the sender address
 * @throws PackageException
 */
@PublicAtsApi
public String getSenderAddress() throws PackageException {

    try {
        Address[] fromAddresses = message.getFrom();
        if (fromAddresses == null || fromAddresses.length == 0) {
            throw new PackageException("Sender not present");
        }

        InternetAddress fromAddress = (InternetAddress) fromAddresses[0];
        return fromAddress.getAddress();

    } catch (MessagingException me) {
        throw new PackageException(me);
    }
}
 
Example 3
Source File: MailUtils.java    From translationstudio8 with GNU General Public License v2.0 6 votes vote down vote up
/**
 * 用来取得 Email 地址。
 * @param emailAddress
 *            the email address
 * @return String
 * 				例如: emailAddress="John <[email protected]>" 就返回 [email protected]
 */
public static String getAddress(String emailAddress) {
	String result = "";
	if (emailAddress == null) {
		return result;
	}
	try {
		InternetAddress address = new InternetAddress(emailAddress);
		String text = address.getAddress();
		if (text == null) {
			result = emailAddress;
		} else {
			result = text;
		}
	} catch (AddressException e) {
		e.printStackTrace();
		return emailAddress;
	}
	return result;
}
 
Example 4
Source File: MailUtils.java    From scada with MIT License 6 votes vote down vote up
/**
 * ����ʼ�������
 * @param msg �ʼ�����
 * @return ���� <Email��ַ>
 */ 
public static String getFrom(MimeMessage msg) throws MessagingException, UnsupportedEncodingException { 
    String from = ""; 
    Address[] froms = msg.getFrom(); 
    if (froms.length < 1){
    	//return "ϵͳ�ָ�";
        throw new MessagingException("û�з�����!");
    }         
    InternetAddress address = (InternetAddress) froms[0]; 
    String person = address.getPersonal(); 
    if (person != null) { 
        person = MimeUtility.decodeText(person) + " "; 
    } else { 
        person = ""; 
    } 
    from = person + "<" + address.getAddress() + ">"; 
     
    return from; 
}
 
Example 5
Source File: MimeMessageHelper.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
private InternetAddress parseAddress(String address) throws MessagingException {
	InternetAddress[] parsed = InternetAddress.parse(address);
	if (parsed.length != 1) {
		throw new AddressException("Illegal address", address);
	}
	InternetAddress raw = parsed[0];
	try {
		return (getEncoding() != null ?
				new InternetAddress(raw.getAddress(), raw.getPersonal(), getEncoding()) : raw);
	}
	catch (UnsupportedEncodingException ex) {
		throw new MessagingException("Failed to parse embedded personal name to correct encoding", ex);
	}
}
 
Example 6
Source File: MimeMessageHelper.java    From spring-analysis-note with MIT License 5 votes vote down vote up
private InternetAddress parseAddress(String address) throws MessagingException {
	InternetAddress[] parsed = InternetAddress.parse(address);
	if (parsed.length != 1) {
		throw new AddressException("Illegal address", address);
	}
	InternetAddress raw = parsed[0];
	try {
		return (getEncoding() != null ?
				new InternetAddress(raw.getAddress(), raw.getPersonal(), getEncoding()) : raw);
	}
	catch (UnsupportedEncodingException ex) {
		throw new MessagingException("Failed to parse embedded personal name to correct encoding", ex);
	}
}
 
Example 7
Source File: AddressExtractor.java    From james-project with Apache License 2.0 5 votes vote down vote up
private MailAddress toMailAddress(InternetAddress address) throws MessagingException {
    try {
        Optional<MailAddress> specialAddress = getSpecialAddress(address.getAddress());
        if (specialAddress.isPresent()) {
            return specialAddress.get();
        }
        return new MailAddress(address);
    } catch (Exception e) {
        throw new MessagingException("Exception thrown parsing: " + address.getAddress(), e);
    }
}
 
Example 8
Source File: SmtpMail.java    From spacewalk with GNU General Public License v2.0 5 votes vote down vote up
private boolean verifyAddress(InternetAddress addr) {
    log.debug("verifyAddress called ...");
    boolean retval = true;
    String domain = addr.getAddress();
    int domainStart = domain.indexOf('@');
    if (domainStart > -1 && domainStart + 1 < domain.length()) {
        domain = domain.substring(domainStart + 1);

    }
    if (log.isDebugEnabled()) {
        log.debug("Restricted domains: " +
                StringUtils.join(restrictedDomains, " | "));
        log.debug("disallowedDomains domains: " +
                StringUtils.join(disallowedDomains, " | "));
    }
    if (restrictedDomains != null && restrictedDomains.length > 0) {
        if (ArrayUtils.lastIndexOf(restrictedDomains, domain) == -1) {
            log.warn("Address " + addr.getAddress() +
                    " not in restricted domains list");
            retval = false;
        }
    }

    if (retval &&  disallowedDomains != null && disallowedDomains.length > 0) {
        if (ArrayUtils.lastIndexOf(disallowedDomains, domain) > -1) {
            log.warn("Address " + addr.getAddress() + " in disallowed domains list");
            retval = false;
        }
    }
    log.debug("verifyAddress returning: " + retval);
    return retval;
}
 
Example 9
Source File: MailUtil.java    From document-management-software with GNU Lesser General Public License v3.0 5 votes vote down vote up
/**
 * Extracts the address email
 * 
 * @param a the address
 * @return the email
 */
public static String getAddressEmail(Address a) {
	if (a != null) {
		InternetAddress ia = (InternetAddress) a;
		return ia.getAddress();
	} else {
		return "";
	}
}
 
Example 10
Source File: MailUtil.java    From document-management-software with GNU Lesser General Public License v3.0 5 votes vote down vote up
/**
 * Extracts the address name
 * 
 * @param a the address
 * 
 * @return the name
 */
public static String getAddressName(Address a) {
	if (a != null) {
		InternetAddress ia = (InternetAddress) a;

		if (ia.getPersonal() != null) {
			return ia.getPersonal();
		} else {
			return ia.getAddress();
		}
	} else {
		return "";
	}
}
 
Example 11
Source File: SmtpMail.java    From uyuni with GNU General Public License v2.0 5 votes vote down vote up
private boolean verifyAddress(InternetAddress addr) {
    log.debug("verifyAddress called ...");
    boolean retval = true;
    String domain = addr.getAddress();
    int domainStart = domain.indexOf('@');
    if (domainStart > -1 && domainStart + 1 < domain.length()) {
        domain = domain.substring(domainStart + 1);

    }
    if (log.isDebugEnabled()) {
        log.debug("Restricted domains: " +
                StringUtils.join(restrictedDomains, " | "));
        log.debug("disallowedDomains domains: " +
                StringUtils.join(disallowedDomains, " | "));
    }
    if (restrictedDomains != null && restrictedDomains.length > 0) {
        if (ArrayUtils.lastIndexOf(restrictedDomains, domain) == -1) {
            log.warn("Address " + addr.getAddress() +
                    " not in restricted domains list");
            retval = false;
        }
    }

    if (retval &&  disallowedDomains != null && disallowedDomains.length > 0) {
        if (ArrayUtils.lastIndexOf(disallowedDomains, domain) > -1) {
            log.warn("Address " + addr.getAddress() + " in disallowed domains list");
            retval = false;
        }
    }
    log.debug("verifyAddress returning: " + retval);
    return retval;
}
 
Example 12
Source File: Forward.java    From james-project with Apache License 2.0 5 votes vote down vote up
private MailAddress toMailAddress(InternetAddress address) throws MessagingException {
    try {
        Optional<MailAddress> specialAddress = AddressExtractor.withContext(getMailetContext())
                .allowedSpecials(ALLOWED_SPECIALS)
                .getSpecialAddress(address.getAddress());
        if (specialAddress.isPresent()) {
            return specialAddress.get();
        }
        return new MailAddress(address);
    } catch (Exception e) {
        throw new MessagingException("Exception thrown in getRecipients() parsing: " + address.getAddress());
    }
}
 
Example 13
Source File: MessageHelper.java    From FairEmail with GNU General Public License v3.0 5 votes vote down vote up
static String getSortKey(Address[] addresses) {
    if (addresses == null || addresses.length == 0)
        return null;
    InternetAddress address = (InternetAddress) addresses[0];
    // Sort on name will result in inconsistent results
    // because the sender name and sender contact name can differ
    return address.getAddress();
}
 
Example 14
Source File: Shortcuts.java    From FairEmail with GNU General Public License v3.0 5 votes vote down vote up
@NotNull
static ShortcutInfoCompat.Builder getShortcut(Context context, InternetAddress address) {
    String name = address.getPersonal();
    String email = address.getAddress();

    Uri lookupUri = null;
    boolean contacts = Helper.hasPermission(context, Manifest.permission.READ_CONTACTS);
    if (contacts) {
        ContentResolver resolver = context.getContentResolver();
        try (Cursor cursor = resolver.query(ContactsContract.CommonDataKinds.Email.CONTENT_URI,
                new String[]{
                        ContactsContract.CommonDataKinds.Photo.CONTACT_ID,
                        ContactsContract.Contacts.LOOKUP_KEY,
                        ContactsContract.Contacts.DISPLAY_NAME
                },
                ContactsContract.CommonDataKinds.Email.ADDRESS + " = ?",
                new String[]{email}, null)) {
            if (cursor != null && cursor.moveToNext()) {
                int colContactId = cursor.getColumnIndex(ContactsContract.CommonDataKinds.Photo.CONTACT_ID);
                int colLookupKey = cursor.getColumnIndex(ContactsContract.Contacts.LOOKUP_KEY);
                int colDisplayName = cursor.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME);

                long contactId = cursor.getLong(colContactId);
                String lookupKey = cursor.getString(colLookupKey);
                String displayName = cursor.getString(colDisplayName);

                lookupUri = ContactsContract.Contacts.getLookupUri(contactId, lookupKey);
                if (!TextUtils.isEmpty(displayName))
                    name = displayName;
            }
        }
    }

    return getShortcut(context, email, name, lookupUri);
}
 
Example 15
Source File: MimeMessageHelper.java    From java-technology-stack with MIT License 5 votes vote down vote up
private InternetAddress parseAddress(String address) throws MessagingException {
	InternetAddress[] parsed = InternetAddress.parse(address);
	if (parsed.length != 1) {
		throw new AddressException("Illegal address", address);
	}
	InternetAddress raw = parsed[0];
	try {
		return (getEncoding() != null ?
				new InternetAddress(raw.getAddress(), raw.getPersonal(), getEncoding()) : raw);
	}
	catch (UnsupportedEncodingException ex) {
		throw new MessagingException("Failed to parse embedded personal name to correct encoding", ex);
	}
}
 
Example 16
Source File: MediatypeEmailImpl.java    From openemm with GNU Affero General Public License v3.0 5 votes vote down vote up
/**
 * Getter for property replyAdr.
 * 
 * @return Value of property replyAdr.
 */
@Override
public String getReplyAdr() throws Exception {
	InternetAddress tmpReply = new InternetAddress(replyEmail, replyFullname, charset);
	if (StringUtils.isNotBlank(tmpReply.getPersonal())) {
		return tmpReply.getPersonal() + " <" + tmpReply.getAddress() + ">";
	} else {
		return tmpReply.getAddress();
	}
}
 
Example 17
Source File: MediatypeEmailImpl.java    From openemm with GNU Affero General Public License v3.0 5 votes vote down vote up
@Override
public String getFromAdr() throws Exception {
	InternetAddress tmpFrom = new InternetAddress(fromEmail, fromFullname, charset);
	if (StringUtils.isNotBlank(tmpFrom.getPersonal())) {
		return tmpFrom.getPersonal() + " <" + tmpFrom.getAddress() + ">";
	} else {
		return tmpFrom.getAddress();
	}
}
 
Example 18
Source File: MessageHelper.java    From FairEmail with GNU General Public License v3.0 4 votes vote down vote up
static String formatAddresses(Address[] addresses, boolean full, boolean compose) {
    if (addresses == null || addresses.length == 0)
        return "";

    List<String> formatted = new ArrayList<>();
    for (int i = 0; i < addresses.length; i++) {
        boolean duplicate = false;
        for (int j = 0; j < i; j++)
            if (addresses[i].equals(addresses[j])) {
                duplicate = true;
                break;
            }
        if (duplicate)
            continue;

        if (addresses[i] instanceof InternetAddress) {
            InternetAddress address = (InternetAddress) addresses[i];
            String email = address.getAddress();
            String personal = address.getPersonal();

            if (TextUtils.isEmpty(personal))
                formatted.add(email);
            else {
                if (compose) {
                    boolean quote = false;
                    personal = personal.replace("\"", "");
                    for (int c = 0; c < personal.length(); c++)
                        // https://tools.ietf.org/html/rfc822
                        if ("()<>@,;:\\\".[]".indexOf(personal.charAt(c)) >= 0) {
                            quote = true;
                            break;
                        }
                    if (quote)
                        personal = "\"" + personal + "\"";
                }

                if (full)
                    formatted.add(personal + " <" + email + ">");
                else
                    formatted.add(personal);
            }
        } else
            formatted.add(addresses[i].toString());
    }
    return TextUtils.join(", ", formatted);
}
 
Example 19
Source File: MailingWizardForm.java    From openemm with GNU Affero General Public License v3.0 4 votes vote down vote up
/**
 * Validate the properties that have been set from this HTTP request,
 * and return an <code>ActionErrors</code> object that encapsulates any
 * validation errors that have been found.  If no errors are found, return
 * <code>null</code> or an <code>ActionErrors</code> object with no
 * recorded error messages.
 * 
 * @param mapping The mapping used to select this instance
 * @param request The servlet request we are processing
 * @return errors
 */
@Override
public ActionErrors formSpecificValidate(ActionMapping mapping,
        HttpServletRequest request) {
	ActionErrors errors = new ActionErrors();

    if (MailingWizardAction.ACTION_NAME.equals(this.action) &&
            StringUtils.length(this.getMailing().getShortname()) < 3) {
        errors.add("shortname", new ActionMessage("error.name.too.short"));
    }
    
    if (this.action.equals(MailingWizardAction.ACTION_SENDADDRESS)) {
        if (StringUtils.length(getReplyFullname()) > 255) {
            errors.add("replyFullname", new ActionMessage("error.reply_fullname_too_long"));
        }
        if (StringUtils.length(getSenderFullname()) > 255) {
            errors.add("senderFullname", new ActionMessage("error.sender_fullname_too_long"));
        }
        if (StringUtils.length(getSenderFullname())== 0) {
            this.replyFullname = getSenderFullname();
        }
        if (StringUtils.length(senderEmail) < 3) {
            errors.add("shortname", new ActionMessage("error.invalid.email"));
        }
        try {
            InternetAddress adr = new InternetAddress(senderEmail);
            String email = adr.getAddress();
            if (!AgnUtils.isEmailValid(email)) {
                errors.add("sender", new ActionMessage("error.mailing.sender_adress"));
            }
        } catch (Exception e) {
            if (!StringUtils.contains(senderEmail, "[agn")) {
                errors.add("sender", new ActionMessage("error.mailing.sender_adress"));
            }
        }
    }

    if (action.equals(MailingWizardAction.ACTION_SUBJECT) && getEmailSubject().length() < 2) {
        errors.add("subject", new ActionMessage("error.mailing.subject.too_short"));
    }

    if (mailing != null && (MailingWizardAction.ACTION_TARGET.equalsIgnoreCase(action) ||
            MailingWizardAction.ACTION_FINISH.equalsIgnoreCase(action))) {
	  if ((mailing.getTargetGroups() == null ||
              mailing.getTargetGroups().isEmpty() ) && getTargetID() == 0  && mailing.getMailingType() == MailingTypes.DATE_BASED.getCode()) {
          errors.add("global", new ActionMessage("error.mailing.rulebased_without_target"));
      }
	}
    
    return errors;
}
 
Example 20
Source File: SenderRecipientTest.java    From greenmail with Apache License 2.0 2 votes vote down vote up
/**
 * Retrieve mail through IMAP and POP3 and check sender and receivers
 *
 * @param greenMail Greenmail instance to read from
 * @param addr      Address of account to retrieve
 */
private void retrieveAndCheck(GreenMailRule greenMail, InternetAddress addr) throws IOException, MessagingException {
    String address = addr.getAddress();
    retrieveAndCheck(greenMail.getPop3(), address);
    retrieveAndCheck(greenMail.getImap(), address);
}