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.robin.utilities.Utilities.java

/**
 * A utility that waits for a gmail mailbox to receive a new message with
 * according to a given SearchTerm. Only "Not seen" messages are searched,
 * and all match is set as SEEN, but just the first occurrence of the
 * matching message is returned./* w  ww  . jav  a  2 s.co  m*/
 * @param username the mailbox owner's user name (no @gmail.com required).
 * @param pass the user password protecting this mailbox
 * @param st the SearchTerm built to filter messages
 * @param timeoutMessage the message to show when no such mail found within
 *            timeout
 * @param timeout The maximum amount of time to wait in milliseconds.
 * @return a last from the new messages thats match the st conditions
 */
public EMail waitForMailWithSearchTerm(final String username, final String pass, final SearchTerm st,
        final String timeoutMessage, final long timeout) {
    String host = "imap.gmail.com";
    final long retryTime = 1000;

    Properties props = System.getProperties();
    props.setProperty("mail.store.protocol", "imaps");
    props.put("mail.imaps.ssl.trust", "*");
    EMail email = null;
    Session session = Session.getDefaultInstance(props, null);
    try {
        Store store = session.getStore("imaps");
        store.connect(host, username, pass);
        Folder inbox = store.getFolder("Inbox");
        inbox.open(Folder.READ_WRITE);
        FluentWait<Folder> waitForMail = new FluentWait<Folder>(inbox)
                .withTimeout(timeout, TimeUnit.MILLISECONDS).pollingEvery(retryTime, TimeUnit.MILLISECONDS)
                .withMessage(timeoutMessage);
        email = waitForMail.until(new Function<Folder, EMail>() {
            @Override
            public EMail apply(final Folder inbox) {
                EMail email = null;
                FlagTerm ft = new FlagTerm(new Flags(Flags.Flag.SEEN), false);
                SearchTerm sst = new AndTerm(ft, st);
                try {
                    inbox.getMessageCount();
                    Message[] messages = inbox.search(sst);
                    for (Message message : messages) {
                        message.setFlag(Flag.SEEN, true);
                    }
                    if (messages.length > 0) {
                        return new EMail(messages[0]);
                    }
                } catch (MessagingException e) {
                    Assert.fail(e.getMessage());
                }
                return email;
            }
        });
        inbox.close(false);
        store.close();
    } catch (MessagingException e) {
        Assert.fail(e.getMessage());
    }
    return email;
}

From source file:org.bibsonomy.util.MailUtils.java

/** Sends the registration mail to the user and to the project admins.
 * /*from www .j  av  a 2 s  .  c  o  m*/
 * @param userName - the name of the user which registered. 
 * @param userEmail - the email address of the user which registered.
 * @param inetAddress - TODO: unused
 * @param locale - a locale to use for localization
 * @return <code>true</code>, if the email could be send without errors.
 */
public boolean sendActivationMail(final String userName, final String userEmail, final String inetAddress,
        final Locale locale) {
    final Object[] messagesParameters = new Object[] { userName, projectName, projectHome, projectBlog,
            projectEmail };
    /*
     * Format the message "mail.registration.body" with the given parameters.
     */
    final String messageBody = messageSource.getMessage("mail.activation.body", messagesParameters, locale);
    final String messageSubject = messageSource.getMessage("mail.activation.subject", messagesParameters,
            locale);

    /*
     * set the recipients
     */
    final String[] recipient = { userEmail };
    try {
        sendMail(recipient, messageSubject, messageBody, projectRegistrationFromAddress);
        return true;
    } catch (final MessagingException e) {
        log.fatal("Could not send registration mail: " + e.getMessage());
    }
    return false;
}

From source file:org.bibsonomy.util.MailUtils.java

/** 
 * Sends the registration mail to the user and to the project admins.
 * //from ww  w .jav  a 2  s.  c  o m
 * @param userName - the name of the user which registered. 
 * @param userEmail - the email address of the user which registered.
 * @param activationCode - user activation code
 * @param inetAddress - TODO: unused!!!
 * @param locale - a locale to use for localization
 * @return <code>true</code>, if the email could be send without errors.
 */
