Example usage for javax.mail.internet MimeMessage MimeMessage

List of usage examples for javax.mail.internet MimeMessage MimeMessage

Introduction

In this page you can find the example usage for javax.mail.internet MimeMessage MimeMessage.

Prototype

public MimeMessage(MimeMessage source) throws MessagingException 

Source Link

Document

Constructs a new MimeMessage with content initialized from the source MimeMessage.

Usage

From source file:mitm.application.djigzo.james.mailets.RequestSenderCertificateTest.java

@Test
public void testRequestCertificateNotAddUser() throws Exception {
    MockMailetConfig mailetConfig = new MockMailetConfig();

    RequestSenderCertificate mailet = new RequestSenderCertificate();

    mailetConfig.setInitParameter("addUser", "false");

    mailet.init(mailetConfig);/*from w  w w.  j a va  2s .co m*/

    MockMail mail = new MockMail();

    MimeMessage message = new MimeMessage(MailSession.getDefaultSession());

    String from = "from@example.com";
    String to = "to@example.com";

    message.setContent("test", "text/plain");
    message.setFrom(new InternetAddress(from));

    message.saveChanges();

    mail.setMessage(message);

    Collection<MailAddress> recipients = new LinkedList<MailAddress>();

    recipients.add(new MailAddress(to));

    mail.setRecipients(recipients);

    mail.setSender(new MailAddress("somethingelse@example.com"));

    assertFalse(proxy.isUser(from));
    assertFalse(proxy.isUser(to));

    mailet.service(mail);

    assertEquals(INITIAL_KEY_STORE_SIZE + 1, proxy.getKeyAndCertStoreSize());

    assertFalse(proxy.isUser(to));
    assertFalse(proxy.isUser(from));
}

From source file:de.egore911.opengate.services.PilotService.java

@POST
@Path("/register")
@Produces("application/json")
@Documentation("Register a new pilot. This will at first verify the login and email are "
        + "unique and the email is valid. After this it will register the pilot and send "
        + "and email to him to verify the address. The 'verify' will finalize the registration. "
        + "This method returns a JSON object containing a status field, i.e. {status: 'failed', "
        + "details: '...'} in case of an error and {status: 'ok', id: ...}. If an internal "
        + "error occured an HTTP 500 will be sent.")
