Example usage for javax.mail.internet AddressException getMessage

List of usage examples for javax.mail.internet AddressException getMessage

Introduction

In this page you can find the example usage for javax.mail.internet AddressException getMessage.

Prototype

public String getMessage() 

Source Link

Document

Returns the detail message string of this throwable.

Usage

From source file:edu.harvard.med.iccbl.screensaver.io.AdminEmailApplication.java

public void sendAdminEmails(String subject, String msg, Collection<ScreensaverUser> adminUsers,
        File attachedFile) throws MessagingException {
    List<String> failMessages = Lists.newArrayList();
    Set<InternetAddress> adminRecipients = Sets.newHashSet();
    adminRecipients.add(getAdminEmail());

    for (String r : getExtraRecipients()) {
        try {/*from   ww w  . j a  va  2  s .  c  o m*/
            adminRecipients.add(new InternetAddress(r));
        } catch (AddressException e) {
            failMessages.add("Address excption for: " + r + ", " + e.getMessage());
        }
    }

    if (adminUsers != null) {
        for (ScreensaverUser user : adminUsers) {
            String address = user.getEmail();
            if (StringUtils.isEmpty(address))
                failMessages.add("Empty address for the user: " + printUser(user));
            else {
                try {
                    adminRecipients.add(new InternetAddress(address));
                } catch (AddressException e) {
                    failMessages.add("Address excption for user: " + printUser(user) + ", " + e.getMessage());
                }
            }
        }
    }

    EmailService emailService = getEmailServiceBasedOnCommandLineOption();

    try {
        emailService.send(subject, msg.toString(), getAdminEmail(),
                adminRecipients.toArray(new InternetAddress[] {}), (InternetAddress[]) null, attachedFile);
    } catch (IOException e) {
        String errmsg = "Exception when trying to attach the file: " + attachedFile;
        log.warn(errmsg, e);
        failMessages.add(errmsg + ", " + e.getMessage());
    }

    if (!failMessages.isEmpty()) {
        sendFailMessages(subject, msg, failMessages);
    }

}

From source file:edu.harvard.med.iccbl.screensaver.io.AdminEmailApplication.java

public boolean sendEmail(String subject, String msg, ScreensaverUser user) throws MessagingException {
    List<String> failMessages = Lists.newArrayList();
    if (StringUtils.isEmpty(user.getEmail())) {
        failMessages.add("Empty address for the user: " + printUser(user));
    } else {/*from   w  w w.  ja v  a  2 s  .  c  o m*/
        EmailService emailService = getEmailServiceBasedOnCommandLineOption();
        if (isAdminEmailOnly()) {
            sendAdminEmails("Admin email only: " + subject,
                    "originally for: " + printUser(user) + "\nOriginal Message:\n" + msg);
        } else {
            try {
                InternetAddress userAddress = new InternetAddress(user.getEmail());
                emailService.send(subject, msg, getAdminEmail(), new InternetAddress[] { userAddress }, null);
            } catch (AddressException e) {
                failMessages.add("Address exception for user: " + printUser(user) + ", " + e.getMessage());
            }
        }
    }
    if (!failMessages.isEmpty()) {
        sendFailMessages("User message: " + subject, msg, failMessages);
    }
    return failMessages.isEmpty();
}

From source file:edu.harvard.med.iccbl.screensaver.io.AdminEmailApplication.java

/**
 * Send email to the administratorUser (running this program), to the &quot;extra recipients&quot; (specified on the
 * command line), and to the admin accounts, passed in.
 * // w w  w  .  j a  va2  s. c o m
 * @param subject
 * @param msg
 * @throws MessagingException
 */
