Example usage for javax.mail MessagingException printStackTrace

List of usage examples for javax.mail MessagingException printStackTrace

Introduction

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

Prototype

public void printStackTrace() 

Source Link

Document

Prints this throwable and its backtrace to the standard error stream.

Usage

From source file:org.sakaiproject.kernel.messaging.activemq.ActiveMQEmailDeliveryT.java

private String getBodyAsString(Object content) {
    Multipart mime = null;/*from  ww w.  j ava  2s .  c o m*/
    StringBuffer sb = new StringBuffer();
    if (content instanceof String) {
        return (String) content;
    } else if (content instanceof Multipart) {
        try {
            mime = (Multipart) content;
            for (int i = 0; i < mime.getCount(); ++i) {
                Part p = mime.getBodyPart(i);
                sb.append(p.getContent());
            }
        } catch (MessagingException e) {
            e.printStackTrace();
            Assert.assertTrue(false);
        } catch (IOException e) {
            e.printStackTrace();
            Assert.assertTrue(false);
        }
    } else {
        Assert.assertTrue(false);
    }
    return sb.toString();
}

From source file:transport.java

public void go(Session session, InternetAddress[] toAddr, InternetAddress from) {
    Transport trans = null;/*from ww w. j  av a 2 s . c  o m*/

    try {
        // create a message
        Message msg = new MimeMessage(session);
        msg.setFrom(from);
        msg.setRecipients(Message.RecipientType.TO, toAddr);
        msg.setSubject("JavaMail APIs transport.java Test");
        msg.setSentDate(new Date()); // Date: header
        msg.setContent(msgText + msgText2, "text/plain");
        msg.saveChanges();

        // get the smtp transport for the address
        trans = session.getTransport(toAddr[0]);

        // register ourselves as listener for ConnectionEvents
        // and TransportEvents
        trans.addConnectionListener(this);
        trans.addTransportListener(this);

        // connect the transport
        trans.connect();

        // send the message
        trans.sendMessage(msg, toAddr);

        // give the EventQueue enough time to fire its events
        try {
            Thread.sleep(5);
        } catch (InterruptedException e) {
        }

    } catch (MessagingException mex) {
        // give the EventQueue enough time to fire its events
        try {
            Thread.sleep(5);
        } catch (InterruptedException e) {
        }

        mex.printStackTrace();
        System.out.println();
        Exception ex = mex;
        do {
            if (ex instanceof SendFailedException) {
                SendFailedException sfex = (SendFailedException) ex;
                Address[] invalid = sfex.getInvalidAddresses();
                if (invalid != null) {
                    System.out.println("    ** Invalid Addresses");
                    if (invalid != null) {
                        for (int i = 0; i < invalid.length; i++)
                            System.out.println("         " + invalid[i]);
                    }
                }
                Address[] validUnsent = sfex.getValidUnsentAddresses();
                if (validUnsent != null) {
                    System.out.println("    ** ValidUnsent Addresses");
                    if (validUnsent != null) {
                        for (int i = 0; i < validUnsent.length; i++)
                            System.out.println("         " + validUnsent[i]);
                    }
                }
                Address[] validSent = sfex.getValidSentAddresses();
                if (validSent != null) {
                    System.out.println("    ** ValidSent Addresses");
                    if (validSent != null) {
                        for (int i = 0; i < validSent.length; i++)
                            System.out.println("         " + validSent[i]);
                    }
                }
            }
            System.out.println();
            if (ex instanceof MessagingException)
                ex = ((MessagingException) ex).getNextException();
            else
                ex = null;
        } while (ex != null);
    } finally {
        try {
            // close the transport
            trans.close();
        } catch (MessagingException mex) { /* ignore */
        }
    }
}

From source file:com.krawler.spring.crm.caseModule.CrmCustomerCaseController.java