public boolean sendRegistrationMail(final String userName, final String userEmail, final String activationCode,
        final String inetAddress, final Locale locale) {
    final Object[] messagesParameters = new Object[] { userName, projectName, projectHome, projectBlog,
            projectEmail, activationCode };
    /*
     * Format the message "mail.registration.body" with the given parameters.
     */
    final String messageBody = messageSource.getMessage("mail.registration.body", messagesParameters, locale);
    final String messageSubject = messageSource.getMessage("mail.registration.subject", messagesParameters,
            locale);

    /*
     * set the recipients
     */
    final String[] recipient = { userEmail };
    try {
        sendMail(recipient, messageSubject, messageBody, projectRegistrationFromAddress);
        return true;
    } catch (final MessagingException e) {
        log.fatal("Could not send registration mail: " + e.getMessage());
    }
    return false;
}

From source file:cz.zcu.kiv.eegdatabase.data.service.SpringJavaMailService.java

protected MimeMessage createMimeMessage(String from, String to, String subject, String emailBody)
        throws MailException {
    try {// w w w .j a v  a 2s.  co m
        MimeMessage mimeMessage = mailSender.createMimeMessage();
        MimeMessageHelper message = new MimeMessageHelper(mimeMessage);
        message.setFrom(from);
        // message.setContent("text/html");
        message.setTo(to);
        message.setSubject(subject);
        message.setText(emailBody, true);
        log.debug("Message " + message);
        return mimeMessage;
    } catch (MessagingException e) {// rethrow as MailException
        throw new MailPreparationException(e.getMessage(), e);
    }
}

From source file:com.threewks.thundr.gmail.GmailMailer.java

/**
 * Create a MimeMessage using the parameters provided.
 *
 * @param to       Email address of the receiver.
 * @param from     Email address of the sender, the mailbox account.
 * @param subject  Subject of the email.
 * @param bodyText Body text of the email.
 * @return MimeMessage to be used to send email.
 * @throws MessagingException/* www.  j  a v a  2  s.  c  o m*/
 */
protected MimeMessage createEmailWithAttachment(Set<InternetAddress> to, InternetAddress from,
        Set<InternetAddress> cc, Set<InternetAddress> bcc, InternetAddress replyTo, String subject,
        String bodyText, List<com.threewks.thundr.mail.Attachment> attachments) {
    Properties props = new Properties();
    Session session = Session.getDefaultInstance(props, null);

    MimeMessage email = new MimeMessage(session);
    try {

        email.setFrom(from);

        if (to != null) {
            email.addRecipients(javax.mail.Message.RecipientType.TO,
                    to.toArray(new InternetAddress[to.size()]));
        }
        if (cc != null) {
            email.addRecipients(javax.mail.Message.RecipientType.CC,
                    cc.toArray(new InternetAddress[cc.size()]));
        }
        if (bcc != null) {
            email.addRecipients(javax.mail.Message.RecipientType.BCC,
                    bcc.toArray(new InternetAddress[bcc.size()]));
        }
        if (replyTo != null) {
            email.setReplyTo(new Address[] { replyTo });
        }

        email.setSubject(subject);

        MimeBodyPart mimeBodyPart = new MimeBodyPart();
        mimeBodyPart.setContent(bodyText, "text/html");
        mimeBodyPart.setHeader("Content-Type", "text/html; charset=\"UTF-8\"");

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

        if (attachments != null) {
            for (com.threewks.thundr.mail.Attachment attachment : attachments) {
                mimeBodyPart = new MimeBodyPart();

                BasicViewRenderer renderer = new BasicViewRenderer(viewResolverRegistry);
                renderer.render(attachment.view());
                byte[] data = renderer.getOutputAsBytes();
                String attachmentContentType = renderer.getContentType();
                String attachmentCharacterEncoding = renderer.getCharacterEncoding();

                populateMimeBodyPart(mimeBodyPart, attachment, data, attachmentContentType,
                        attachmentCharacterEncoding);

                multipart.addBodyPart(mimeBodyPart);
            }
        }

        email.setContent(multipart);
    } catch (MessagingException e) {
        Logger.error(e.getMessage());
        Logger.error(
                "Failed to create email from: %s;%s, to: %s, cc: %s, bcc: %s, replyTo %s;%s, subject %s, body %s, number of attachments %d",
                from.getAddress(), from.getPersonal(), Transformers.InternetAddressesToString.from(to),
                Transformers.InternetAddressesToString.from(cc),
                Transformers.InternetAddressesToString.from(bcc),
                replyTo == null ? "null" : replyTo.getAddress(),
                replyTo == null ? "null" : replyTo.getPersonal(), subject, bodyText,
                attachments == null ? 0 : attachments.size());
        throw new GmailException(e);
    }

    return email;
}

