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:com.threewks.thundr.mail.JavaMailMailer.java

@Override
protected void sendInternal(Map.Entry<String, String> from, Map.Entry<String, String> replyTo,
        Map<String, String> to, Map<String, String> cc, Map<String, String> bcc, String subject, Object body,
        List<Attachment> attachments) {
    try {//from  w ww. j av  a 2s  . c om
        Session emailSession = getSession();

        Message message = new MimeMessage(emailSession);
        message.setFrom(emailAddress(from));
        if (replyTo != null) {
            message.setReplyTo(new Address[] { emailAddress(replyTo) });
        }

        message.setSubject(subject);

        BasicViewRenderer viewRenderer = render(body);
        String content = viewRenderer.getOutputAsString();
        String contentType = ContentType.cleanContentType(viewRenderer.getContentType());
        contentType = StringUtils.isBlank(contentType) ? ContentType.TextHtml.value() : contentType;

        if (Expressive.isEmpty(attachments)) {
            message.setContent(content, contentType);
        } else {
            Multipart multipart = new MimeMultipart("mixed"); // subtype must be "mixed" or inline & regular attachments won't play well together
            addBody(multipart, content, contentType);
            addAttachments(multipart, attachments);
            message.setContent(multipart);
        }

        addRecipients(to, message, RecipientType.TO);
        addRecipients(cc, message, RecipientType.CC);
        addRecipients(bcc, message, RecipientType.BCC);

        sendMessage(message);
    } catch (MessagingException e) {
        throw new MailException(e, "Failed to send an email: %s", e.getMessage());
    }
}

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

/**
 *
 * @param from the sender of the email./*from w w  w .ja v  a  2 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 bcc, String subject, String content, String contentType,
        String encoding, List attachments) throws SystemException {
    final Message message = createMessage(from, to, bcc, subject, content, contentType, encoding, attachments);

    try {
        Transport.send(message);
        log.info("Mail sent...");
    } catch (MessagingException e) {
        log.error("Unable to send message: " + e.getMessage(), e);
        //e.printStackTrace();
        throw new SystemException("Unable to send message.", e);
    }
}

From source file:org.restcomm.connect.email.EmailService.java

EmailResponse sendEmailSsL(final Mail mail) {
    try {/*from w  ww  . j ava 2s  . c o m*/
        InternetAddress from;
        if (mail.from() != null || !mail.from().equalsIgnoreCase("")) {
            from = new InternetAddress(mail.from());
        } else {
            from = new InternetAddress(user);
        }
        final InternetAddress to = new InternetAddress(mail.to());
        final MimeMessage email = new MimeMessage(session);
        email.setFrom(from);
        email.addRecipient(Message.RecipientType.TO, to);
        email.setSubject(mail.subject());
        email.setText(mail.body());
        email.addRecipients(Message.RecipientType.CC, InternetAddress.parse(mail.cc(), false));
        email.addRecipients(Message.RecipientType.BCC, InternetAddress.parse(mail.bcc(), false));
        //Transport.send(email);
        transport.connect(host, Integer.parseInt(port), user, password);
        transport.sendMessage(email, email.getRecipients(Message.RecipientType.TO));
        return new EmailResponse(mail);
    } catch (final MessagingException exception) {
        logger.error(exception.getMessage(), exception);
        return new EmailResponse(exception, exception.getMessage());
    }
}

From source file:be.fedict.eid.dss.model.bean.TaskMDB.java

private void sendMail(String mailTo, String subject, String messageBody, String attachmentMimetype,
        byte[] attachment) {
    LOG.debug("sending email to " + mailTo + " with subject \"" + subject + "\"");
    String smtpServer = this.configuration.getValue(ConfigProperty.SMTP_SERVER, String.class);
    if (null == smtpServer || smtpServer.trim().isEmpty()) {
        LOG.warn("no SMTP server configured");
        return;/* www  .  j  a va 2 s .  co  m*/
    }
    String mailFrom = this.configuration.getValue(ConfigProperty.MAIL_FROM, String.class);
    if (null == mailFrom || mailFrom.trim().isEmpty()) {
        LOG.warn("no mail from address configured");
        return;
    }
    LOG.debug("mail from: " + mailFrom);

    Properties props = new Properties();
    props.put("mail.smtp.host", smtpServer);
    props.put("mail.from", mailFrom);

    String mailPrefix = this.configuration.getValue(ConfigProperty.MAIL_PREFIX, String.class);
    if (null != mailPrefix && false == mailPrefix.trim().isEmpty()) {
        subject = "[" + mailPrefix.trim() + "] " + subject;
    }

    Session session = Session.getInstance(props, null);
    try {
        MimeMessage mimeMessage = new MimeMessage(session);
        mimeMessage.setFrom();
        mimeMessage.setRecipients(RecipientType.TO, mailTo);
        mimeMessage.setSubject(subject);
        mimeMessage.setSentDate(new Date());

        MimeBodyPart mimeBodyPart = new MimeBodyPart();
        mimeBodyPart.setText(messageBody);

        Multipart multipart = new MimeMultipart();
        // first part is body
        multipart.addBodyPart(mimeBodyPart);

        // second part is attachment
        if (null != attachment) {
            MimeBodyPart attachmentMimeBodyPart = new MimeBodyPart();
            DataSource dataSource = new ByteArrayDataSource(attachment, attachmentMimetype);
            attachmentMimeBodyPart.setDataHandler(new DataHandler(dataSource));
            multipart.addBodyPart(attachmentMimeBodyPart);
        }

        mimeMessage.setContent(multipart);
        Transport.send(mimeMessage);
    } catch (MessagingException e) {
        throw new RuntimeException("send failed, exception: " + e.getMessage(), e);
    }
}