public Response performRegister(@FormParam("login") String login, @FormParam("email") String email,
        @FormParam("faction_id") @Documentation("ID of the faction this pilot will be working for") long factionId) {
    JSONObject jsonObject = new JSONObject();
    EntityManager em = EntityManagerFilter.getEntityManager();
    Number n = (Number) em
            .createQuery("select count(pilot.key) from Pilot pilot " + "where pilot.login = (:login)")
            .setParameter("login", login).getSingleResult();
    if (n.intValue() > 0) {
        try {//from  w w w.ja v  a  2  s.  c o m
            StatusHelper.failed(jsonObject, "Duplicate login");
            return Response.ok(jsonObject.toString()).build();
        } catch (JSONException e) {
            LOG.log(Level.SEVERE, e.getMessage(), e);
            return Response.status(Status.INTERNAL_SERVER_ERROR).build();
        }
    }

    n = (Number) em.createQuery("select count(pilot.key) from Pilot pilot " + "where pilot.email = (:email)")
            .setParameter("email", email).getSingleResult();
    if (n.intValue() > 0) {
        try {
            StatusHelper.failed(jsonObject, "Duplicate email");
            return Response.ok(jsonObject.toString()).build();
        } catch (JSONException e) {
            LOG.log(Level.SEVERE, e.getMessage(), e);
            return Response.status(Status.INTERNAL_SERVER_ERROR).build();
        }
    }

    InternetAddress recipient;
    try {
        recipient = new InternetAddress(email, login);
    } catch (UnsupportedEncodingException e1) {
        try {
            StatusHelper.failed(jsonObject, "Invalid email");
            return Response.ok(jsonObject.toString()).build();
        } catch (JSONException e) {
            LOG.log(Level.SEVERE, e.getMessage(), e);
            return Response.status(Status.INTERNAL_SERVER_ERROR).build();
        }
    }

    Faction faction;
    try {
        faction = em.find(Faction.class, factionId);
    } catch (NoResultException e) {
        try {
            StatusHelper.failed(jsonObject, "Invalid faction");
            return Response.ok(jsonObject.toString()).build();
        } catch (JSONException e1) {
            LOG.log(Level.SEVERE, e.getMessage(), e1);
            return Response.status(Status.INTERNAL_SERVER_ERROR).build();
        }
    }

    Vessel vessel;
    try {
        vessel = (Vessel) em
                .createQuery("select vessel from Vessel vessel " + "where vessel.faction = :faction "
                        + "order by vessel.techLevel asc")
                .setParameter("faction", faction).setMaxResults(1).getSingleResult();
        // TODO assign initical equipment as well
    } catch (NoResultException e) {
        try {
            StatusHelper.failed(jsonObject, "Faction has no vessel");
            return Response.ok(jsonObject.toString()).build();
        } catch (JSONException e1) {
            LOG.log(Level.SEVERE, e.getMessage(), e1);
            return Response.status(Status.INTERNAL_SERVER_ERROR).build();
        }
    }

    String passwordHash;
    String password = randomText();
    try {
        passwordHash = hashPassword(password);
    } catch (NoSuchAlgorithmException e) {
        LOG.log(Level.SEVERE, e.getMessage(), e);
        return Response.status(Status.INTERNAL_SERVER_ERROR).build();
    }

    em.getTransaction().begin();
    try {
        Pilot pilot = new Pilot();
        pilot.setLogin(login);
        pilot.setCreated(new Date());
        pilot.setPasswordHash(passwordHash);
        pilot.setEmail(email);
        pilot.setFaction(faction);
        pilot.setVessel(vessel);
        pilot.setVerificationCode(randomText());
        em.persist(pilot);
        em.getTransaction().commit();
        try {
            // send e-mail to registered user containing the new password

            Properties props = new Properties();
            Session session = Session.getDefaultInstance(props, null);

            String msgBody = "Welcome to opengate!\n\nSomeone, propably you, registered the user "
                    + pilot.getLogin()
                    + " with your e-mail adress. The following credentials can be used for your account:\n"
                    + "  login : " + pilot.getLogin() + "\n" + "  password : " + password + "\n\n"
                    + "To log into the game you need to verify your account using the following link: http://opengate-meta.appspot.com/services/pilot/verify/"
                    + pilot.getLogin() + "?verification=" + pilot.getVerificationCode();

            try {
                Message msg = new MimeMessage(session);
                msg.setFrom(new InternetAddress("egore911@gmail.com", "Opengate administration"));
                msg.addRecipient(Message.RecipientType.TO, recipient);
                msg.setSubject("Your Example.com account has been activated");
                msg.setText(msgBody);
                Transport.send(msg);

            } catch (AddressException e) {
                LOG.log(Level.SEVERE, e.getMessage(), e);
                return Response.status(Status.INTERNAL_SERVER_ERROR).build();
            } catch (MessagingException e) {
                LOG.log(Level.SEVERE, e.getMessage(), e);
                return Response.status(Status.INTERNAL_SERVER_ERROR).build();
            } catch (UnsupportedEncodingException e) {
                LOG.log(Level.SEVERE, e.getMessage(), e);
                return Response.status(Status.INTERNAL_SERVER_ERROR).build();
            }

            StatusHelper.ok(jsonObject);
            jsonObject.put("id", pilot.getKey().getId());
            jsonObject.put("vessel_id", pilot.getVessel().getKey().getId());
            // TODO properly wrap the vessel and its equipment/cargo
            return Response.ok(jsonObject.toString()).build();
        } catch (JSONException e) {
            LOG.log(Level.SEVERE, e.getMessage(), e);
            return Response.status(Status.INTERNAL_SERVER_ERROR).build();
        }
    } catch (NoResultException e) {
        return Response.status(Status.FORBIDDEN).build();
    } finally {
        if (em.getTransaction().isActive()) {
            em.getTransaction().rollback();
        }
    }
}