public ModelAndView custPassword_Change(HttpServletRequest request, HttpServletResponse response)
        throws ServletException {

    String newpass = request.getParameter("newpass");
    String currentpass = request.getParameter("curpass");
    String customerid = request.getParameter("customerid");
    String email = request.getParameter("email");
    Map model = new HashMap();
    // String replaceStr=request.getParameter("cdomain");
    String url = URLUtil.getRequestPageURL(request, Links.UnprotectedLoginPageFull);
    String loginurl = url.concat("caselogin.jsp");
    String name = request.getParameter("cname");
    boolean verify_pass = false;
    String responseMessage = "";
    if ((String) request.getSession().getAttribute(Constants.SESSION_CUSTOMER_ID) != null) {
        DefaultTransactionDefinition def = new DefaultTransactionDefinition();
        def.setName("JE_Tx");
        def.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRED);
        def.setIsolationLevel(TransactionDefinition.ISOLATION_READ_UNCOMMITTED);
        TransactionStatus status = txnManager.getTransaction(def);
        try {//from   www  . ja  v a 2 s .  c  om

            verify_pass = contactManagementService.verifyCurrentPass(currentpass, customerid);
            if (verify_pass) {
                contactManagementService.custPassword_Change(newpass, customerid);
                txnManager.commit(status);
                request.setAttribute("homepage", "true");
                request.setAttribute("success", "true");
                responseMessage = "usercases/redirect";
                String partnerNames = sessionHandlerImplObj.getPartnerName();
                String sysEmailId = sessionHandlerImplObj.getSystemEmailId();
                String passwordString = "Username: " + email + " <br/><br/>Password: <b>" + newpass + "</b>";
                String htmlmsg = "Dear <b>" + name
                        + "</b>,<br/><br/> Your <b>password has been changed</b> for your account on "
                        + partnerNames + " CRM. <br/><br/>" + passwordString + "<br/><br/>You can log in at:\n"
                        + loginurl + "<br/><br/>See you on " + partnerNames + " CRM <br/><br/> -The "
                        + partnerNames + " CRM Team";
                try {
                    SendMailHandler.postMail(new String[] { email }, "[" + partnerNames + "] Password Changed",
                            htmlmsg, "", sysEmailId, partnerNames + " Admin");
                } catch (MessagingException e) {
                    e.printStackTrace();
                }

            } else {
                request.setAttribute("changepassword", "true");
                request.setAttribute("mis_pass", "true");
                txnManager.commit(status);
            }

        } catch (Exception e) {
            logger.warn("custPassword_change Error:", e);
            txnManager.rollback(status);
            responseMessage = "../../usercases/failure";
        }
    } else {
        request.setAttribute("logout", "true");
    }
    responseMessage = "usercases/redirect";
    return new ModelAndView(responseMessage, "model", model);
}

From source file:org.infoglue.cms.util.mail.MailService.java

/**
 * /*w  w  w  .ja va  2s . com*/
 */
public void send(final Message message) throws SystemException {
    try {
        Transport.send(message);
    } catch (MessagingException e) {
        e.printStackTrace();
        throw new SystemException("Unable to send message.", e);
    }

}

From source file:org.infoglue.cms.util.mail.MailService.java

/**
 *
 * @param from the sender of the email.//from  www . ja  v a2  s  .c  om
 * @param to the recipient of the email.
 * @param subject the subject of the email.
 * @param content the body of the email.
 * @throws SystemException if the email couldn't be sent due to some mail server exception.
 */
public void send(String from, String to, String subject, String content, String contentType, String encoding)
        throws SystemException {
    final Message message = createMessage(from, to, null, subject, content, contentType, encoding);

    try {
        Transport.send(message);
    } catch (MessagingException e) {
        e.printStackTrace();
        throw new SystemException("Unable to send message.", e);
    }

}

From source file:TestOpenMailRelay.java