From source file:at.molindo.notify.channel.mail.AbstractMailClient.java

protected String toErrorMessage(MessagingException e) {
    return e == null ? null : e.getMessage();
}

From source file:com.google.code.rptm.mailarchive.DefaultMailingListArchive.java

public void retrieveMessages(String mailingList, YearMonth month, MimeMessageProcessor processor,
        MailingListArchiveEventListener eventListener) throws MailingListArchiveException {
    Session session = Session.getDefaultInstance(new Properties());
    try {/*from ww  w.ja  v  a  2s  .c  o m*/
        Store store = session.getStore(new URLName("mstor:" + getMboxFile(mailingList, month, eventListener)));
        store.connect();
        try {
            Folder folder = store.getDefaultFolder();
            folder.open(Folder.READ_ONLY);
            for (Message msg : folder.getMessages()) {
                if (!processor.processMessage((MimeMessage) msg)) {
                    break;
                }
            }
        } finally {
            store.close();
        }
    } catch (MessagingException ex) {
        throw new MailingListArchiveException("JavaMail exception: " + ex.getMessage(), ex);
    } catch (IOException ex) {
        throw new MailingListArchiveException("I/O exception: " + ex.getMessage(), ex);
    }
}

From source file:com.cubusmail.server.mail.security.MailboxLoginModule.java

public boolean logout() throws LoginException {

    log.debug("Start logout...");
    try {/*from w ww .  j a  v a2 s.  c  o  m*/
        SecurityUtils.getMailboxPrincipal(this.subject).getMailbox().logout();
    } catch (MessagingException e) {
        // nothing to do
        log.warn(e.getMessage());
    }
    log.debug("Logout successful");

    this.subject.getPrincipals().remove(SecurityUtils.getMailboxPrincipal(this.subject));

    return true;
}

From source file:com.cubusmail.server.services.RetrieveImageServlet.java

/**
 * @param parent//from www  .j a va 2 s.c om
 * @return
 */
private Part findImagePart(Part parent) {

    try {
        if (MessageUtils.isImagepart(parent)) {
            return parent;
        } else if (parent.isMimeType("multipart/*")) {
            Multipart mp;
            mp = (Multipart) parent.getContent();
            int count = mp.getCount();
            for (int i = 0; i < count; i++) {
                Part subPart = findImagePart(mp.getBodyPart(i));
                if (subPart != null) {
                    return subPart;
                }
            }
        }
    } catch (MessagingException e) {
        log.error(e.getMessage(), e);
    } catch (IOException e) {
        log.error(e.getMessage(), e);
    }

    return null;
}

From source file:com.cubusmail.server.mail.security.MailboxLoginModule.java

public boolean login() throws LoginException {

    if (this.callbackHandler == null) {
        log.fatal("callbackHandler is null");
        throw new LoginException(IErrorCodes.EXCEPTION_AUTHENTICATION_FAILED);
    }/*  w  ww  .ja  v a  2  s . c  o  m*/

    Callback[] callbacks = new Callback[2];
    callbacks[0] = new NameCallback("Username");
    callbacks[1] = new PasswordCallback("Password", false);

    try {
        this.callbackHandler.handle(callbacks);
        String username = ((NameCallback) callbacks[0]).getName();

        char[] tmpPassword = ((PasswordCallback) callbacks[1]).getPassword();
        if (tmpPassword == null) {
            // treat a NULL password as an empty password
            tmpPassword = new char[0];
        }
        char[] password = new char[tmpPassword.length];
        System.arraycopy(tmpPassword, 0, password, 0, tmpPassword.length);
        ((PasswordCallback) callbacks[1]).clearPassword();

        // start authentication
        // TODO: very dirty, must be replaced by Spring Security stuff
        ApplicationContext context = WebApplicationContextUtils
                .getRequiredWebApplicationContext(SessionManager.getRequest().getSession().getServletContext());
        MailboxFactory factory = context.getBean(MailboxFactory.class);
        IMailbox mailbox = factory.createMailbox(IMailbox.TYPE_IMAP);
        mailbox.init(username, new String(password));

        log.debug("Start login...");
        mailbox.login();
        log.debug("Login successful");

        this.mailboxPrincipal = new MailboxPrincipal(username, mailbox);
        this.succeeded = true;
    } catch (IOException ioe) {
        log.error(ioe.getMessage(), ioe);
        throw new LoginException(ioe.toString());
    } catch (UnsupportedCallbackException uce) {
        log.error(uce.getMessage(), uce);
        throw new LoginException(IErrorCodes.EXCEPTION_AUTHENTICATION_FAILED);
    } catch (MessagingException e) {
        log.error(e.getMessage(), e);
        mapMessagingException(e);
    }

    return this.succeeded;
}

