Example usage for javax.mail MessagingException getMessage

List of usage examples for javax.mail MessagingException getMessage

Introduction

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

Prototype

public String getMessage() 

Source Link

Document

Returns the detail message string of this throwable.

Usage

From source file:org.nuxeo.ecm.platform.mail.web.actions.MailActionsBean.java

public String checkCurrentInbox() {
    DocumentModel mailFolder = navigationContext.getCurrentDocument();

    try {/*from ww w . j a v a2s. co m*/
        MailCoreHelper.checkMail(mailFolder, documentManager);
    } catch (MessagingException e) {
        log.debug(e, e);
        facesMessages.add(StatusMessage.Severity.ERROR,
                resourcesAccessor.getMessages().get("feedback.check.mail.error") + e.getMessage());

        return CURRENT_PAGE;
    }

    facesMessages.add(StatusMessage.Severity.INFO,
            resourcesAccessor.getMessages().get("feedback.check.mail.success"));
    Events.instance().raiseEvent("documentChildrenChanged");

    return CURRENT_PAGE;
}

From source file:tld.mydomain.example.site.controller.ContactController.java

/**
 * Contact Submit Handler//  w w w  . j a va 2 s  . c o  m
 * @return
 * @throws IOException 
 * @throws MessagingException 
 */
@RequestMapping("/contact/send")
public ModelAndView contactSend(HttpServletResponse resp, HttpServletRequest request,
        @ModelAttribute("contactForm") @Valid ContactForm contactForm, BindingResult result)
        throws IOException {

    ModelAndView model = null;

    if (result.hasErrors()) {
        model = new ModelAndView("contact/Contact");
        model.addObject("currentMainMenuItem", "contact");
        model.addObject("contactForm", contactForm);
    } else {
        try {
            contactService.sendContactEmail(contactForm);

            model = new ModelAndView("contact/SendSuccess");
            model.addObject("mainMenu", "contact");

        } catch (MessagingException e) {

            model = new ModelAndView("contact/SendFailed");
            model.addObject("mainMenu", "contact");
            model.addObject("sendError", e.getMessage());
        }
    }

    return model;

}

From source file:org.jahia.modules.gateway.decoders.BaseMailDecoder.java

protected String getSenderEmail(Message message) {
    String from = null;/*from   ww  w . jav a 2  s.  c  o  m*/
    try {
        Address[] senders = message.getFrom();
        if (senders != null && senders.length > 0) {
            from = ((InternetAddress) senders[0]).getAddress();
        }
    } catch (MessagingException e) {
        logger.error(e.getMessage(), e);
    }
    return from;
}

From source file:org.blue.star.plugins.send_mail.java

public boolean execute_check() {

    Properties props = System.getProperties();
    props.put("mail.smtp.host", smtpServer);
    if (smtpAuth) {
        props.put("mail.smtp.auth", "true");
    }// w  ww  .j  ava2  s.co m

    Session session = Session.getInstance(props, null);
    SMTPTransport transport = null;
    //      if (debug)
    //         session.setDebug(true);

    // construct the message
    try {
        Message msg = new MimeMessage(session);
        if (from != null)
            msg.setFrom(new InternetAddress(from));
        else
            msg.setFrom();

        msg.setRecipients(Message.RecipientType.TO, InternetAddress.parse(to, false));

        if (subject != null)
            msg.setSubject(subject);

        msg.setHeader("X-Mailer", "blue-send-mail");
        msg.setSentDate(new Date());
        msg.setText(message.replace("\\n", "\n").replace("\\t", "\t"));

        transport = (SMTPTransport) session.getTransport(ssl ? "smtps" : "smtp");
        if (smtpAuth)
            transport.connect(smtpServer, smtpUser, smtpPass);
        else
            transport.connect();
        transport.sendMessage(msg, msg.getAllRecipients());
        transport.close();

    } catch (MessagingException mE) {
        mE.printStackTrace();
        this.state = common_h.STATE_CRITICAL;
        this.text = mE.getMessage();
        return false;
    } finally {
        try {
            transport.close();
        } catch (Exception e) {
        }
    }

    state = common_h.STATE_OK;
    text = "Message Sent!";
    return true;
}