From source file:net.sourceforge.fenixedu.presentationTier.Action.ExceptionHandlingAction.java

private void sendEmail(String from, String subject, String body) {
    Properties props = new Properties();
    props.put("mail.smtp.host",
            Objects.firstNonNull(FenixConfigurationManager.getConfiguration().getMailSmtpHost(), "localhost"));
    Session session = Session.getDefaultInstance(props, null);
    MimeMessage message = new MimeMessage(session);
    try {/*w  w  w.j  a v a 2s.  c o m*/
        message.setFrom(new InternetAddress(from));
        message.addRecipient(Message.RecipientType.TO,
                new InternetAddress(CoreConfiguration.getConfiguration().defaultSupportEmailAddress()));
        message.setSubject(subject);
        message.setText(body);
        Transport.send(message);
    } catch (Exception e) {
        logger.error("Could not send support email! Original message was: " + body, e);
    }
}

From source file:de.saly.elasticsearch.imap.AbstractIMAPRiverUnitTest.java

protected void putMailInMailbox2(final int messages) throws MessagingException {

    for (int i = 0; i < messages; i++) {
        final MimeMessage message = new MimeMessage((Session) null);
        message.setFrom(new InternetAddress(EMAIL_TO));
        message.addRecipient(Message.RecipientType.TO, new InternetAddress(EMAIL_USER_ADDRESS2));
        message.setSubject(EMAIL_SUBJECT + "::" + i);
        message.setText(EMAIL_TEXT + "::" + SID++);
        message.setSentDate(new Date());
        MockMailbox.get(EMAIL_USER_ADDRESS2).getInbox().add(message);
    }//from   ww w .  j  a  v  a  2 s .  c  o m

    logger.info("Putted " + messages + " into mailbox " + EMAIL_USER_ADDRESS2);
}

From source file:edu.umich.ctools.sectionsUtilityTool.Friend.java

public static void notifyCurrentUser(String instructorName, String instructorEmail, String inviteEmail) {

    M_log.debug("Friend notifyCurrentUser() called");
    String to = instructorEmail;/*from  w  w w. j  ava 2 s.c om*/
    String from = contactEmail;
    String host = mailHost;

    M_log.info("Setting up mailProps");

    Properties properties = System.getProperties();
    properties.put(MAIL_SMTP_AUTH, "false");
    properties.put(MAIL_SMTP_STARTTLS, "true"); //Put to false, if no https is needed
    properties.put(MAIL_SMTP_HOST, host);
    properties.put(MAIL_DEBUG, "true");

    M_log.debug("Initiating Session for sendMail");
    Session session = Session.getInstance(properties);

    try {

        HashMap<String, String> map = new HashMap<String, String>();

        map.put("<instructor>", instructorName);
        map.put("<friend>", inviteEmail);

        emailMessage = Friend.readFile(requesterEmailFile, StandardCharsets.UTF_8);
        emailMessage = replacePlaceHolders(emailMessage, map);

        M_log.debug("Setting up message for sendMail");
        MimeMessage message = new MimeMessage(session);
        message.setFrom(new InternetAddress(from));
        message.addRecipient(Message.RecipientType.TO, new InternetAddress(to));
        message.setSubject(subjectLine);

        message.setText(emailMessage);

        M_log.info("Sending message");
        Transport.send(message);

        M_log.info("Message sent to " + instructorName);

    } catch (Exception e) {
        M_log.error("notifyCurrentUser exception: " + e.getMessage());
    }
}

