Example usage for javax.mail.internet MimeMessage getSubject

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

Introduction

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

Prototype

@Override
public String getSubject() throws MessagingException 

Source Link

Document

Returns the value of the "Subject" header field.

Usage

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

@Test
public void testEncodedSubject() throws Exception {
    MockMailetConfig mailetConfig = new MockMailetConfig("test");

    Mailet mailet = new FilterSubject();

    mailetConfig.setInitParameter("filter", "/(^(.*)$)/ $1 !@#\\$%^&*()");

    mailet.init(mailetConfig);//from  www .j  a v a2  s . com

    MockMail mail = new MockMail();

    MimeMessage message = MailUtils.loadMessage(new File(testBase, "mail/encoded-subject.eml"));

    assertEquals("test encoded subject  ", message.getSubject());

    mail.setMessage(message);

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

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

    mail.setRecipients(recipients);

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

    mailet.service(mail);

    message = mail.getMessage();

    assertEquals("test encoded subject   !@#$%^&*()", message.getSubject());

    /*
     * Check if subject is encoded
     */
    assertEquals(
            "=?UTF-8?Q?test_encoded_subjec?=\r\n =?UTF-8?Q?t_=C3=A4=C3=B6=C3=BC_=C3=84=C3=96=C3=9C_!@#$%^&*()?=",
            StringUtils.join(message.getHeader("subject"), ','));
}

From source file:org.parancoe.test.LoggingMailSender.java

@Override
protected void doSend(MimeMessage[] mimeMessages, Object[] originalMessages) {
    if (mimeMessages != null) {
        for (MimeMessage mimeMessage : mimeMessages) {
            try {
                logger.info("from: {}", (Object[]) mimeMessage.getFrom());
                logger.info("to: {}", (Object[]) mimeMessage.getRecipients(Message.RecipientType.TO));
                logger.info("cc: {}", (Object[]) mimeMessage.getRecipients(Message.RecipientType.CC));
                logger.info("bcc: {}", (Object[]) mimeMessage.getRecipients(Message.RecipientType.BCC));
                logger.info("subject: {}", mimeMessage.getSubject());
                logger.info("content: {}", mimeMessage.getContent().toString());
                logger.info("content type: {}", mimeMessage.getContentType());
            } catch (Exception ex) {
                logger.error("Can't get message content", ex);
            }//  w w w .j a v a  2  s . c o m
        }
    }
}

From source file:com.twinsoft.convertigo.engine.admin.services.projects.Deploy.java