From source file:org.jkcsoft.java.mail.Emailer.java

private void sendMsg(String to, String toName, String from, String fromName, String subject, String msgBody,
        String strMimeType) throws Exception {
    InternetAddress[] toAddrArr = new InternetAddress[] { new InternetAddress(to, toName) };
    InternetAddress fromAddr = new InternetAddress(from, fromName);
    try {// w w  w  .  j  a  v a  2s .  c o m
        _sendMsg(toAddrArr, null, fromAddr, subject, msgBody, strMimeType);
    } catch (MessagingException e) {
        setState(SystemState.LAST_CONNECTION_FAILED);
        setStateMessage(e.getMessage());
        LogHelper.error(this, "Sending email", e);
        throw e;
    }
    setState(SystemState.LAST_CONNECTION_OK);
}

From source file:org.artifactory.mail.MailServiceImpl.java

/**
 * Send an e-mail message/*from   ww  w.ja  va  2 s. c  o m*/
 *
 * @param recipients Recipients of the message that will be sent
 * @param subject    The subject of the message
 * @param body       The body of the message
 * @param config     A mail server configuration to use
 * @throws Exception
 */
@Override
public void sendMail(String[] recipients, String subject, String body, final MailServerConfiguration config)
        throws EmailException {

    verifyParameters(recipients, config);

    if (!config.isEnabled()) {
        log.debug("Ignoring requested mail delivery. The given configuration is disabled.");
        return;
    }

    boolean debugEnabled = log.isDebugEnabled();

    Properties properties = new Properties();

    properties.put("mail.smtp.host", config.getHost());
    properties.put("mail.smtp.port", Integer.toString(config.getPort()));

    properties.put("mail.smtp.quitwait", "false");

    //Default protocol
    String protocol = "smtp";

    //Enable TLS if set
    if (config.isUseTls()) {
        properties.put("mail.smtp.starttls.enable", "true");
    }

    //Enable SSL if set
    boolean useSsl = config.isUseSsl();
    if (useSsl) {
        properties.put("mail.smtp.socketFactory.port", Integer.toString(config.getPort()));
        properties.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
        properties.put("mail.smtp.socketFactory.fallback", "false");
        //Requires special protocol
        protocol = "smtps";
    }

    //Set debug property if enabled by the logger
    properties.put("mail.debug", debugEnabled);

    Authenticator authenticator = null;
    if (!StringUtils.isEmpty(config.getUsername())) {
        properties.put("mail.smtp.auth", "true");
        authenticator = new Authenticator() {
            @Override
            protected PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication(config.getUsername(), config.getPassword());
            }
        };
    }

    Session session = Session.getInstance(properties, authenticator);
    Message message = new MimeMessage(session);

    String subjectPrefix = config.getSubjectPrefix();
    String fullSubject = (!StringUtils.isEmpty(subjectPrefix)) ? (subjectPrefix + " " + subject) : subject;
    try {
        message.setSubject(fullSubject);

        if (!StringUtils.isEmpty(config.getFrom())) {
            InternetAddress addressFrom = new InternetAddress(config.getFrom());
            message.setFrom(addressFrom);
        }

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

        //Create multi-part message in case we want to add html support
        Multipart multipart = new MimeMultipart("related");

        BodyPart htmlPart = new MimeBodyPart();
        htmlPart.setContent(body, "text/html");
        multipart.addBodyPart(htmlPart);
        message.setContent(multipart);

        //Set debug property if enabled by the logger
        session.setDebug(debugEnabled);

        //Connect and send
        Transport transport = session.getTransport(protocol);
        if (useSsl) {
            transport.connect(config.getHost(), config.getPort(), config.getUsername(), config.getPassword());
        } else {
            transport.connect();
        }
        transport.sendMessage(message, message.getAllRecipients());
        transport.close();
    } catch (MessagingException e) {
        String em = e.getMessage();
        throw new EmailException(
                "An error has occurred while sending an e-mail" + (em != null ? ": " + em.trim() : "") + ".\n",
                e);
    }
}