/** Do the work: send the mail to the SMTP server.  */
public void doSend() {

    // We need to pass info to the mail server as a Properties, since
    // JavaMail (wisely) allows room for LOTS of properties...
    Properties props = new Properties();

    // Your LAN must define the local SMTP server as "mailhost"
    // for this simple-minded version to be able to send mail...
    props.put("mail.smtp.host", "mailhost");

    // Create the Session object
    session = Session.getDefaultInstance(props, null);
    session.setDebug(true); // Verbose!

    try {/*from   ww w.  ja  v  a  2  s .c  o m*/
        // create a message
        mesg = new MimeMessage(session);

        // From Address - this should come from a Properties...
        mesg.setFrom(new InternetAddress("nobody@host.domain"));

        // TO Address 
        InternetAddress toAddress = new InternetAddress(message_recip);
        mesg.addRecipient(Message.RecipientType.TO, toAddress);

        // CC Address
        InternetAddress ccAddress = new InternetAddress(message_cc);
        mesg.addRecipient(Message.RecipientType.CC, ccAddress);

        // The Subject
        mesg.setSubject(message_subject);

        // Now the message body.
        mesg.setText(message_body);
        // XXX I18N: use setText(msgText.getText(), charset)

        // Finally, send the message!
        Transport.send(mesg);

    } catch (MessagingException ex) {
        while ((ex = (MessagingException) ex.getNextException()) != null) {
            ex.printStackTrace();
        }
    }
}

From source file:fr.treeptik.cloudunit.utils.EmailUtils.java

/**
 * public method to send mail parameter is map with emailType, user
 *
 * @param mapConfigEmail/*  ww w  .j a  v  a  2  s.c  o  m*/
 * @throws MessagingException
 */
@Async
public void sendEmail(Map<String, Object> mapConfigEmail) throws MessagingException {

    User user = (User) mapConfigEmail.get("user");
    String emailType = (String) mapConfigEmail.get("emailType");

    logger.info("start email configuration for " + emailType + " to : " + user.getEmail());
    logger.debug("EmailUtils : User " + user.toString());

    String body = null;
    try {
        mapConfigEmail = this.initEmailConfig(mapConfigEmail);
        mapConfigEmail = this.defineEmailType(mapConfigEmail);
        body = (String) mapConfigEmail.get("body");

        MimeMessage message = (MimeMessage) mapConfigEmail.get("message");

        // For Spring vagrant profil, we redirect all emails
        // If value is not set, we use the classic configuration
        if (applicationContext.getEnvironment().acceptsProfiles("vagrant")
                && emailForceRedirect.trim().length() > 0) {
            message.setRecipients(Message.RecipientType.TO, emailForceRedirect);
        } else {
            message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(user.getEmail()));
        }

        message.setContent(body, "text/html; charset=utf-8");

        Transport.send(message);

    } catch (MessagingException e) {
        logger.error("Error sendEmail method - " + e);
        e.printStackTrace();
    }
    logger.info("Email of " + emailType + " send to " + user.getEmail());

}

From source file:transport.java

public void go(Session session, InternetAddress[] toAddr, InternetAddress from) {
    Transport trans = null;/* ww w  .j  av  a2s.c  om*/

    try {
        // create a message
        Message msg = new MimeMessage(session);
        msg.setFrom(from);
        msg.setRecipients(Message.RecipientType.TO, toAddr);
        msg.setSubject("JavaMail APIs transport.java Test");
        msg.setSentDate(new Date()); // Date: header
        msg.setContent(msgText + msgText2, "text/plain");
        msg.saveChanges();

        // get the smtp transport for the address
        trans = session.getTransport(toAddr[0]);

        // register ourselves as listener for ConnectionEvents 
        // and TransportEvents
        trans.addConnectionListener(this);
        trans.addTransportListener(this);

        // connect the transport
        trans.connect();

        // send the message
        trans.sendMessage(msg, toAddr);

        // give the EventQueue enough time to fire its events
        try {
            Thread.sleep(5);
        } catch (InterruptedException e) {
        }

    } catch (MessagingException mex) {
        // give the EventQueue enough time to fire its events
        try {
            Thread.sleep(5);
        } catch (InterruptedException e) {
        }

        System.out.println("Sending failed with exception:");
        mex.printStackTrace();
        System.out.println();
        Exception ex = mex;
        do {
            if (ex instanceof SendFailedException) {
                SendFailedException sfex = (SendFailedException) ex;
                Address[] invalid = sfex.getInvalidAddresses();
                if (invalid != null) {
                    System.out.println("    ** Invalid Addresses");
                    for (int i = 0; i < invalid.length; i++)
                        System.out.println("         " + invalid[i]);
                }
                Address[] validUnsent = sfex.getValidUnsentAddresses();
                if (validUnsent != null) {
                    System.out.println("    ** ValidUnsent Addresses");
                    for (int i = 0; i < validUnsent.length; i++)
                        System.out.println("         " + validUnsent[i]);
                }
                Address[] validSent = sfex.getValidSentAddresses();
                if (validSent != null) {
                    System.out.println("    ** ValidSent Addresses");
                    for (int i = 0; i < validSent.length; i++)
                        System.out.println("         " + validSent[i]);
                }
            }
            System.out.println();
            if (ex instanceof MessagingException)
                ex = ((MessagingException) ex).getNextException();
            else
                ex = null;
        } while (ex != null);
    } finally {
        try {
            // close the transport
            if (trans != null)
                trans.close();
        } catch (MessagingException mex) {
            /* ignore */ }
    }
}