public boolean sendEmails(String subject, String msg, Collection<? extends ScreensaverUser> users)
        throws MessagingException {
    List<String> failMessages = Lists.newArrayList();
    Set<InternetAddress> recipients = Sets.newHashSet();

    if (users != null) {
        for (ScreensaverUser user : users) {
            String address = user.getEmail();
            if (StringUtils.isEmpty(address))
                failMessages.add("Empty address for the user: " + printUser(user));
            else {
                try {
                    recipients.add(new InternetAddress(address));
                } catch (AddressException e) {
                    failMessages.add("Address excption for user: " + printUser(user) + ", " + e.getMessage());
                }
            }
        }
    }

    if (!recipients.isEmpty()) {
        EmailService emailService = getEmailServiceBasedOnCommandLineOption();

        emailService.send(subject, msg.toString(), getAdminEmail(),
                recipients.toArray(new InternetAddress[] {}), (InternetAddress[]) null);
    }
    if (!failMessages.isEmpty()) {
        sendFailMessages(subject, msg, failMessages);
    }
    return failMessages.isEmpty();
}

From source file:org.apache.hupa.server.handler.AbstractSendMessageHandler.java

@Override
protected GenericResult executeInternal(A action, ExecutionContext context) throws ActionException {
    GenericResult result = new GenericResult();
    try {/*from   ww  w .j  a  v a2 s .  c o m*/

        Message message = createMessage(session, action);
        message = fillBody(message, action);

        sendMessage(getUser(), message);
        saveSentMessage(getUser(), message);

        resetAttachments(action);

        // TODO: notify the user more accurately where the error is
        // if the message was sent and the storage in the sent folder failed, etc.
    } catch (AddressException e) {
        result.setError("Error while parsing recipient: " + e.getMessage());
        logger.error("Error while parsing recipient", e);
    } catch (AuthenticationFailedException e) {
        result.setError("Error while sending message: SMTP Authentication error.");
        logger.error("SMTP Authentication error", e);
    } catch (MessagingException e) {
        result.setError("Error while sending message: " + e.getMessage());
        logger.error("Error while sending message", e);
    } catch (Exception e) {
        result.setError("Unexpected exception while sendig message: " + e.getMessage());
        logger.error("Unexpected exception while sendig message: ", e);
    }
    return result;
}

From source file:org.openvpms.web.component.im.contact.EmailEditor.java

/**
 * Validates the email address and personal name (if any) using {@link InternetAddress}.
 *
 * @param validator the validator/*from w ww.ja  v  a2  s .  c om*/
 * @return {@code true} if they are valid, otherwise {@code false}
 */
private boolean validateInternetAddress(Validator validator) {
    boolean valid = false;
    String name = getName();
    if (StringUtils.equals(name, defaultEmailName)) {
        name = null;
    }
    String email = ContactHelper.getEmail(getEmailAddress(), name, true);
    try {
        new InternetAddress(email, true);
        valid = true;
    } catch (AddressException exception) {
        // if a personal name is specified, it is most likely the cause of the exception (the email address
        // has its own validation within the archetype), so use its property for the validation error
        Property property = (name != null) ? getProperty("name") : getProperty("emailAddress");
        validator.add(property, new ValidatorError(property, exception.getMessage()));
    }
    return valid;
}

From source file:org.apache.hupa.server.service.SendMessageBaseServiceImpl.java

public GenericResult send(SendMessageAction action) throws Exception {
    GenericResult result = new GenericResultImpl();
    try {//from   w ww  . j av  a  2s. co m
        User user = getUser();
        Message message = createMessage(cache.getMailSession(user), action);
        message = fillBody(message, action);
        sendMessage(getUser(), message);
        if (!user.getSettings().getSmtpServer().contains("gmail.com")) {
            saveSentMessage(getUser(), message);
        }
        resetAttachments(action);

        // TODO: notify the user more accurately where the error is
        // if the message was sent and the storage in the sent folder failed, etc.
    } catch (AddressException e) {
        result.setError("Error while parsing recipient: " + e.getMessage());
        logger.error("Error while parsing recipient", e);
    } catch (AuthenticationFailedException e) {
        result.setError("Error while sending message: SMTP Authentication error.");
        logger.error("SMTP Authentication error", e);
    } catch (MessagingException e) {
        result.setError("Error while sending message: " + e.getMessage());
        logger.error("Error while sending message", e);
    } catch (Exception e) {
        result.setError("Unexpected exception while sendig message: " + e.getMessage());
        logger.error("Unexpected exception while sendig message: ", e);
    }
    return result;
}

