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:org.openhab.binding.mail.action.SendMailActions.java

@RuleAction(label = "Send HTML Mail", description = "sends a HTML mail with several URL attachments")
public @ActionOutput(name = "success", type = "java.lang.Boolean") Boolean sendHtmlMail(
        @ActionInput(name = "recipient") @Nullable String recipient,
        @ActionInput(name = "subject") @Nullable String subject,
        @ActionInput(name = "html") @Nullable String html,
        @ActionInput(name = "urlList") @Nullable List<String> urlStringList) {
    if (recipient == null) {
        logger.info("can't send to missing recipient");
        return false;
    }//w  w  w  .  j a  v  a 2  s.  co m

    try {
        MailBuilder builder = new MailBuilder(recipient);

        if (subject != null && !subject.isEmpty()) {
            builder.withSubject(subject);
        }
        if (html != null && !html.isEmpty()) {
            builder.withHtml(html);
        }
        if (urlStringList != null) {
            for (String urlString : urlStringList) {
                builder.withURLAttachment(urlString);
            }
        }

        if (handler == null) {
            logger.info("handler is null, can't send mail");
            return false;
        } else {
            return handler.sendMail(builder.build());
        }
    } catch (AddressException e) {
        logger.info("could not send mail: {}", e.getMessage());
        return false;
    } catch (MalformedURLException e) {
        logger.info("could not send mail: {}", e.getMessage());
        return false;
    } catch (EmailException e) {
        logger.info("could not send mail: {}", e.getMessage());
        return false;
    }
}

From source file:eagle.common.email.EagleMailClient.java

private boolean _send(String from, String to, String cc, String title, String content) {
    Message msg = new MimeMessage(session);
    try {//  www.j av  a2 s.c  o  m
        msg.setFrom(new InternetAddress(from));
        msg.setSubject(title);
        if (to != null) {
            msg.setRecipients(Message.RecipientType.TO, InternetAddress.parse(to));
        }
        if (cc != null) {
            msg.setRecipients(Message.RecipientType.CC, InternetAddress.parse(cc));
        }
        //msg.setRecipients(Message.RecipientType.BCC, InternetAddress.parse(DEFAULT_BCC_ADDRESS));
        msg.setContent(content, "text/html;charset=utf-8");
        LOG.info(String.format("Going to send mail: from[%s], to[%s], cc[%s], title[%s]", from, to, cc, title));
        Transport.send(msg);
        return true;
    } catch (AddressException e) {
        LOG.info("Send mail failed, got an AddressException: " + e.getMessage(), e);
        return false;
    } catch (MessagingException e) {
        LOG.info("Send mail failed, got an AddressException: " + e.getMessage(), e);
        return false;
    }
}

From source file:com.sfs.ucm.service.MailService.java

/**
 * Send mail message in plain text. Mail host is obtained from instance-specific properties file via AppManager.
 * /*w  w  w  .  jav  a2  s  . c om*/
 * @param fromAddress
 * @param ccRe
 * @param toRecipient
 * @param subject
 * @param body
 * @param messageType
 *            - text/plain or text/html
 * @return status message
 * @throws IllegalArgumentException
 */