From source file:org.bibsonomy.util.MailUtils.java

/** 
 * Sends the registration mail to the user and to the group admins.
 *//*from   w  ww.  j ava  2s .  c o m*/
public boolean sendJoinGroupDenied(final String groupName, final String deniedUserName,
        final String deniedUserEMail, final String reason, final Locale locale) {
    Object[] messagesParameters;
    messagesParameters = new Object[] { groupName, deniedUserName, reason, projectHome, null, null,
            projectName.toLowerCase(), projectEmail };
    /*
     * Format the message "mail.registration.body" with the given parameters.
     */
    final String messageBody = messageSource.getMessage("mail.joinGroupRequest.denied.body", messagesParameters,
            locale);
    final String messageSubject = messageSource.getMessage("mail.joinGroupRequest.denied.subject",
            messagesParameters, locale);

    /*
     * set the recipients
     */
    final String[] recipient = { deniedUserEMail };
    try {
        sendMail(recipient, messageSubject, messageBody, projectJoinGroupRequestFromAddress);
        return true;
    } catch (final MessagingException e) {
        log.fatal("Could not send Deny JoinGrouprequest mail: " + e.getMessage());
    }
    return false;
}

From source file:org.bibsonomy.util.MailUtils.java

/** 
 * Sends the registration mail to the user and to the group admins.
 *//*from   w  w w  .  j ava 2s. c o m*/
public boolean sendJoinGroupRequest(final String groupName, final String groupMail, final User loginUser,
        final String reason, final Locale locale) {
    Object[] messagesParameters;
    try {
        messagesParameters = new Object[] { groupName, loginUser.getName(), reason, projectHome,
                URLEncoder.encode(groupName, "UTF-8").toLowerCase(),
                URLEncoder.encode(loginUser.getName(), "UTF-8").toLowerCase(), projectName.toLowerCase(),
                projectEmail };
    } catch (UnsupportedEncodingException e1) {
        throw new InternServerException(e1.getMessage());
    }
    /*
     * Format the message "mail.registration.body" with the given parameters.
     */
    final String messageBody = messageSource.getMessage("mail.joinGroupRequest.body", messagesParameters,
            locale);
    final String messageSubject = messageSource.getMessage("mail.joinGroupRequest.subject", messagesParameters,
            locale);

    /*
     * send an e-Mail to the group (from our registration Adress)
     */
    try {
        sendMail(new String[] { groupMail }, messageSubject, messageBody, projectJoinGroupRequestFromAddress);
        return true;
    } catch (final MessagingException e) {
        log.fatal("Could not send join group request mail: " + e.getMessage());
    }
    return false;
}

From source file:com.epam.ta.reportportal.core.admin.ServerAdminHandlerImpl.java