From source file:edu.cornell.mannlib.vitro.webapp.controller.freemarker.ContactMailController.java

private ResponseValues processValidRequest(VitroRequest vreq, String webusername, String webuseremail,
        String[] recipients, String comments) throws Error {
    String statusMsg = null; // holds the error status

    ApplicationBean appBean = vreq.getAppBean();
    String deliveryfrom = "Message from the " + appBean.getApplicationName() + " Contact Form";

    String originalReferer = getOriginalRefererFromSession(vreq);

    String msgText = composeEmail(webusername, webuseremail, comments, deliveryfrom, originalReferer,
            vreq.getRemoteAddr(), vreq);

    try {/*from w w  w .  jav  a 2  s . c  o m*/
        // Write the message to the journal file
        FileWriter fw = new FileWriter(locateTheJournalFile(), true);
        PrintWriter outFile = new PrintWriter(fw);
        writeBackupCopy(outFile, msgText, vreq);

        try {
            // Send the message
            Session s = FreemarkerEmailFactory.getEmailSession(vreq);
            sendMessage(s, webuseremail, webusername, recipients, deliveryfrom, msgText);
        } catch (AddressException e) {
            statusMsg = "Please supply a valid email address.";
            outFile.println(statusMsg);
            outFile.println(e.getMessage());
        } catch (SendFailedException e) {
            statusMsg = "The system was unable to deliver your mail.  Please try again later.  [SEND FAILED]";
            outFile.println(statusMsg);
            outFile.println(e.getMessage());
        } catch (MessagingException e) {
            statusMsg = "The system was unable to deliver your mail.  Please try again later.  [MESSAGING]";
            outFile.println(statusMsg);
            outFile.println(e.getMessage());
            e.printStackTrace();
        }

        outFile.close();
    } catch (IOException e) {
        log.error("Can't open file to write email backup");
    }

    if (statusMsg == null) {
        // Message was sent successfully
        return new TemplateResponseValues(TEMPLATE_CONFIRMATION);
    } else {
        Map<String, Object> body = new HashMap<String, Object>();
        body.put("errorMessage", statusMsg);
        return new TemplateResponseValues(TEMPLATE_ERROR, body);
    }
}

From source file:org.apache.axis2.transport.mail.PollTableEntry.java