@Asynchronous
public Future<String> sendMessage(final String fromAddress, final String ccRecipient, final String toRecipient,
        final String subject, final String body, final String messageType) throws IllegalArgumentException {

    // argument validation
    if (fromAddress == null) {
        throw new IllegalArgumentException("sendMessage: Invalid or undefined fromAddress");
    }
    if (toRecipient == null) {
        throw new IllegalArgumentException("sendMessage: Invalid or undefined toRecipient");
    }
    if (subject == null) {
        throw new IllegalArgumentException("sendMessage: Invalid or undefined subject");
    }
    if (body == null) {
        throw new IllegalArgumentException("sendMessage: Invalid or undefined body conent");
    }
    if (messageType == null || (!messageType.equals("text/plain") && !messageType.equals("text/html"))) {
        throw new IllegalArgumentException("sendMessage: Invalid or undefined messageType");
    }

    String status = null;

    try {
        Properties props = new Properties();
        props.put("mail.smtp.host", appManager.getApplicationProperty("mail.host"));
        props.put("mail.smtp.port", appManager.getApplicationProperty("mail.port"));

        Object[] params = new Object[4];
        params[0] = (String) subject;
        params[1] = (String) fromAddress;
        params[2] = (String) ccRecipient;
        params[3] = (String) toRecipient;
        logger.info("Sending message: subject: {}, fromAddress: {}, ccRecipient: {}, toRecipient: {}", params);

        Session session = Session.getDefaultInstance(props);
        Message message = new MimeMessage(session);
        message.setFrom(new InternetAddress(fromAddress));
        Address toAddress = new InternetAddress(toRecipient);
        message.addRecipient(Message.RecipientType.TO, toAddress);

        if (StringUtils.isNotBlank(ccRecipient)) {
            Address ccAddress = new InternetAddress(ccRecipient);
            message.addRecipient(Message.RecipientType.CC, ccAddress);
        }
        message.setSubject(subject);
        message.setContent(body, messageType);
        Transport.send(message);
    } catch (AddressException e) {
        logger.error("sendMessage Address Exception occurred: {}", e.getMessage());
        status = "sendMessage Address Exception occurred";
    } catch (MessagingException e) {
        logger.error("sendMessage Messaging Exception occurred: {}", e.getMessage());
        status = "sendMessage Messaging Exception occurred";
    }

    return new AsyncResult<String>(status);

}

From source file:com.sfs.ucm.service.MailService.java

/**
 * Send mail message in plain text. Mail host is obtained from instance-specific properties file via AppManager.
 * /*ww  w  .j  a v  a 2 s.c o m*/
 * @param fromAddress
 * @param recipients
 *            - fully qualified recipient address
 * @param subject
 * @param body
 * @param messageType
 *            - text/plain or text/html
 * @throws IllegalArgumentException
 */
@Asynchronous
public Future<String> sendMessage(final String fromAddress, final String ccRecipient,
        final String[] toRecipients, final String subject, final String body, final String messageType) {

    // argument validation
    if (fromAddress == null) {
        throw new IllegalArgumentException("sendMessage: Invalid or undefined fromAddress");
    }
    if (toRecipients == null) {
        throw new IllegalArgumentException("sendMessage: Invalid or undefined toRecipients");
    }
    if (subject == null) {
        throw new IllegalArgumentException("sendMessage: Invalid or undefined subject");
    }
    if (body == null) {
        throw new IllegalArgumentException("sendMessage: Invalid or undefined body conent");
    }
    if (messageType == null || (!messageType.equals("text/plain") && !messageType.equals("text/html"))) {
        throw new IllegalArgumentException("sendMessage: Invalid or undefined messageType");
    }

    String status = null;
    try {
        Properties props = new Properties();
        props.put("mail.smtp.host", appManager.getApplicationProperty("mail.host"));
        props.put("mail.smtp.port", appManager.getApplicationProperty("mail.port"));

        Object[] params = new Object[4];
        params[0] = (String) subject;
        params[1] = (String) fromAddress;
        params[2] = (String) ccRecipient;
        params[3] = (String) StringUtils.join(toRecipients);
        logger.info("Sending message: subject: {}, fromAddress: {}, ccRecipient: {}, toRecipient: {}", params);

        Session session = Session.getDefaultInstance(props);
        Message message = new MimeMessage(session);
        message.setFrom(new InternetAddress(fromAddress));
        Address[] toAddresses = new Address[toRecipients.length];
        for (int i = 0; i < toAddresses.length; i++) {
            toAddresses[i] = new InternetAddress(toRecipients[i]);
        }
        message.addRecipients(Message.RecipientType.TO, toAddresses);

        if (StringUtils.isNotBlank(ccRecipient)) {
            Address ccAddress = new InternetAddress(ccRecipient);
            message.addRecipient(Message.RecipientType.CC, ccAddress);
        }
        message.setSubject(subject);
        message.setContent(body, messageType);
        Transport.send(message);
    } catch (AddressException e) {
        logger.error("sendMessage Address Exception occurred: {}", e.getMessage());
        status = "sendMessage Address Exception occurred";
    } catch (MessagingException e) {
        logger.error("sendMessage Messaging Exception occurred: {}", e.getMessage());
        status = "sendMessage Messaging Exception occurred";
    }

    return new AsyncResult<String>(status);

}