From source file:com.krawler.esp.handlers.ProfileHandler.java

public static void setPassword(Session session, HttpServletRequest request) throws ServiceException {
    try {// ww  w .  j  a v  a 2 s  .c  o  m
        String password = request.getParameter("password");
        if (password == null || password.length() <= 0) {
            password = AuthHandler.generateNewPassword();
        }
        String newpass = AuthHandler.getSHA1(password);
        User user = (User) session.load(User.class, request.getParameter("userid"));
        UserLogin userLogin = user.getUserLogin();
        userLogin.setPassword(newpass);
        session.saveOrUpdate(userLogin);
        String uri = URLUtil.getPageURL(request, Links.loginpageFull);
        String fname = user.getFirstName();
        if (StringUtil.isNullOrEmpty(fname)) {
            fname = user.getUserLogin().getUserName();
        }
        String pmsg = String.format(KWLErrorMsgs.msgTempPassword, fname, password, uri);
        String htmlmsg = String.format(KWLErrorMsgs.msgMailPassword, fname, password, uri, uri);
        try {
            String adminEmailId = request.getSession().getAttribute("sysemailid").toString();
            SendMailHandler.postMail(new String[] { user.getEmailID() }, KWLErrorMsgs.msgMailSubjectPassword,
                    htmlmsg, pmsg, adminEmailId);
        } catch (MessagingException e) {
            e.printStackTrace();
        }
    } catch (Exception e) {
        throw ServiceException.FAILURE("ProfileHandler.setPassword", e);
    }
}

From source file:gr.abiss.calipso.mail.MailSender.java

/**
 * we bend the rules a little and fire off a new thread for sending
 * an email message.  This has the advantage of not slowing down the item
 * create and update screens, i.e. the system returns the next screen
 * after "submit" without blocking.  This has been used in production
 * for quite a while now, on Tomcat without any problems.  This helps a lot
 * especially when the SMTP server is slow to respond, etc.
 *//*from  www  .  j a  va  2 s  .c o  m*/
private void sendInNewThread(final MimeMessage message) {
    //       try {
    //          logger.info("Sending message: " + message.getSubject() + "\n" + message.getContent());
    //      } catch (MessagingException e1) {
    //         // TODO Auto-generated catch block
    //         e1.printStackTrace();
    //      } catch (IOException e1) {
    //         // TODO Auto-generated catch block
    //         e1.printStackTrace();
    //      }
    if (logger.isDebugEnabled()) {
        try {
            logger.debug("Message contenttype: " + message.getContentType());
            logger.debug("Message content: " + message.getContent());
            Enumeration headers = message.getAllHeaders();

            logger.debug("Message Headers...");
            while (headers.hasMoreElements()) {
                Header h = (Header) headers.nextElement();
                logger.error(h.getName() + ": " + h.getValue());
            }
            logger.debug("Message flags: " + message.getFlags());
        } catch (MessagingException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
    new Thread() {
        @Override
        public void run() {
            logger.debug("send mail thread start");
            try {
                try {
                    sender.send(message);
                    logger.debug("send mail thread successfull");
                } catch (Exception e) {
                    logger.error("send mail thread failed, dumping headers: ");
                    logger.error("mail headers dump start");
                    Enumeration headers = message.getAllHeaders();
                    while (headers.hasMoreElements()) {
                        Header h = (Header) headers.nextElement();
                        logger.error(h.getName() + ": " + h.getValue());
                    }
                    logger.error("mail headers dump end, exception follows", e);
                }
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
        }
    }.start();
}