@Override
public boolean loadConfiguration(ParameterInclude paramIncl) throws AxisFault {
    String address = ParamUtils.getOptionalParam(paramIncl, MailConstants.TRANSPORT_MAIL_ADDRESS);
    if (address == null) {
        return false;
    } else {/*from  w w  w .  ja  v  a  2s.c  o m*/
        try {
            emailAddress = new InternetAddress(address);
        } catch (AddressException e) {
            throw new AxisFault("Invalid email address specified by '" + MailConstants.TRANSPORT_MAIL_ADDRESS
                    + "' parameter :: " + e.getMessage());
        }

        List<Parameter> params = paramIncl.getParameters();
        Properties props = new Properties();
        for (Parameter p : params) {
            if (p.getName().startsWith("mail.")) {
                props.setProperty(p.getName(), (String) p.getValue());
            }

            if (MailConstants.MAIL_POP3_USERNAME.equals(p.getName())
                    || MailConstants.MAIL_IMAP_USERNAME.equals(p.getName())) {
                userName = (String) p.getValue();
            }
            if (MailConstants.MAIL_POP3_PASSWORD.equals(p.getName())
                    || MailConstants.MAIL_IMAP_PASSWORD.equals(p.getName())) {
                password = (String) p.getValue();
            }
            if (MailConstants.TRANSPORT_MAIL_PROTOCOL.equals(p.getName())) {
                protocol = (String) p.getValue();
            }
        }

        session = Session.getInstance(props, null);
        MailUtils.setupLogging(session, log, paramIncl);

        contentType = ParamUtils.getOptionalParam(paramIncl, MailConstants.TRANSPORT_MAIL_CONTENT_TYPE);
        try {
            String replyAddress = ParamUtils.getOptionalParam(paramIncl,
                    MailConstants.TRANSPORT_MAIL_REPLY_ADDRESS);
            if (replyAddress != null) {
                this.replyAddress = new InternetAddress(replyAddress);
            }
        } catch (AddressException e) {
            throw new AxisFault("Invalid email address specified by '"
                    + MailConstants.TRANSPORT_MAIL_REPLY_ADDRESS + "' parameter :: " + e.getMessage());
        }

        folder = ParamUtils.getOptionalParam(paramIncl, MailConstants.TRANSPORT_MAIL_FOLDER);

        addPreserveHeaders(
                ParamUtils.getOptionalParam(paramIncl, MailConstants.TRANSPORT_MAIL_PRESERVE_HEADERS));
        addRemoveHeaders(ParamUtils.getOptionalParam(paramIncl, MailConstants.TRANSPORT_MAIL_REMOVE_HEADERS));

        String option = ParamUtils.getOptionalParam(paramIncl,
                MailConstants.TRANSPORT_MAIL_ACTION_AFTER_PROCESS);
        actionAfterProcess = MailTransportListener.MOVE.equals(option) ? PollTableEntry.MOVE
                : PollTableEntry.DELETE;
        option = ParamUtils.getOptionalParam(paramIncl, MailConstants.TRANSPORT_MAIL_ACTION_AFTER_FAILURE);
        actionAfterFailure = MailTransportListener.MOVE.equals(option) ? PollTableEntry.MOVE
                : PollTableEntry.DELETE;

        moveAfterProcess = ParamUtils.getOptionalParam(paramIncl,
                MailConstants.TRANSPORT_MAIL_MOVE_AFTER_PROCESS);
        moveAfterFailure = ParamUtils.getOptionalParam(paramIncl,
                MailConstants.TRANSPORT_MAIL_MOVE_AFTER_FAILURE);

        String processInParallel = ParamUtils.getOptionalParam(paramIncl,
                MailConstants.TRANSPORT_MAIL_PROCESS_IN_PARALLEL);
        if (processInParallel != null) {
            processingMailInParallel = Boolean.parseBoolean(processInParallel);
            if (log.isDebugEnabled() && processingMailInParallel) {
                log.debug("Parallel mail processing enabled for : " + address);
            }
        }

        String pollInParallel = ParamUtils.getOptionalParam(paramIncl,
                BaseConstants.TRANSPORT_POLL_IN_PARALLEL);
        if (pollInParallel != null) {
            setConcurrentPollingAllowed(Boolean.parseBoolean(pollInParallel));
            if (log.isDebugEnabled() && isConcurrentPollingAllowed()) {
                log.debug("Concurrent mail polling enabled for : " + address);
            }
        }

        String strMaxRetryCount = ParamUtils.getOptionalParam(paramIncl, MailConstants.MAX_RETRY_COUNT);
        if (strMaxRetryCount != null) {
            maxRetryCount = Integer.parseInt(strMaxRetryCount);
        }

        String strReconnectTimeout = ParamUtils.getOptionalParam(paramIncl, MailConstants.RECONNECT_TIMEOUT);
        if (strReconnectTimeout != null) {
            reconnectTimeout = Integer.parseInt(strReconnectTimeout) * 1000;
        }

        return super.loadConfiguration(paramIncl);
    }
}

From source file:org.apache.cocoon.acting.Sendmail.java