From source file:eagle.common.email.EagleMailClient.java

private boolean _send(String from, String to, String cc, String title, String content,
        List<MimeBodyPart> attachments) {
    MimeMessage mail = new MimeMessage(session);
    try {// w w w .  jav a 2  s  . c  om
        mail.setFrom(new InternetAddress(from));
        mail.setSubject(title);
        if (to != null) {
            mail.setRecipients(Message.RecipientType.TO, InternetAddress.parse(to));
        }
        if (cc != null) {
            mail.setRecipients(Message.RecipientType.CC, InternetAddress.parse(cc));
        }

        //mail.setRecipients(Message.RecipientType.BCC, InternetAddress.parse(DEFAULT_BCC_ADDRESS));

        MimeBodyPart mimeBodyPart = new MimeBodyPart();
        mimeBodyPart.setContent(content, "text/html;charset=utf-8");

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

        for (MimeBodyPart attachment : attachments) {
            multipart.addBodyPart(attachment);
        }

        mail.setContent(multipart);
        //         mail.setContent(content, "text/html;charset=utf-8");
        LOG.info(String.format("Going to send mail: from[%s], to[%s], cc[%s], title[%s]", from, to, cc, title));
        Transport.send(mail);
        return true;
    } catch (AddressException e) {
        LOG.info("Send mail failed, got an AddressException: " + e.getMessage(), e);
        return false;
    } catch (MessagingException e) {
        LOG.info("Send mail failed, got an AddressException: " + e.getMessage(), e);
        return false;
    }
}

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

public void send() throws AxisFault {

    try {/*from ww w  .ja  va  2 s  .  co m*/

        Session session = Session.getInstance(properties, new Authenticator() {
            protected PasswordAuthentication getPasswordAuthentication() {
                return passwordAuthentication;
            }
        });
        MimeMessage msg = new MimeMessage(session);

        // Set date - required by rfc2822
        msg.setSentDate(new java.util.Date());

        // Set from - required by rfc2822
        String from = properties.getProperty("mail.smtp.from");
        if (from != null) {
            msg.setFrom(new InternetAddress(from));
        }

        EndpointReference epr = null;
        MailToInfo mailToInfo;

        if (messageContext.getTo() != null && !messageContext.getTo().hasAnonymousAddress()) {
            epr = messageContext.getTo();
        }

        if (epr != null) {
            if (!epr.hasNoneAddress()) {
                mailToInfo = new MailToInfo(epr);
                msg.addRecipient(Message.RecipientType.TO, new InternetAddress(mailToInfo.getEmailAddress()));

            } else {
                if (from != null) {
                    mailToInfo = new MailToInfo(from);
                    msg.addRecipient(Message.RecipientType.TO,
                            new InternetAddress(mailToInfo.getEmailAddress()));
                } else {
                    String error = EMailSender.class.getName() + "Couldn't countinue due to"
                            + " FROM addressing is NULL";
                    log.error(error);
                    throw new AxisFault(error);
                }
            }
        } else {
            // replyto : from : or reply-path;
            if (from != null) {
                mailToInfo = new MailToInfo(from);
                msg.addRecipient(Message.RecipientType.TO, new InternetAddress(mailToInfo.getEmailAddress()));
            } else {
                String error = EMailSender.class.getName() + "Couldn't countinue due to"
                        + " FROM addressing is NULL and EPR is NULL";
                log.error(error);
                throw new AxisFault(error);
            }

        }

        msg.setSubject("__ Axis2/Java Mail Message __");

        if (mailToInfo.isxServicePath()) {
            msg.setHeader(Constants.X_SERVICE_PATH, "\"" + mailToInfo.getContentDescription() + "\"");
        }

        if (inReplyTo != null) {
            msg.setHeader(Constants.IN_REPLY_TO, inReplyTo);
        }

        createMailMimeMessage(msg, mailToInfo, format);
        Transport.send(msg);

        log.info("Message being send. [Action = ]" + messageContext.getOptions().getAction());

        sendReceive(messageContext, msg.getMessageID());
    } catch (AddressException e) {
        throw new AxisFault(e.getMessage(), e);
    } catch (MessagingException e) {
        throw new AxisFault(e.getMessage(), e);
    }
}