From source file:net.triptech.metahive.service.EmailSenderService.java

/**
 * Send an email message using the configured Spring sender. On success
 * record the sent message in the datastore for reporting purposes
 *
 * @param email the email// ww w  .  jav a  2s .c  om
 * @param attachments the attachments
 * @throws ServiceException the service exception
 */
public final void send(final SimpleMailMessage email, TreeMap<String, Object> attachments)
        throws ServiceException {

    // Check to see whether the required fields are set (to, from, message)
    if (email.getTo() == null) {
        throw new ServiceException("Error sending email: Recipient " + "address required");
    }
    if (StringUtils.isBlank(email.getFrom())) {
        throw new ServiceException("Error sending email: Email requires " + "a from address");
    }
    if (StringUtils.isBlank(email.getText())) {
        throw new ServiceException("Error sending email: No email " + "message specified");
    }
    if (mailSender == null) {
        throw new ServiceException("The JavaMail sender has not " + "been configured");
    }

    // Prepare the email message
    MimeMessage message = mailSender.createMimeMessage();
    MimeMessageHelper helper = null;
    boolean htmlMessage = false;
    if (StringUtils.containsIgnoreCase(email.getText(), "<html")) {
        htmlMessage = true;
        try {
            helper = new MimeMessageHelper(message, true, "UTF-8");
        } catch (MessagingException me) {
            throw new ServiceException("Error preparing email for sending: " + me.getMessage());
        }
    } else {
        helper = new MimeMessageHelper(message);
    }

    try {
        helper.setTo(email.getTo());
        helper.setFrom(email.getFrom());
        helper.setSubject(email.getSubject());

        if (email.getCc() != null) {
            helper.setCc(email.getCc());
        }
        if (email.getBcc() != null) {
            helper.setBcc(email.getBcc());
        }

        if (htmlMessage) {
            String plainText = email.getText();
            try {
                ConvertHtmlToText htmlToText = new ConvertHtmlToText();
                plainText = htmlToText.convert(email.getText());
            } catch (Exception e) {
                logger.error("Error converting HTML to plain text: " + e.getMessage());
            }
            helper.setText(plainText, email.getText());
        } else {
            helper.setText(email.getText());
        }

        if (email.getSentDate() != null) {
            helper.setSentDate(email.getSentDate());
        } else {
            helper.setSentDate(Calendar.getInstance().getTime());
        }

    } catch (MessagingException me) {
        throw new ServiceException("Error preparing email for sending: " + me.getMessage());
    }

    // Append any attachments (if an HTML email)
    if (htmlMessage && attachments != null) {
        for (String id : attachments.keySet()) {
            Object reference = attachments.get(id);

            if (reference instanceof File) {
                try {
                    FileSystemResource res = new FileSystemResource((File) reference);
                    helper.addInline(id, res);
                } catch (MessagingException me) {
                    logger.error("Error appending File attachment: " + me.getMessage());
                }
            }
            if (reference instanceof URL) {
                try {
                    UrlResource res = new UrlResource((URL) reference);
                    helper.addInline(id, res);
                } catch (MessagingException me) {
                    logger.error("Error appending URL attachment: " + me.getMessage());
                }
            }
        }
    }

    // Send the email message
    try {
        mailSender.send(message);
    } catch (MailException me) {
        logger.error("Error sending email: " + me.getMessage());
        throw new ServiceException("Error sending email: " + me.getMessage());
    }
}

From source file:org.jenkinsci.plugins.send_mail_builder.SendMailBuilder.java

