Example usage for javax.mail.internet InternetAddress validate

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

Introduction

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

Prototype

public void validate() throws AddressException 

Source Link

Document

Validate that this address conforms to the syntax rules of RFC 822.

Usage

From source file:edu.gmu.csd.validation.Validation.java

public void validateEmailAddress(FacesContext context, UIComponent componentToValidate, Object value)
        throws ValidationException {
    boolean isEmailValid = false;
    String emailAddress = (String) value;

    if (emailAddress == null) {
        isEmailValid = false;// w w  w  .j a  va 2 s  .  c o  m
    }

    try {
        InternetAddress emailAddr = new InternetAddress(emailAddress);
        emailAddr.validate();
        isEmailValid = true;
    } catch (AddressException ex) {
        isEmailValid = false;
    }

    if (!isEmailValid) {
        FacesMessage message = new FacesMessage("Your email address should be of valid format.");
        throw new ValidatorException(message);
    }
}

From source file:com.keybox.manage.action.UserPasswordResetAction.java

/**
 * PW Reset Submit//from ww  w. j a  v a2  s . c o  m
 * @return <strong>PW Reset Page</strong>, if PW Reset enabled <br>
  *          <strong>Error Page</strong>, if PW Reset disabled or Email empty
 */
@Action(value = "/pwResetSubmit", results = { @Result(name = "input", location = "/pw_reset.jsp"),
        @Result(name = "error", location = "/error.jsp") })
public String pwResetSubmit() {
    if (pwMailResetEnabled && StringUtils.isNotEmpty(email)) {
        try {
            //EMail Address validate Test
            InternetAddress internetAddress = new InternetAddress(email);
            internetAddress.validate();

            //Reset Password and send mail
            if (UserDB.resetPWMail(email)) {
                addActionMessage(PW_RESET_MASSAGE);
                addActionError(null);
            } else {
                addActionMessage(null);
                addActionError(ERROR_MASSAGE);
            }
        } catch (AddressException e) {
            addActionMessage(null);
            addActionError(INVALID_MAIL_MASSAGE);
        }
        return INPUT;
    } else {
        return ERROR;
    }
}

From source file:ome.services.mail.MailUtil.java

/**
 * Helper Validate that this address conforms to the syntax rules of RFC
 * 822./*from  w  w  w .jav  a  2  s  . co  m*/
 *
 * @param email
 *            email address
 */
public boolean validateEmail(String email) {
    boolean isValid = true;
    try {
        InternetAddress internetAddress = new InternetAddress(email);
        internetAddress.validate();
    } catch (AddressException e) {
        isValid = false;
    }
    return isValid;
}

From source file:de.kaffeeshare.server.NamespaceCheck.java

private JSONObject checkNamespace(String namespace) {
    JSONObject json = new JSONObject();
    try {//w ww  . java 2s. c  o  m

        // By convention, all namespaces starting with "_" (underscore) are reserved for system use.
        if (namespace.charAt(0) == '_') {
            json.put("status", "error");
            return json;
        }

        // check if namespace is valid 
        try {
            DatastoreManager.setNamespace(namespace);
        } catch (Exception e) {
            json.put("status", "error");
            return json;
        }

        // check if email and jabber address are valid!
        // I believe a valid email address also a valid jabber address
        // so I only check for valid email address
        try {
            InternetAddress emailAddr = new InternetAddress(namespace + "@abc.com");
            emailAddr.validate();
        } catch (AddressException ex) {
            json.put("status", "error");
            return json;
        }

        // check if namespace is empty
        if (!DatastoreManager.getDatastore().isEmpty()) {
            json.put("status", "use");
            return json;
        }

        json.put("status", "success");
        return json;
    } catch (JSONException e) {
        log.warning("JSON exception @ namespace check");
        e.printStackTrace();
        return null;
    }
}

From source file:business.controllers.LabController.java

public void transferLabData(Lab body, Lab lab) {
    lab.setName(body.getName());/*from  w ww.j av a  2s .  co m*/
    lab.setHubAssistanceEnabled(body.isHubAssistanceEnabled());
    if (lab.getContactData() == null) {
        lab.setContactData(new ContactData());
    }
    lab.getContactData().copy(body.getContactData());
    Set<String> emailAddresses = new LinkedHashSet<>();
    for (String email : body.getEmailAddresses()) {
        try {
            InternetAddress address = new InternetAddress(email);
            address.validate();
            emailAddresses.add(email.trim().toLowerCase());
        } catch (AddressException e) {
            throw new EmailAddressInvalid(email);
        }
    }
    lab.setEmailAddresses(new ArrayList<>(emailAddresses));
}

From source file:models.services.Email.java

/**
 * The constructor of the Service Email.
 *
 * @param address the email address./*from www. ja  v a 2s .c  o  m*/
 * @param muteNotifications whether or not the notifications should be enabled
 * for this email address.
 * @param validated whether or not this email address is validated.
 * @throws javax.mail.internet.AddressException
 */