From source file:ru.org.linux.user.EditRegisterController.java

@RequestMapping(method = RequestMethod.POST)
public ModelAndView edit(HttpServletRequest request, HttpServletResponse response,
        @Valid @ModelAttribute("form") EditRegisterRequest form, Errors errors) throws Exception {
    Template tmpl = Template.getTemplate(request);

    if (!tmpl.isSessionAuthorized()) {
        throw new AccessViolationException("Not authorized");
    }/*www  .j  ava  2s .  c o  m*/

    String nick = tmpl.getNick();
    String password = Strings.emptyToNull(form.getPassword());

    if (password != null && password.equalsIgnoreCase(nick)) {
        errors.reject(null, "   ? ? ");
    }

    InternetAddress mail = null;

    if (!Strings.isNullOrEmpty(form.getEmail())) {
        try {
            mail = new InternetAddress(form.getEmail());
        } catch (AddressException e) {
            errors.rejectValue("email", null, "? e-mail: " + e.getMessage());
        }
    }

    String url = null;

    if (!Strings.isNullOrEmpty(form.getUrl())) {
        url = URLUtil.fixURL(form.getUrl());
    }

    String name = Strings.emptyToNull(form.getName());

    if (name != null) {
        name = StringUtil.escapeHtml(name);
    }

    String town = null;

    if (!Strings.isNullOrEmpty(form.getTown())) {
        town = StringUtil.escapeHtml(form.getTown());
    }

    String info = null;

    if (!Strings.isNullOrEmpty(form.getInfo())) {
        info = StringUtil.escapeHtml(form.getInfo());
    }

    ipBlockDao.checkBlockIP(request.getRemoteAddr(), errors, tmpl.getCurrentUser());

    boolean emailChanged = false;

    User user = userService.getUser(nick);

    if (Strings.isNullOrEmpty(form.getOldpass())) {
        errors.rejectValue("oldpass", null,
                "? ? ?   ");
    } else if (!user.matchPassword(form.getOldpass())) {
        errors.rejectValue("oldpass", null, "? ");
    }

    user.checkAnonymous();

    String newEmail = null;

    if (mail != null) {
        if (user.getEmail() != null && user.getEmail().equals(form.getEmail())) {
            newEmail = null;
        } else {
            if (userDao.getByEmail(mail.getAddress().toLowerCase(), false) != null) {
                errors.rejectValue("email", null, " email  ???");
            }

            newEmail = mail.getAddress().toLowerCase();

            emailChanged = true;
        }
    }

    if (!errors.hasErrors()) {
        userDao.updateUser(user, name, url, newEmail, town, password, info);
        //  token-  ? ? ?
        if (password != null) {
            try {
                UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken(
                        user.getNick(), password);
                UserDetailsImpl details = (UserDetailsImpl) userDetailsService
                        .loadUserByUsername(user.getNick());
                token.setDetails(details);
                Authentication auth = authenticationManager.authenticate(token);
                SecurityContextHolder.getContext().setAuthentication(auth);
                rememberMeServices.loginSuccess(request, response, auth);
            } catch (Exception ex) {
                logger.error(
                        " ? ?    ? ?. ",
                        ex);
            }
        }

        if (emailChanged) {
            emailService.sendEmail(user.getNick(), newEmail, false);
        }
    } else {
        return new ModelAndView("edit-reg");
    }

    if (emailChanged) {
        String msg = " ?  ?. "
                + " ?  " + StringUtil.escapeHtml(newEmail)
                + " ?   ? email.";

        return new ModelAndView("action-done", "message", msg);
    } else {
        return new ModelAndView(new RedirectView("/people/" + tmpl.getNick() + "/profile"));
    }
}

From source file:org.collectionspace.chain.csp.persistence.file.TestGeneral.java

/**
 * Sets up and sends email message providing you have set up the email address to send to
 *///from   www.  j  a  va 2  s.  com