From source file:com.netflix.genie.server.jobmanager.impl.JobMonitor.java

/**
 * Check the properties file to figure out if an email
 * needs to be sent at the end of the job. If yes, get
 * mail properties and try and send email about Job Status.
 * @return 0 for success, -1 for failure
 *//*from w  ww  .j  a v a  2  s  . c o m*/
private boolean sendEmail(String emailTo) {
    logger.debug("called");

    if (!config.getBoolean("netflix.genie.server.mail.enable", false)) {
        logger.warn("Email is disabled but user has specified an email address.");
        return false;
    }

    // Sender's email ID
    String fromEmail = config.getString("netflix.genie.server.mail.smpt.from", "no-reply-genie@geniehost.com");
    logger.info("From email address to use to send email: " + fromEmail);

    // Set the smtp server hostname. Use localhost as default
    String smtpHost = config.getString("netflix.genie.server.mail.smtp.host", "localhost");
    logger.debug("Email smtp server: " + smtpHost);

    // Get system properties
    Properties properties = new Properties();

    // Setup mail server
    properties.setProperty("mail.smtp.host", smtpHost);

    // check whether authentication should be turned on
    Authenticator auth = null;

    if (config.getBoolean("netflix.genie.server.mail.smtp.auth", false)) {
        logger.debug("Email Authentication Enabled");

        properties.put("mail.smtp.starttls.enable", "true");
        properties.put("mail.smtp.auth", "true");

        String userName = config.getString("netflix.genie.server.mail.smtp.user");
        String password = config.getString("netflix.genie.server.mail.smtp.password");

        if ((userName == null) || (password == null)) {
            logger.error("Authentication is enabled and username/password for smtp server is null");
            return false;
        }
        logger.debug(
                "Constructing authenticator object with username" + userName + " and password " + password);
        auth = new SMTPAuthenticator(userName, password);
    } else {
        logger.debug("Email authentication not enabled.");
    }

    // Get the default Session object.
    Session session = Session.getInstance(properties, auth);

    try {
        // Create a default MimeMessage object.
        MimeMessage message = new MimeMessage(session);

        // Set From: header field of the header.
        message.setFrom(new InternetAddress(fromEmail));

        // Set To: header field of the header.
        message.addRecipient(Message.RecipientType.TO, new InternetAddress(emailTo));

        // Set Subject: header field
        message.setSubject("Genie Job " + ji.getJobName() + " completed with Status: " + ji.getStatus());

        // Now set the actual message
        String body = "Your Genie Job is complete\n\n" + "Job ID: " + ji.getJobID() + "\n" + "Job Name: "
                + ji.getJobName() + "\n" + "Status: " + ji.getStatus() + "\n" + "Status Message: "
                + ji.getStatusMsg() + "\n" + "Output Base URL: " + ji.getOutputURI() + "\n";

        message.setText(body);

        // Send message
        Transport.send(message);
        logger.info("Sent email message successfully....");
        return true;
    } catch (MessagingException mex) {
        logger.error("Got exception while sending email", mex);
        return false;
    }
}

From source file:com.eviware.soapui.impl.wsdl.submit.filters.HttpRequestFilter.java