@Override
public boolean perform(final AbstractBuild<?, ?> build, final Launcher launcher, final BuildListener listener)
        throws IOException, InterruptedException {
    final EnvVars env = build.getEnvironment(listener);
    final String charset = Mailer.descriptor().getCharset();
    final MimeMessage msg = new MimeMessage(Mailer.descriptor().createSession());
    try {/*from w ww  .  j a  va 2 s  .  com*/
        msg.setFrom(Mailer.StringToAddress(JenkinsLocationConfiguration.get().getAdminAddress(), charset));
        msg.setContent("", "text/plain");
        msg.setSentDate(new Date());
        String actualReplyTo = env.expand(replyTo);
        if (StringUtils.isBlank(actualReplyTo)) {
            actualReplyTo = Mailer.descriptor().getReplyToAddress();
        }
        if (StringUtils.isNotBlank(actualReplyTo)) {
            msg.setReplyTo(new Address[] { Mailer.StringToAddress(actualReplyTo, charset) });
        }
        msg.setRecipients(RecipientType.TO, toInternetAddresses(listener, env.expand(tos), charset));
        msg.setRecipients(RecipientType.CC, toInternetAddresses(listener, env.expand(ccs), charset));
        msg.setRecipients(RecipientType.BCC, toInternetAddresses(listener, env.expand(bccs), charset));
        msg.setSubject(env.expand(subject), charset);
        msg.setText(env.expand(text), charset);
        Transport.send(msg);
    } catch (final MessagingException e) {
        listener.getLogger().println(Messages.SendMail_FailedToSend());
        e.printStackTrace(listener.error(e.getMessage()));
        return false;
    }
    listener.getLogger().println(Messages.SendMail_SentSuccessfully());
    return true;
}

From source file:org.apache.james.smtpserver.fastfail.URIRBLHandler.java

/**
 * Check method/* www  . j  a  v  a  2s  .  co m*/
 */
protected boolean check(SMTPSession session, Mail mail) {
    MimeMessage message;

    try {
        message = mail.getMessage();

        HashSet<String> domains = scanMailForDomains(message, session);

        for (String domain : domains) {
            Iterator<String> uRbl = uriRbl.iterator();
            String target = domain;

            while (uRbl.hasNext()) {
                try {
                    String uRblServer = uRbl.next();
                    String address = target + "." + uRblServer;

                    if (session.getLogger().isDebugEnabled()) {
                        session.getLogger().debug("Lookup " + address);
                    }

                    dnsService.getByName(address);

                    // store server name for later use
                    session.setAttachment(URBLSERVER, uRblServer, State.Transaction);
                    session.setAttachment(LISTED_DOMAIN, target, State.Transaction);

                    return true;

                } catch (UnknownHostException uhe) {
                    // domain not found. keep processing
                }
            }
        }
    } catch (MessagingException e) {
        session.getLogger().error(e.getMessage());
    } catch (IOException e) {
        session.getLogger().error(e.getMessage());
    }
    return false;
}

From source file:net.orpiske.dcd.collector.dataset.impl.MBoxDataSet.java

@Override
public Data next() {
    MBoxData mBoxData = null;//from  w w  w.j  a va  2  s .c  om
    Message message;

    try {
        message = inbox.getMessage(currentMessage);

        if (logger.isDebugEnabled()) {
            logger.debug("Processing message " + currentMessage + " of " + messageCount + "");

            if (logger.isTraceEnabled()) {
                logger.trace("------- MESSAGE START -------");
                logger.trace(message.getContent().toString());
                logger.trace("-------  MESSAGE END  -------");
            }
        }

        mBoxData = new MBoxData(message.getContent().toString());
        mBoxData.setBody(message.getContent().toString());

        StringBuilder stringBuilder = new StringBuilder();
        Enumeration<Header> enumeration = message.getAllHeaders();
        while (enumeration.hasMoreElements()) {
            Header header = enumeration.nextElement();

            if (header.getName().equalsIgnoreCase("from")) {
                mBoxData.setOriginator(header.getValue());
            } else {
                stringBuilder.append(header.getValue());
            }

            if (header.getName().equalsIgnoreCase("date")) {
                String strDate = header.getValue();
                Date date = getDate(strDate);

                mBoxData.setDate(date);
            }

            stringBuilder.append('\n');
        }

        mBoxData.setHeader(stringBuilder.toString());
    } catch (MessagingException e) {
        logger.error("Unable to process message " + currentMessage + ": " + e.getMessage(), e);
    } catch (IOException e) {
        logger.error("I/O error while processing the message " + currentMessage + ": " + e.getMessage(), e);
    }

    currentMessage++;
    return mBoxData;
}