public Email(InternetAddress address, boolean muteNotifications, boolean validated) throws AddressException {
    super(muteNotifications, KEY, validated);
    address.validate();
    if (address == null) {
        throw new IllegalArgumentException("Email address can't be null.");
    }
    this.emailAddres = address;
}

From source file:net.timbusproject.extractors.pojo.CallBack.java

private boolean isValidEmailAddress(String email) {
    boolean result = true;
    try {//from  ww  w  .jav  a  2s  . c  o m
        InternetAddress emailAddr = new InternetAddress(email);
        emailAddr.validate();
    } catch (AddressException ex) {
        result = false;
    }
    if (result)
        System.out.println("The e-mail " + email + " adress is valid.");
    else
        System.out.println("The e-mail " + email + " adress is not valid");
    return result;
}

From source file:org.haiku.haikudepotserver.dataobjects.User.java

@Override
protected void validateForSave(ValidationResult validationResult) {
    super.validateForSave(validationResult);

    if (null == getIsRoot()) {
        setIsRoot(Boolean.FALSE);
    }/*from www  .j  a v  a 2 s. c o  m*/

    if (null != getNickname()) {
        if (!NICKNAME_PATTERN.matcher(getNickname()).matches()) {
            validationResult.addFailure(new BeanValidationFailure(this, NICKNAME.getName(), "malformed"));
        }
    }

    if (null != getPasswordHash()) {
        if (!PASSWORDHASH_PATTERN.matcher(getPasswordHash()).matches()) {
            validationResult.addFailure(new BeanValidationFailure(this, PASSWORD_HASH.getName(), "malformed"));
        }
    }

    if (null != getPasswordSalt()) {
        if (!PASSWORDSALT_PATTERN.matcher(getPasswordSalt()).matches()) {
            validationResult.addFailure(new BeanValidationFailure(this, PASSWORD_HASH.getName(), "malformed"));
        }
    }

    if (null != getEmail()) {
        try {
            InternetAddress internetAddress = new InternetAddress(getEmail());
            internetAddress.validate();
        } catch (AddressException ae) {
            validationResult.addFailure(new BeanValidationFailure(this, EMAIL.getName(), "malformed"));
        }
    }

}

From source file:org.codice.alliance.core.email.impl.EmailSenderImpl.java

/** sendEmail method sends email after receiving input parameters */
@Override//from ww w.j a v a2s. c om
public void sendEmail(String fromEmail, String toEmail, String subject, String body,
        List<Pair<String, InputStream>> attachments) throws IOException {
    notNull(fromEmail, "fromEmail must be non-null");
    notNull(toEmail, "toEmail must be non-null");
    notNull(subject, "subject must be non-null");
    notNull(body, "body must be non-null");
    notNull(attachments, "attachments must be non-null");

    if (StringUtils.isBlank(mailHost)) {
        throw new IOException("the mail server hostname has not been configured");
    }

    List<File> tempFiles = new LinkedList<>();

    try {
        InternetAddress emailAddr = new InternetAddress(toEmail);
        emailAddr.validate();

        Properties properties = createSessionProperties();

        Session session = Session.getDefaultInstance(properties);

        MimeMessage mimeMessage = new MimeMessage(session);
        mimeMessage.setFrom(new InternetAddress(fromEmail));
        mimeMessage.addRecipient(Message.RecipientType.TO, emailAddr);
        mimeMessage.setSubject(subject);

        BodyPart messageBodyPart = new MimeBodyPart();
        messageBodyPart.setText(body);

        Multipart multipart = new MimeMultipart();
        multipart.addBodyPart(messageBodyPart);

        Holder<Long> bytesWritten = new Holder<>(0L);

        for (Pair<String, InputStream> attachment : attachments) {

            messageBodyPart = new MimeBodyPart();
            File file = File.createTempFile("email-sender-", ".dat");
            tempFiles.add(file);

            copyDataToTempFile(file, attachment.getValue(), bytesWritten);
            messageBodyPart.setDataHandler(new DataHandler(new FileDataSource(file)));
            messageBodyPart.setFileName(attachment.getKey());
            multipart.addBodyPart(messageBodyPart);
        }

        mimeMessage.setContent(multipart);

        send(mimeMessage);

        LOGGER.debug("Email sent to " + toEmail);

    } catch (AddressException e) {
        throw new IOException("invalid email address: email=" + toEmail, e);
    } catch (MessagingException e) {
        throw new IOException("message error occurred on send", e);
    } finally {
        tempFiles.forEach(file -> {
            if (!file.delete()) {
                LOGGER.debug("unable to delete tmp file: path={}", file);
            }
        });
    }
}

From source file:models.services.Email.java

/**
 * The constructor of Email, only requiring the email address to be filled
 * in.//from  ww  w.  ja va2  s  . c  o  m
 *
 * @param address the email address.
 * @throws javax.mail.internet.AddressException
 */
public Email(InternetAddress address) throws AddressException {
    super(false, KEY, false);
    if (address == null) {
        throw new IllegalArgumentException("Email address can't be null.");
    }
    address.validate();
    this.emailAddres = address;
}