@Override
protected void doUpload(HttpServletRequest request, Document document, FileItem item) throws Exception {
    if (!item.getName().endsWith(".car")) {
        ServiceUtils/*from   w ww . j  a  v  a  2 s  .c  o m*/
                .addMessage(document, document.getDocumentElement(),
                        "The deployment of the project " + item.getName()
                                + " has failed. The archive file is not valid (.car required).",
                        "error", false);
    }

    super.doUpload(request, document, item);

    // Depending on client browsers, according to the documentation,
    // item.getName() can either return a full path file name, or
    // simply a file name.
    String projectArchive = item.getName();

    // Bugfix #1425
    int i = projectArchive.lastIndexOf('/');
    if (i == -1) {
        i = projectArchive.lastIndexOf('\\');
        if (i != -1) {
            projectArchive = projectArchive.substring(i + 1);
        }
    } else {
        projectArchive = projectArchive.substring(i + 1);
    }

    String projectName = projectArchive.substring(0, projectArchive.indexOf(".car"));

    Engine.theApp.databaseObjectsManager.deployProject(getRepository() + projectArchive, true, bAssembleXsl);

    if (Boolean.parseBoolean(
            EnginePropertiesManager.getProperty(PropertyName.NOTIFICATIONS_NOTIFY_PROJECT_DEPLOYMENT))) {

        final String fUser = (String) request.getSession().getAttribute(SessionKey.ADMIN_USER.toString());
        final String fProjectName = projectName;

        new Thread(new Runnable() {
            public void run() {
                try {
                    Properties props = new Properties();

                    props.put("mail.smtp.host",
                            EnginePropertiesManager.getProperty(PropertyName.NOTIFICATIONS_SMTP_HOST));
                    props.put("mail.smtp.socketFactory.port",
                            EnginePropertiesManager.getProperty(PropertyName.NOTIFICATIONS_SMTP_PORT));
                    props.put("mail.smtp.auth", "true");
                    props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
                    props.put("mail.smtp.socketFactory.fallback", "false");

                    // Initializing
                    Session mailSession = Session.getInstance(props, new Authenticator() {
                        @Override
                        public PasswordAuthentication getPasswordAuthentication() {
                            return new PasswordAuthentication(
                                    EnginePropertiesManager.getProperty(PropertyName.NOTIFICATIONS_SMTP_USER),
                                    EnginePropertiesManager
                                            .getProperty(PropertyName.NOTIFICATIONS_SMTP_PASSWORD));
                        }
                    });
                    MimeMessage message = new MimeMessage(mailSession);

                    message.addRecipient(Message.RecipientType.TO, new InternetAddress(
                            EnginePropertiesManager.getProperty(PropertyName.NOTIFICATIONS_TARGET_EMAIL)));
                    message.setSubject("[trial] deployment of " + fProjectName + " by " + fUser);
                    message.setText(message.getSubject() + "\n" + "http://trial.convertigo.net/cems/projects/"
                            + fProjectName + "\n" + "https://trial.convertigo.net/cems/projects/"
                            + fProjectName);
                    Transport.send(message);
                } catch (MessagingException e1) {
                }
            }
        }).start();
    }

    String message = "The project '" + projectName + "' has been successfully deployed.";
    Engine.logAdmin.info(message);
    ServiceUtils.addMessage(document, document.getDocumentElement(), message, "message", false);
}

From source file:eu.openanalytics.rsb.component.EmailDepositHandler.java

@SuppressWarnings("unchecked")
public void handleJob(final Message<MimeMessage> message) throws MessagingException, IOException {
    final DepositEmailConfiguration depositEmailConfiguration = message.getHeaders()
            .get(EMAIL_CONFIG_HEADER_NAME, DepositEmailConfiguration.class);
    final String applicationName = depositEmailConfiguration.getApplicationName();
    final MimeMessage mimeMessage = message.getPayload();

    final Address[] replyTo = mimeMessage.getReplyTo();
    Validate.notEmpty(replyTo, "no reply address found for job emailed with headers:"
            + Collections.list(mimeMessage.getAllHeaders()));

    final Map<String, Serializable> meta = new HashMap<String, Serializable>();
    meta.put(EMAIL_SUBJECT_META_NAME, mimeMessage.getSubject());
    meta.put(EMAIL_ADDRESSEE_META_NAME, getPrimaryAddressee(mimeMessage));
    meta.put(EMAIL_REPLY_TO_META_NAME, replyTo[0].toString());
    meta.put(EMAIL_REPLY_CC_META_NAME, getCCAddressees(mimeMessage));
    meta.put(EMAIL_BODY_META_NAME, getResponseBody(depositEmailConfiguration));

    final MultiFilesJob job = new MultiFilesJob(Source.EMAIL, applicationName,
            ApplicationPermissionEvaluator.NO_AUTHENTICATED_USERNAME, UUID.randomUUID(),
            (GregorianCalendar) GregorianCalendar.getInstance(), meta);

    try {//  w  w  w .j av  a 2s .c  om
        addEmailAttachmentsToJob(depositEmailConfiguration, mimeMessage, job);
        getMessageDispatcher().dispatch(job);
    } catch (final Exception e) {
        final MultiFilesResult errorResult = job.buildErrorResult(e, getMessages());
        handleResult(errorResult);
    }
}

From source file:com.meltmedia.cadmium.email.TestingMessageTransformer.java