public Map act(Redirector redirector, SourceResolver resolver, Map objectModel, String source,
        Parameters parameters) throws Exception {
    boolean success = false;
    Map status = null;//from   w w w.  j a  va 2s.  co  m

    MailSender mms = null;
    try {
        Request request = ObjectModelHelper.getRequest(objectModel);

        // FIXME Remove support of old smtphost parameter
        String smtpHost = parameters.getParameter("smtp-host",
                parameters.getParameter("smtphost", this.smtpHost));
        String smtpUser = parameters.getParameter("smtp-user", this.smtpUser);
        String smtpPassword = parameters.getParameter("smtp-password", this.smtpPassword);

        // Empty parameter means absent parameter
        if ("".equals(smtpHost)) {
            smtpHost = this.smtpHost;
        }
        if ("".equals(smtpUser)) {
            smtpUser = this.smtpUser;
        }
        if ("".equals(smtpPassword)) {
            smtpPassword = this.smtpPassword;
        }

        mms = (MailSender) this.manager.lookup(MailSender.ROLE);

        // Initialize non-default session if host or user specified.
        if (smtpHost != null || smtpUser != null) {
            mms.setSmtpHost(smtpHost, smtpUser, smtpPassword);
        }

        if (parameters.isParameter("from")) {
            mms.setFrom(parameters.getParameter("from", null));
        }
        if (parameters.isParameter("to")) {
            mms.setTo(parameters.getParameter("to", null));
        }
        if (parameters.isParameter("replyTo")) {
            mms.setReplyTo(parameters.getParameter("replyTo", null));
        }
        if (parameters.isParameter("cc")) {
            mms.setCc(parameters.getParameter("cc", null));
        }
        if (parameters.isParameter("bcc")) {
            mms.setBcc(parameters.getParameter("bcc", null));
        }
        if (parameters.isParameter("subject")) {
            mms.setSubject(parameters.getParameter("subject", null));
        }
        if (parameters.isParameter("charset")) {
            mms.setCharset(parameters.getParameter("charset", null));
        }

        if (parameters.isParameter("src")) {
            mms.setBodyFromSrc(parameters.getParameter("src", null));
            if (parameters.isParameter("srcMimeType")) {
                mms.setBodyFromSrcMimeType(parameters.getParameter("srcMimeType", null));
            }
        } else if (parameters.isParameter("body")) {
            mms.setBody(parameters.getParameter("body", null));
        }

        if (parameters.isParameter("attachments")) {
            String fileName[] = StringUtils.split(parameters.getParameter("attachments"));
            for (int i = 0; i < fileName.length; i++) {
                String srcName = fileName[i];

                if (srcName.indexOf(":") == -1) {
                    Object obj = request.get(srcName);
                    mms.addAttachment(obj);
                    if (getLogger().isDebugEnabled()) {
                        getLogger().debug("request-attachment: " + obj);
                    }
                } else {
                    mms.addAttachmentURL(srcName, null, srcName.substring(srcName.lastIndexOf('/') + 1));
                    if (getLogger().isDebugEnabled()) {
                        getLogger().debug("sitemap-attachment: " + srcName);
                    }
                }
            }
        }

        mms.send();

        success = true;
        status = new HashMap(3);
        status.put(Sendmail.STATUS, "success");

    } catch (AddressException e) {
        getLogger().warn("AddressException: ", e);

        status = new HashMap(3);
        status.put(Sendmail.STATUS, "user-error");
        status.put(Sendmail.MESSAGE, e.getMessage());

    } catch (MessagingException e) {
        getLogger().warn("MessagingException: " + "An error occured while sending email.", e);

        status = new HashMap(3);
        status.put(Sendmail.STATUS, "server-error");
        status.put(Sendmail.MESSAGE, "An error occured while sending email: " + e.getMessage());

    } catch (ServiceException e) {
        getLogger().error("ServiceException: " + "An error occured while initializing.", e);

        status = new HashMap(3);
        status.put(Sendmail.STATUS, "server-error");
        status.put(Sendmail.MESSAGE, "An exception was thrown while sending email: " + e.getMessage());

    } catch (Exception e) {
        getLogger().error("An exception was thrown while sending email.", e);

        status = new HashMap(3);
        status.put(Sendmail.STATUS, "server-error");
        status.put(Sendmail.MESSAGE, "An exception was thrown while sending email.");

    } finally {
        ObjectModelHelper.getRequest(objectModel).setAttribute(Sendmail.REQUEST_ATTRIBUTE, status);
        this.manager.release(mms);
    }

    return success ? status : null;
}