From source file:org.overlord.sramp.governance.services.NotificationResource.java

/**
 * POST to email a notification about an artifact.
 *
 * @param environment/* ww w.j a v  a2s  .c  o m*/
 * @param uuid
 * @throws SrampAtomException
 */
@POST
@Path("email/{group}/{template}/{target}/{uuid}")
@Produces("application/xml")
public Map<String, ValueEntity> emailNotification(@Context HttpServletRequest request,
        @PathParam("group") String group, @PathParam("template") String template,
        @PathParam("target") String target, @PathParam("uuid") String uuid) throws Exception {

    Map<String, ValueEntity> results = new HashMap<String, ValueEntity>();
    try {
        // 0. run the decoder on the arguments, after replacing * by % (this so parameters can
        //    contain slashes (%2F)
        group = SlashDecoder.decode(group);
        template = SlashDecoder.decode(template);
        target = SlashDecoder.decode(target);
        uuid = SlashDecoder.decode(uuid);

        // 1. get the artifact from the repo
        SrampAtomApiClient client = SrampAtomApiClientFactory.createAtomApiClient();
        QueryResultSet queryResultSet = client.buildQuery("/s-ramp[@uuid = ?]").parameter(uuid).query(); //$NON-NLS-1$
        if (queryResultSet.size() == 0) {
            results.put(GovernanceConstants.STATUS, new ValueEntity("fail")); //$NON-NLS-1$
            results.put(GovernanceConstants.MESSAGE,
                    new ValueEntity("Could not obtain artifact from repository.")); //$NON-NLS-1$
            return results;
        }
        ArtifactSummary artifactSummary = queryResultSet.iterator().next();

        // 2. get the destinations for this group
        NotificationDestinations destinations = governance.getNotificationDestinations("email").get(group); //$NON-NLS-1$
        if (destinations == null) {
            destinations = new NotificationDestinations(group, governance.getDefaultEmailFromAddress(),
                    group + "@" + governance.getDefaultEmailDomain()); //$NON-NLS-1$
        }

        // 3. send the email notification
        try {
            MimeMessage m = new MimeMessage(mailSession);
            Address from = new InternetAddress(destinations.getFromAddress());
            Address[] to = new InternetAddress[destinations.getToAddresses().length];
            for (int i = 0; i < destinations.getToAddresses().length; i++) {
                to[i] = new InternetAddress(destinations.getToAddresses()[i]);
            }
            m.setFrom(from);
            m.setRecipients(Message.RecipientType.TO, to);

            String subject = "/governance-email-templates/" + template + ".subject.tmpl"; //$NON-NLS-1$ //$NON-NLS-2$
            URL subjectUrl = Governance.class.getClassLoader().getResource(subject);
            if (subjectUrl != null)
                subject = IOUtils.toString(subjectUrl);
            subject = subject.replaceAll("\\$\\{uuid}", uuid); //$NON-NLS-1$
            subject = subject.replaceAll("\\$\\{name}", artifactSummary.getName()); //$NON-NLS-1$
            subject = subject.replaceAll("\\$\\{target}", target); //$NON-NLS-1$
            m.setSubject(subject);

            m.setSentDate(new java.util.Date());
            String content = "/governance-email-templates/" + template + ".body.tmpl"; //$NON-NLS-1$ //$NON-NLS-2$
            URL contentUrl = Governance.class.getClassLoader().getResource(content);
            if (contentUrl != null)
                content = IOUtils.toString(contentUrl);
            content = content.replaceAll("\\$\\{uuid}", uuid); //$NON-NLS-1$
            content = content.replaceAll("\\$\\{name}", artifactSummary.getName()); //$NON-NLS-1$
            content = content.replaceAll("\\$\\{target}", target); //$NON-NLS-1$
            content = content.replaceAll("\\$\\{dtgovurl}", governance.getDTGovUiUrl()); //$NON-NLS-1$
            m.setContent(content, "text/plain"); //$NON-NLS-1$
            Transport.send(m);
        } catch (javax.mail.MessagingException e) {
            logger.error(e.getMessage(), e);
        }

        // 4. build the response
        results.put(GovernanceConstants.STATUS, new ValueEntity("success")); //$NON-NLS-1$

        return results;
    } catch (Exception e) {
        logger.error(Messages.i18n.format("NotificationResource.EmailError", e.getMessage(), e)); //$NON-NLS-1$
        throw new SrampAtomException(e);
    }
}