public MimeBodyPart newSentToBodyPart(MimeMessage message) throws MessagingException {
    // get information about the original message.
    Address[] originalFromRecipient = message.getFrom();
    Address[] originalToRecipient = message.getRecipients(Message.RecipientType.TO);
    Address[] originalCcRecipient = message.getRecipients(Message.RecipientType.CC);
    Address[] originalBccRecipient = message.getRecipients(Message.RecipientType.BCC);
    String originalSubject = message.getSubject();

    // create the html for the string buffer.
    StringBuffer html = new StringBuffer();
    html.append("<html><body><table style=\"width: 100%;\"><tr><td>header</td><td>value</td></tr>");
    html.append("<tr><td>Subject:</td><td>").append(escape(originalSubject)).append("</td></tr>");

    // iterate over the addresses.
    if (originalFromRecipient != null) {
        for (int i = 0; i < originalFromRecipient.length; i++) {
            html.append("<tr><td>FROM:</td><td>").append(escape(originalFromRecipient[i])).append("</td></tr>");
        }/* ww  w  .  j  av  a 2  s  .  c  o m*/
    }
    if (originalToRecipient != null) {
        for (int i = 0; i < originalToRecipient.length; i++) {
            html.append("<tr><td>TO:</td><td>").append(escape(originalToRecipient[i])).append("</td></tr>");
        }
    }
    if (originalCcRecipient != null) {
        for (int i = 0; i < originalCcRecipient.length; i++) {
            html.append("<tr><td>CC:</td><td>").append(escape(originalCcRecipient[i])).append("</td></tr>");
        }
    }
    if (originalBccRecipient != null) {
        for (int i = 0; i < originalBccRecipient.length; i++) {
            html.append("<tr><td>BCC:</td><td>").append(escape(originalBccRecipient[i])).append("</td></tr>");
        }
    }
    html.append("</table></body></html>");

    MimeBodyPart sentToBodyPart = new MimeBodyPart();
    sentToBodyPart.setContent(html.toString(), "text/html");
    sentToBodyPart.setHeader("Content-ID", "original-addresses");
    sentToBodyPart.setDisposition("inline");

    return sentToBodyPart;
}

From source file:ca.airspeed.demo.testingemail.EmailServiceTest.java

/**
 * When we send out an email with just a text body, et expect to get a
 * Multipart email having only a plain text body.
 *//*  w  ww. jav a  2  s .  co  m*/
@Test
public void testSimpleEmail() throws Exception {
    // Given:
    EmailService service = makeALocalMailer();

    InternetAddress expectedTo = new InternetAddress("Indiana.Jones@domain.com", "Indiana Jones");
    String expectedSubject = "This is a Test Email";
    String expectedTextBody = "This is a simple test.";

    // When:
    service.sendSimpleEmail(expectedTo, expectedSubject, expectedTextBody);

    // Then:
    List<WiserMessage> messages = wiser.getMessages();
    assertEquals("Number of messages sent;", 1, messages.size());

    WiserMessage message = messages.get(0);
    assertNotNull("No message was actually sent.", message);
    MimeMessage mimeMessage = message.getMimeMessage();
    Address[] toRecipients = mimeMessage.getRecipients(RecipientType.TO);
    assertEquals("Number of To: Recipient;", 1, toRecipients.length);
    Address toRecipient = toRecipients[0];
    assertEquals("To: Recipient;", expectedTo, toRecipient);

    InternetAddress expectedFrom = new InternetAddress("admin@domain.com", "Domain Admin");
    Address[] fromArr = mimeMessage.getFrom();
    assertEquals("From: email addresses;", 1, fromArr.length);
    assertEquals("Email From: address,", expectedFrom, fromArr[0]);

    assertEquals("Subject;", expectedSubject, mimeMessage.getSubject());

    assertNotNull("The date of the email cannot be null.", mimeMessage.getSentDate());

    MimeMultipart body = ((MimeMultipart) mimeMessage.getContent());
    assertEquals("Number of MIME Parts in the body;", 1, body.getCount());
    MimeMultipart textPart = ((MimeMultipart) body.getBodyPart(0).getContent());
    assertEquals("Number of MIME parts in the text body;", 1, textPart.getCount());
    MimeBodyPart plainTextPart = ((MimeBodyPart) textPart.getBodyPart(0));
    assertTrue("Expected the plain text content to be text/plain.", plainTextPart.isMimeType("text/plain"));
    assertEquals("Text Body;", expectedTextBody, plainTextPart.getContent());
}