@Test
public void testEmail() {
    Boolean doIreallyWantToSpam = false; // set to true when you have configured the email addresses
    /* please personalises these emails before sending - I don't want your spam. */
    String from = "admin@collectionspace.org";
    String[] recipients = { "" };

    String SMTP_HOST_NAME = "localhost";
    String SMTP_PORT = "25";
    String message = "Hi, Test Message Contents";
    String subject = "A test from collectionspace test suite";
    String SSL_FACTORY = "javax.net.ssl.SSLSocketFactory";
    Security.addProvider(new com.sun.net.ssl.internal.ssl.Provider()); //REM - Replace.  This is pre-JDK 1.4 code, from the days when JSSE was a separate download.  Fix the imports so they refer to the classes in javax.net.ssl If you really want to get hold of a specific instance, you can use Security.getProvider(name). You'll find the appropriate names in the providers documentation. 
    boolean debug = true;

    Properties props = new Properties();
    props.put("mail.smtp.host", SMTP_HOST_NAME);
    //props.put("mail.smtp.auth", "true");
    props.put("mail.smtp.auth", "false");
    props.put("mail.debug", "true");
    props.put("mail.smtp.port", SMTP_PORT);
    props.put("mail.smtp.socketFactory.port", SMTP_PORT);
    props.put("mail.smtp.socketFactory.class", SSL_FACTORY);
    props.put("mail.smtp.socketFactory.fallback", "false");

    Session session = Session.getDefaultInstance(props);

    session.setDebug(debug);
    if (doIreallyWantToSpam) {

        Message msg = new MimeMessage(session);
        InternetAddress addressFrom;
        try {
            addressFrom = new InternetAddress(from);
            msg.setFrom(addressFrom);

            InternetAddress[] addressTo = new InternetAddress[recipients.length];
            for (int i = 0; i < recipients.length; i++) {
                addressTo[i] = new InternetAddress(recipients[i]);
            }
            msg.setRecipients(Message.RecipientType.TO, addressTo);

            // Setting the Subject and Content Type
            msg.setSubject(subject);
            msg.setContent(message, "text/plain");
            if (doIreallyWantToSpam) {
                Transport.send(msg);
                assertTrue(doIreallyWantToSpam);
            }
        } catch (AddressException e) {
            log.debug(e.getMessage());
            assertTrue(false);
        } catch (MessagingException e) {
            log.debug(e.getMessage());
            assertTrue(false);
        }
    }
    //assertTrue(doIreallyWantToSpam);
}

From source file:hudson.tasks.mail.impl.BaseBuildResultMail.java

/**
 * Creates empty mail./*from  w w w .  ja va2 s  .c om*/
 *
 * @param build build.
 * @param listener listener.
 * @return empty mail.
 * @throws MessagingException exception if any.
 */
protected MimeMessage createEmptyMail(AbstractBuild<?, ?> build, BuildListener listener)
        throws MessagingException {
    MimeMessage msg = new HudsonMimeMessage(Mailer.descriptor().createSession());
    // TODO: I'd like to put the URL to the page in here,
    // but how do I obtain that?
    msg.setContent("", "text/plain");
    msg.setFrom(new InternetAddress(Mailer.descriptor().getAdminAddress()));
    msg.setSentDate(new Date());

    Set<InternetAddress> rcp = new LinkedHashSet<InternetAddress>();
    StringTokenizer tokens = new StringTokenizer(getRecipients());
    while (tokens.hasMoreTokens()) {
        String address = tokens.nextToken();
        if (address.startsWith("upstream-individuals:")) {
            // people who made a change in the upstream
            String projectName = address.substring("upstream-individuals:".length());
            AbstractProject up = Hudson.getInstance().getItemByFullName(projectName, AbstractProject.class);
            if (up == null) {
                listener.getLogger().println("No such project exist: " + projectName);
                continue;
            }
            includeCulpritsOf(up, build, listener, rcp);
        } else {
            // ordinary address
            try {
                rcp.add(new InternetAddress(address));
            } catch (AddressException e) {
                // report bad address, but try to send to other addresses
                e.printStackTrace(listener.error(e.getMessage()));
            }
        }
    }

    if (CollectionUtils.isNotEmpty(upstreamProjects)) {
        for (AbstractProject project : upstreamProjects) {
            includeCulpritsOf(project, build, listener, rcp);
        }
    }

    if (sendToIndividuals) {
        Set<User> culprits = build.getCulprits();

        if (debug)
            listener.getLogger()
                    .println("Trying to send e-mails to individuals who broke the build. sizeof(culprits)=="
                            + culprits.size());

        rcp.addAll(buildCulpritList(listener, culprits));
    }
    msg.setRecipients(Message.RecipientType.TO, rcp.toArray(new InternetAddress[rcp.size()]));

    AbstractBuild<?, ?> pb = build.getPreviousBuild();
    if (pb != null) {
        MailMessageIdAction b = pb.getAction(MailMessageIdAction.class);
        if (b != null) {
            msg.setHeader("In-Reply-To", b.messageId);
            msg.setHeader("References", b.messageId);
        }
    }

    return msg;
}