@SuppressWarnings("deprecation")
@Override/*from  www  .j a v  a2 s  .  co  m*/
public void filterHttpRequest(SubmitContext context, HttpRequestInterface<?> request) {
    HttpRequestBase httpMethod = (HttpRequestBase) context.getProperty(BaseHttpRequestTransport.HTTP_METHOD);

    String path = PropertyExpander.expandProperties(context, request.getPath());
    StringBuffer query = new StringBuffer();
    String encoding = System.getProperty("soapui.request.encoding", StringUtils.unquote(request.getEncoding()));

    StringToStringMap responseProperties = (StringToStringMap) context
            .getProperty(BaseHttpRequestTransport.RESPONSE_PROPERTIES);

    MimeMultipart formMp = "multipart/form-data".equals(request.getMediaType())
            && httpMethod instanceof HttpEntityEnclosingRequestBase ? new MimeMultipart() : null;

    RestParamsPropertyHolder params = request.getParams();

    for (int c = 0; c < params.getPropertyCount(); c++) {
        RestParamProperty param = params.getPropertyAt(c);

        String value = PropertyExpander.expandProperties(context, param.getValue());
        responseProperties.put(param.getName(), value);

        List<String> valueParts = sendEmptyParameters(request)
                || (!StringUtils.hasContent(value) && param.getRequired())
                        ? RestUtils.splitMultipleParametersEmptyIncluded(value,
                                request.getMultiValueDelimiter())
                        : RestUtils.splitMultipleParameters(value, request.getMultiValueDelimiter());

        // skip HEADER and TEMPLATE parameter encoding (TEMPLATE is encoded by
        // the URI handling further down)
        if (value != null && param.getStyle() != ParameterStyle.HEADER
                && param.getStyle() != ParameterStyle.TEMPLATE && !param.isDisableUrlEncoding()) {
            try {
                if (StringUtils.hasContent(encoding)) {
                    value = URLEncoder.encode(value, encoding);
                    for (int i = 0; i < valueParts.size(); i++)
                        valueParts.set(i, URLEncoder.encode(valueParts.get(i), encoding));
                } else {
                    value = URLEncoder.encode(value);
                    for (int i = 0; i < valueParts.size(); i++)
                        valueParts.set(i, URLEncoder.encode(valueParts.get(i)));
                }
            } catch (UnsupportedEncodingException e1) {
                SoapUI.logError(e1);
                value = URLEncoder.encode(value);
                for (int i = 0; i < valueParts.size(); i++)
                    valueParts.set(i, URLEncoder.encode(valueParts.get(i)));
            }
            // URLEncoder replaces space with "+", but we want "%20".
            value = value.replaceAll("\\+", "%20");
            for (int i = 0; i < valueParts.size(); i++)
                valueParts.set(i, valueParts.get(i).replaceAll("\\+", "%20"));
        }

        if (param.getStyle() == ParameterStyle.QUERY && !sendEmptyParameters(request)) {
            if (!StringUtils.hasContent(value) && !param.getRequired())
                continue;
        }

        switch (param.getStyle()) {
        case HEADER:
            for (String valuePart : valueParts)
                httpMethod.addHeader(param.getName(), valuePart);
            break;
        case QUERY:
            if (formMp == null || !request.isPostQueryString()) {
                for (String valuePart : valueParts) {
                    if (query.length() > 0)
                        query.append('&');

                    query.append(URLEncoder.encode(param.getName()));
                    query.append('=');
                    if (StringUtils.hasContent(valuePart))
                        query.append(valuePart);
                }
            } else {
                try {
                    addFormMultipart(request, formMp, param.getName(), responseProperties.get(param.getName()));
                } catch (MessagingException e) {
                    SoapUI.logError(e);
                }
            }

            break;
        case TEMPLATE:
            try {
                value = getEncodedValue(value, encoding, param.isDisableUrlEncoding(),
                        request.getSettings().getBoolean(HttpSettings.ENCODED_URLS));
                path = path.replaceAll("\\{" + param.getName() + "\\}", value == null ? "" : value);
            } catch (UnsupportedEncodingException e) {
                SoapUI.logError(e);
            }
            break;
        case MATRIX:
            try {
                value = getEncodedValue(value, encoding, param.isDisableUrlEncoding(),
                        request.getSettings().getBoolean(HttpSettings.ENCODED_URLS));
            } catch (UnsupportedEncodingException e) {
                SoapUI.logError(e);
            }

            if (param.getType().equals(XmlBoolean.type.getName())) {
                if (value.toUpperCase().equals("TRUE") || value.equals("1")) {
                    path += ";" + param.getName();
                }
            } else {
                path += ";" + param.getName();
                if (StringUtils.hasContent(value)) {
                    path += "=" + value;
                }
            }
        case PLAIN:
            break;
        }
    }

    if (request.getSettings().getBoolean(HttpSettings.FORWARD_SLASHES))
        path = PathUtils.fixForwardSlashesInPath(path);

    if (PathUtils.isHttpPath(path)) {
        try {
            // URI(String) automatically URLencodes the input, so we need to
            // decode it first...
            URI uri = new URI(path, request.getSettings().getBoolean(HttpSettings.ENCODED_URLS));
            context.setProperty(BaseHttpRequestTransport.REQUEST_URI, uri);
            java.net.URI oldUri = httpMethod.getURI();
            httpMethod.setURI(new java.net.URI(oldUri.getScheme(), oldUri.getUserInfo(), oldUri.getHost(),
                    oldUri.getPort(), (uri.getPath()) == null ? "/" : uri.getPath(), oldUri.getQuery(),
                    oldUri.getFragment()));
        } catch (Exception e) {
            SoapUI.logError(e);
        }
    } else if (StringUtils.hasContent(path)) {
        try {
            java.net.URI oldUri = httpMethod.getURI();
            String pathToSet = StringUtils.hasContent(oldUri.getRawPath()) && !"/".equals(oldUri.getRawPath())
                    ? oldUri.getRawPath() + path
                    : path;
            java.net.URI newUri = URIUtils.createURI(oldUri.getScheme(), oldUri.getHost(), oldUri.getPort(),
                    pathToSet, oldUri.getQuery(), oldUri.getFragment());
            httpMethod.setURI(newUri);
            context.setProperty(BaseHttpRequestTransport.REQUEST_URI,
                    new URI(newUri.toString(), request.getSettings().getBoolean(HttpSettings.ENCODED_URLS)));
        } catch (Exception e) {
            SoapUI.logError(e);
        }
    }

    if (query.length() > 0 && !request.isPostQueryString()) {
        try {
            java.net.URI oldUri = httpMethod.getURI();
            httpMethod.setURI(URIUtils.createURI(oldUri.getScheme(), oldUri.getHost(), oldUri.getPort(),
                    oldUri.getRawPath(), query.toString(), oldUri.getFragment()));
        } catch (Exception e) {
            SoapUI.logError(e);
        }
    }

    if (request instanceof RestRequest) {
        String acceptEncoding = ((RestRequest) request).getAccept();
        if (StringUtils.hasContent(acceptEncoding)) {
            httpMethod.setHeader("Accept", acceptEncoding);
        }
    }

    if (formMp != null) {
        // create request message
        try {
            if (request.hasRequestBody() && httpMethod instanceof HttpEntityEnclosingRequest) {
                String requestContent = PropertyExpander.expandProperties(context, request.getRequestContent(),
                        request.isEntitizeProperties());
                if (StringUtils.hasContent(requestContent)) {
                    initRootPart(request, requestContent, formMp);
                }
            }

            for (Attachment attachment : request.getAttachments()) {
                MimeBodyPart part = new PreencodedMimeBodyPart("binary");

                if (attachment instanceof FileAttachment<?>) {
                    String name = attachment.getName();
                    if (StringUtils.hasContent(attachment.getContentID())
                            && !name.equals(attachment.getContentID()))
                        name = attachment.getContentID();

                    part.setDisposition(
                            "form-data; name=\"" + name + "\"; filename=\"" + attachment.getName() + "\"");
                } else
                    part.setDisposition("form-data; name=\"" + attachment.getName() + "\"");

                part.setDataHandler(new DataHandler(new AttachmentDataSource(attachment)));

                formMp.addBodyPart(part);
            }

            MimeMessage message = new MimeMessage(AttachmentUtils.JAVAMAIL_SESSION);
            message.setContent(formMp);
            message.saveChanges();
            RestRequestMimeMessageRequestEntity mimeMessageRequestEntity = new RestRequestMimeMessageRequestEntity(
                    message, request);
            ((HttpEntityEnclosingRequest) httpMethod).setEntity(mimeMessageRequestEntity);
            httpMethod.setHeader("Content-Type", mimeMessageRequestEntity.getContentType().getValue());
            httpMethod.setHeader("MIME-Version", "1.0");
        } catch (Throwable e) {
            SoapUI.logError(e);
        }
    } else if (request.hasRequestBody() && httpMethod instanceof HttpEntityEnclosingRequest) {
        if (StringUtils.hasContent(request.getMediaType()))
            httpMethod.setHeader("Content-Type", getContentTypeHeader(request.getMediaType(), encoding));

        if (request.isPostQueryString()) {
            try {
                ((HttpEntityEnclosingRequest) httpMethod).setEntity(new StringEntity(query.toString()));
            } catch (UnsupportedEncodingException e) {
                SoapUI.logError(e);
            }
        } else {
            String requestContent = PropertyExpander.expandProperties(context, request.getRequestContent(),
                    request.isEntitizeProperties());
            List<Attachment> attachments = new ArrayList<Attachment>();

            for (Attachment attachment : request.getAttachments()) {
                if (attachment.getContentType().equals(request.getMediaType())) {
                    attachments.add(attachment);
                }
            }

            if (StringUtils.hasContent(requestContent) && attachments.isEmpty()) {
                try {
                    byte[] content = encoding == null ? requestContent.getBytes()
                            : requestContent.getBytes(encoding);
                    ((HttpEntityEnclosingRequest) httpMethod).setEntity(new ByteArrayEntity(content));
                } catch (UnsupportedEncodingException e) {
                    ((HttpEntityEnclosingRequest) httpMethod)
                            .setEntity(new ByteArrayEntity(requestContent.getBytes()));
                }
            } else if (attachments.size() > 0) {
                try {
                    MimeMultipart mp = null;

                    if (StringUtils.hasContent(requestContent)) {
                        mp = new MimeMultipart();
                        initRootPart(request, requestContent, mp);
                    } else if (attachments.size() == 1) {
                        ((HttpEntityEnclosingRequest) httpMethod)
                                .setEntity(new InputStreamEntity(attachments.get(0).getInputStream(), -1));

                        httpMethod.setHeader("Content-Type",
                                getContentTypeHeader(request.getMediaType(), encoding));
                    }

                    if (((HttpEntityEnclosingRequest) httpMethod).getEntity() == null) {
                        if (mp == null)
                            mp = new MimeMultipart();

                        // init mimeparts
                        AttachmentUtils.addMimeParts(request, attachments, mp, new StringToStringMap());

                        // create request message
                        MimeMessage message = new MimeMessage(AttachmentUtils.JAVAMAIL_SESSION);
                        message.setContent(mp);
                        message.saveChanges();
                        RestRequestMimeMessageRequestEntity mimeMessageRequestEntity = new RestRequestMimeMessageRequestEntity(
                                message, request);
                        ((HttpEntityEnclosingRequest) httpMethod).setEntity(mimeMessageRequestEntity);
                        httpMethod.setHeader("Content-Type", getContentTypeHeader(
                                mimeMessageRequestEntity.getContentType().getValue(), encoding));
                        httpMethod.setHeader("MIME-Version", "1.0");
                    }
                } catch (Exception e) {
                    SoapUI.logError(e);
                }
            }
        }
    }
}