From source file:com.angstoverseer.service.mail.MailServiceImpl.java

@Override
public void handleIncomingEmail(InputStream inputStream) {
    Properties props = new Properties();
    Session session = Session.getDefaultInstance(props, null);

    try {//from  w ww  .ja  va  2s.c om
        MimeMessage mimeMessage = new MimeMessage(session, inputStream);

        Object messageContent = mimeMessage.getContent();
        String message;
        if (messageContent instanceof Multipart) {
            Multipart mp = (Multipart) messageContent;
            BodyPart bodyPart = mp.getBodyPart(0);
            InputStream is = bodyPart.getInputStream();
            message = convertStreamToString(is);
        } else {
            message = (String) messageContent;
        }

        Address sender = mimeMessage.getFrom()[0];
        final String commandOutput = commandService.process(message, extractEmail(sender.toString()));

        sendResponseMail(sender, commandOutput, mimeMessage.getSubject());
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}

From source file:com.haulmont.cuba.core.app.EmailerTest.java

@Test
public void testSimpleParamList() throws Exception {
    testMailSender.clearBuffer();//w w  w.  j  a v a 2 s  . co m

    emailer.sendEmail("myemail@example.com", "Test Email", "Test Body 2");

    assertEquals(1, testMailSender.getBufferSize());
    MimeMessage msg = testMailSender.fetchSentEmail();

    assertEquals(1, msg.getAllRecipients().length);
    assertEquals("myemail@example.com", msg.getAllRecipients()[0].toString());

    assertEquals("Test Email", msg.getSubject());
    assertEquals("Test Body 2", getBody(msg));
    assertTrue(getBodyContentType(msg).startsWith("text/plain;"));
}

From source file:com.haulmont.cuba.core.app.EmailerTest.java

private void doTestSynchronous(boolean useFs) throws Exception {
    emailerConfig.setFileStorageUsed(useFs);
    testMailSender.clearBuffer();//from  w  w  w.j  ava  2s  . co  m

    EmailInfo myInfo = new EmailInfo("testemail@example.com", "Test Email", "Test Body");
    emailer.sendEmail(myInfo);

    assertEquals(1, testMailSender.getBufferSize());
    MimeMessage msg = testMailSender.fetchSentEmail();

    assertEquals(1, msg.getAllRecipients().length);
    assertEquals("testemail@example.com", msg.getAllRecipients()[0].toString());

    assertEquals("Test Email", msg.getSubject());
    assertEquals("Test Body", getBody(msg));
    assertTrue(getBodyContentType(msg).startsWith("text/plain;"));
}

From source file:com.haulmont.cuba.core.app.EmailerTest.java

private void doTestAsynchronous(boolean useFs) throws Exception {
    emailerConfig.setFileStorageUsed(useFs);
    testMailSender.clearBuffer();/*from  w  w  w.  ja  va2s .c  o  m*/

    String body = "Test Email Body";
    EmailInfo myInfo = new EmailInfo("recipient@example.com", "Test", body);
    List<SendingMessage> messages = emailer.sendEmailAsync(myInfo);
    assertEquals(1, messages.size());

    // not sent yet
    assertTrue(testMailSender.isEmpty());
    SendingMessage sendingMsg = reload(messages.get(0));
    assertEquals(SendingStatus.QUEUE, sendingMsg.getStatus());

    // run scheduler
    emailer.processQueuedEmails();

    // check
    assertEquals(1, testMailSender.getBufferSize());
    MimeMessage msg = testMailSender.fetchSentEmail();

    assertEquals(1, msg.getAllRecipients().length);
    assertEquals("recipient@example.com", msg.getAllRecipients()[0].toString());

    assertEquals("Test", msg.getSubject());
    assertEquals(body, getBody(msg));
    assertTrue(getBodyContentType(msg).startsWith("text/plain;"));

    sendingMsg = reload(messages.get(0));
    assertEquals(SendingStatus.SENT, sendingMsg.getStatus());
}