From source file:com.nokia.helium.core.EmailDataSender.java

/**
 * Send xml data/*from w w w .  j  a v  a  2  s. c o m*/
 * 
 * @param String purpose of this email
 * @param String file to send
 * @param String mime type
 * @param String subject of email
 * @param String header of mail
 * @param boolean compress data if true
 */
public void sendData(String purpose, File fileToSend, String mimeType, String subject, String header,
        boolean compressData) throws EmailSendException {
    try {
        log.debug("sendData:Send file: " + fileToSend + " and mimetype: " + mimeType);
        if (fileToSend != null && fileToSend.exists()) {
            InternetAddress[] toAddresses = getToAddressList();
            Properties props = new Properties();
            if (smtpServerAddress != null) {
                log.debug("sendData:smtp address: " + smtpServerAddress);
                props.setProperty("mail.smtp.host", smtpServerAddress);
            }
            Session mailSession = Session.getDefaultInstance(props, null);
            MimeMessage message = new MimeMessage(mailSession);
            message.setSubject(subject == null ? "" : subject);
            MimeMultipart multipart = new MimeMultipart("related");
            BodyPart messageBodyPart = new MimeBodyPart();
            ByteArrayDataSource dataSrc = null;
            String fileName = fileToSend.getName();
            if (compressData) {
                log.debug("Sending compressed data");
                dataSrc = compressFile(fileToSend);
                dataSrc.setName(fileName + ".gz");
                messageBodyPart.setFileName(fileName + ".gz");
            } else {
                log.debug("Sending uncompressed data:");
                dataSrc = new ByteArrayDataSource(new FileInputStream(fileToSend), mimeType);

                message.setContent(FileUtils.readFileToString(fileToSend), "text/html");
                multipart = null;
            }
            String headerToSend = null;
            if (header == null) {
                headerToSend = "";
            }
            messageBodyPart.setHeader("helium-bld-data", headerToSend);
            messageBodyPart.setDataHandler(new DataHandler(dataSrc));

            if (multipart != null) {
                multipart.addBodyPart(messageBodyPart); // add to the
                // multipart
                message.setContent(multipart);
            }
            try {
                message.setFrom(getFromAddress());
            } catch (AddressException e) {
                throw new EmailSendException("Error retrieving the from address: " + e.getMessage(), e);
            } catch (LDAPException e) {
                throw new EmailSendException("Error retrieving the from address: " + e.getMessage(), e);
            }
            message.addRecipients(Message.RecipientType.TO, toAddresses);
            log.info("Sending email alert: " + subject);
            Transport.send(message);
        }
    } catch (MessagingException e) {
        String fullErrorMessage = "Failed sending e-mail: " + purpose;
        if (e.getMessage() != null) {
            fullErrorMessage += ": " + e.getMessage();
        }
        throw new EmailSendException(fullErrorMessage, e);
    } catch (IOException e) {
        String fullErrorMessage = "Failed sending e-mail: " + purpose;
        if (e.getMessage() != null) {
            fullErrorMessage += ": " + e.getMessage();
        }
        // We are Ignoring the errors as no need to fail the build.
        throw new EmailSendException(fullErrorMessage, e);
    }
}