From source file:mitm.application.djigzo.james.matchers.HasValidPasswordTest.java

@Test
public void testZeroValidityInterval() throws MessagingException, EncryptorException {
    HasValidPassword matcher = new HasValidPassword();

    MockMatcherConfig matcherConfig = new MockMatcherConfig("test", "matchOnError=false", mailetContext);

    matcher.init(matcherConfig);/*w w w . j  a v a2s  .c o  m*/

    Mail mail = new MockMail();

    MimeMessage message = new MimeMessage(MailSession.getDefaultSession());

    message.setContent("test", "text/plain");
    message.setFrom(new InternetAddress("123456@example.com"));

    message.saveChanges();

    mail.setMessage(message);

    Collection<MailAddress> recipients = new LinkedList<MailAddress>();

    recipients.add(new MailAddress("test1@example.com"));

    mail.setRecipients(recipients);

    Collection<?> result = matcher.match(mail);

    assertEquals(0, result.size());
}

From source file:com.silverpeas.mailinglist.service.job.TestMessageChecker.java

@Test
public void testProcessEmailHtmlTextWithAttachment() throws MessagingException, IOException {
    MessageListener mockListener1 = mock(MessageListener.class);
    when(mockListener1.getComponentId()).thenReturn("componentId");
    when(mockListener1.checkSender("bart.simpson@silverpeas.com")).thenReturn(Boolean.TRUE);
    MessageListener mockListener2 = mock(MessageListener.class);
    messageChecker.addMessageListener(mockListener1);
    messageChecker.addMessageListener(mockListener2);
    Map<String, MessageListener> listenersByEmail = new HashMap<String, MessageListener>(2);
    listenersByEmail.put("thesimpsons@silverpeas.com", mockListener1);
    listenersByEmail.put("theflanders@silverpeas.com", mockListener2);
    MimeMessage mail = new MimeMessage(messageChecker.getMailSession());
    InternetAddress bart = new InternetAddress("bart.simpson@silverpeas.com");
    InternetAddress theSimpsons = new InternetAddress("thesimpsons@silverpeas.com");
    mail.addFrom(new InternetAddress[] { bart });
    mail.addRecipient(RecipientType.TO, theSimpsons);
    mail.setSubject("Html Email test with attachment");
    String html = loadHtml();//from  w w w  .jav  a 2  s.  c om
    MimeBodyPart attachment = new MimeBodyPart(TestMessageChecker.class.getResourceAsStream("lemonde.html"));
    attachment.setDisposition(Part.ATTACHMENT);
    attachment.setFileName("lemonde.html");
    MimeBodyPart body = new MimeBodyPart();
    body.setContent(html, "text/html; charset=\"UTF-8\"");
    Multipart multiPart = new MimeMultipart();
    multiPart.addBodyPart(body);
    multiPart.addBodyPart(attachment);
    mail.setContent(multiPart);
    Transport.send(mail);
    Map<MessageListener, MessageEvent> events = new HashMap<MessageListener, MessageEvent>();
    messageChecker.processEmail(mail, events, listenersByEmail);
    assertNotNull(events);
    assertEquals(1, events.size());
    assertNull(events.get(mockListener2));

    MessageEvent event = events.get(mockListener1);
    assertNotNull(event);
    assertNotNull(event.getMessages());
    assertEquals(1, event.getMessages().size());
    Message message = event.getMessages().get(0);
    assertEquals("bart.simpson@silverpeas.com", message.getSender());
    assertEquals("Html Email test with attachment", message.getTitle());
    assertEquals(html, message.getBody());
    assertEquals(htmlEmailSummary, message.getSummary());
    assertEquals(ATT_SIZE, message.getAttachmentsSize());
    assertEquals(1, message.getAttachments().size());
    String path = MessageFormat.format(attachmentPath,
            messageChecker.getMailProcessor().replaceSpecialChars(message.getMessageId()));
    Attachment attached = message.getAttachments().iterator().next();
    assertEquals(path, attached.getPath());
    assertEquals("lemonde.html", attached.getFileName());
    assertEquals("componentId", message.getComponentId());
    assertEquals("text/html", message.getContentType());
    verify(mockListener1, atLeastOnce()).checkSender("bart.simpson@silverpeas.com");
}