@Override
public OperationCompletionRS saveEmailSettings(String profileId, ServerEmailResource request) {
    ServerSettings settings = findServerSettings(profileId);
    if (null != request) {
        ServerEmailDetails serverEmailConfig = new ServerEmailDetails();

        if (request.isDebug())
            serverEmailConfig.setDebug(request.isDebug());

        if (null != request.getHost())
            serverEmailConfig.setHost(request.getHost());

        int port = request.getPort();
        if ((port <= 0) || (port > 65535))
            BusinessRule.fail().withError(ErrorType.INCORRECT_REQUEST,
                    "Incorrect 'Port' value. Allowed value is [1..65535]");
        serverEmailConfig.setPort(port);

        if (null != request.getProtocol())
            serverEmailConfig.setProtocol(request.getProtocol());
        if (request.getAuthEnabled()) {
            serverEmailConfig.setAuthEnabled(request.getAuthEnabled());
            if (null != request.getUsername())
                serverEmailConfig.setUsername(request.getUsername());
            if (null != request.getPassword())
                serverEmailConfig.setPassword(simpleEncryptor.encrypt(request.getPassword()));

        } else {/*from   ww  w .ja  v a 2  s  . c o m*/
            serverEmailConfig.setAuthEnabled(false);
            /* Auto-drop values on switched-off authentication */
            serverEmailConfig.setUsername(null);
            serverEmailConfig.setPassword(null);
        }

        serverEmailConfig.setStarTlsEnabled(Boolean.TRUE.equals(request.isStarTlsEnabled()));
        serverEmailConfig.setSslEnabled(Boolean.TRUE.equals(request.isSslEnabled()));

        //expect(UserUtils.isEmailValid(email), equalTo(true)).verify(BAD_REQUEST_ERROR, email);
        ofNullable(request.getFrom()).ifPresent(serverEmailConfig::setFrom);

        try {
            emailServiceFactory.getEmailService(serverEmailConfig).get().testConnection();
        } catch (MessagingException ex) {
            LOGGER.error("Cannot send email to user", ex);
            fail().withError(FORBIDDEN_OPERATION,
                    "Email configuration is incorrect. Please, check your configuration. " + ex.getMessage());
        }
        ServerSettings update = new ServerSettings();
        update.setId(settings.getId());
        //TODO active primitive should be replaced with Object(Boolean) type
        update.setActive(settings.getActive());
        update.setServerEmailDetails(serverEmailConfig);

        repository.partialUpdate(update);
    }
    return new OperationCompletionRS(
            "Server Settings with profile '" + profileId + "' is successfully updated.");
}

From source file:org.socraticgrid.hl7.ucs.nifi.processor.SendEmail.java

private String sendEmail(String emailSubject, String fromEmail, String toEmail, String emailBody,
        String mimeType, String charset, String smtpServerUrl, String smtpServerPort, String username,
        String password, ServiceStatusController serviceStatusControllerService) throws Exception {

    String statusMessage = "Email sent successfully to " + toEmail;

    Properties props = new Properties();
    props.put("mail.smtp.auth", "true");
    props.put("mail.smtp.starttls.enable", "true");
    props.put("mail.smtp.host", smtpServerUrl);
    props.put("mail.smtp.port", smtpServerPort);

    Session session = Session.getInstance(props, new javax.mail.Authenticator() {
        protected PasswordAuthentication getPasswordAuthentication() {
            return new PasswordAuthentication(username, password);
        }/*from   w  ww .j a va 2s  . co  m*/
    });
    try {
        MimeMessage message = new MimeMessage(session);
        message.setFrom(new InternetAddress(fromEmail));
        message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(toEmail));
        message.setSubject(emailSubject);
        message.setContent(emailBody, mimeType + "; charset=" + charset);
        Transport.send(message);
        getLogger().info("Email sent successfully!");
        serviceStatusControllerService.updateServiceStatus("EMAIL", Status.AVAILABLE);
    } catch (MessagingException e) {
        serviceStatusControllerService.updateServiceStatus("EMAIL", Status.UNAVAILABLE);
        getLogger().error("Unable to send Email! Reason : " + e.getMessage(), e);
        statusMessage = "Unable to send Email! Reason : " + e.getMessage();
        throw new RuntimeException(e);
    }
    return statusMessage;
}

From source file:org.openadaptor.auxil.connector.smtp.SMTPConnection.java

/**
 * Set up javamail objects required to create connection to smtp server.
 * @throws ConnectionException/*from www . ja va2s  .c om*/
 */
protected void createConnection() throws ConnectionException {
    Session session;

    try {
        log.debug("To: " + to);
        log.debug("Subject: " + subject);

        Properties props = System.getProperties();
        if (mailHost != null) {
            props.put("mail.smtp.host", mailHost);
            props.put("mail.smtp.port", mailHostPort);
        } else {
            throw new ConnectionException("FATAL: mailHost property not set", this);
        }
        // Get a Session object
        session = Session.getInstance(props, null);

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

        message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(to, false));
        if (cc != null)
            message.setRecipients(Message.RecipientType.CC, InternetAddress.parse(cc, false));
        if (bcc != null)
            message.setRecipients(Message.RecipientType.BCC, InternetAddress.parse(bcc, false));

        message.setSubject(subject);

        message.setHeader("X-Mailer", mailer);
        message.setSentDate(new Date());

    } catch (MessagingException me) {
        throw new ConnectionException(me.getMessage(), me, this);
    }
    log.debug("Successfully connected.");
    connected = true;
}