Example usage for javax.mail.internet MimeMessage setContent

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

Introduction

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

Prototype

@Override
public void setContent(Object o, String type) throws MessagingException 

Source Link

Document

A convenience method for setting this Message's content.

Usage

From source file:io.uengine.mail.MailAsyncService.java

@Async
public void download(String type, String version, String token, String subject, String fromUser,
        String fromName, final String toUser, final String toName, InternetAddress[] toCC) {
    Session session = setMailProperties(toUser);

    Map model = new HashMap();
    model.put("link",
            MessageFormatter.arrayFormat("http://www.uengine.io/download/get?type={}&version={}&token={}",
                    new Object[] { type, version, token }).getMessage());
    model.put("name", toName);

    String body = VelocityEngineUtils.mergeTemplateIntoString(velocityEngine, "mail/download.vm", "UTF-8",
            model);//from w  w  w . java 2  s.com

    try {
        InternetAddress from = new InternetAddress(fromUser, fromName);
        MimeMessage message = new MimeMessage(session);
        message.setFrom(from);
        message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(toUser));
        message.setSubject(subject);
        message.setContent(body, "text/html; charset=utf-8");
        if (toCC != null && toCC.length > 0)
            message.setRecipients(Message.RecipientType.CC, toCC);

        Transport.send(message);

        logger.info("{} ? ?? .", toUser);
    } catch (Exception e) {
        throw new ServiceException("??   .", e);
    }
}

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

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

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

    matcher.init(matcherConfig);//from  w  w w. java2s  . 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("TEST2@EXAMPLE.COM"));

    mail.setRecipients(recipients);

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

    assertEquals(1, result.size());
    assertTrue(result.contains(new MailAddress("TEST2@EXAMPLE.COM")));

    DjigzoMailAttributes attributes = new DjigzoMailAttributesImpl(mail);

    Passwords passwords = attributes.getPasswords();

    assertNotNull(passwords);
    assertNotNull(passwords.get("test2@example.com"));
    assertEquals("test2", passwords.get("test2@example.com").getPassword());
    assertEquals("ID2", passwords.get("test2@example.com").getPasswordID());
}

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

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

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

    matcher.init(matcherConfig);/*from   www.ja  v  a 2  s  . c  om*/

    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("test2@example.com"));

    mail.setRecipients(recipients);

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

    assertEquals(1, result.size());
    assertTrue(result.contains(new MailAddress("test2@example.com")));

    DjigzoMailAttributes attributes = new DjigzoMailAttributesImpl(mail);

    Passwords passwords = attributes.getPasswords();

    assertNotNull(passwords);
    assertNotNull(passwords.get("test2@example.com"));
    assertEquals("test2", passwords.get("test2@example.com").getPassword());
    assertEquals("ID2", passwords.get("test2@example.com").getPasswordID());
}

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

@Test
public void testMail() {
    try {/*from w  w  w  . j a v  a  2 s .c  o m*/
        mailServer = SimpleSmtpServer.start(smtpPort);
        Properties properties = new Properties();
        properties.setProperty("mail.smtp.host", "localhost"); //$NON-NLS-1$ //$NON-NLS-2$
        properties.setProperty("mail.smtp.port", String.valueOf(smtpPort)); //$NON-NLS-1$
        Session mailSession = Session.getDefaultInstance(properties);
        MimeMessage m = new MimeMessage(mailSession);
        Address from = new InternetAddress("me@gmail.com"); //$NON-NLS-1$
        Address[] to = new InternetAddress[1];
        to[0] = new InternetAddress("dev@mailinator.com"); //$NON-NLS-1$
        m.setFrom(from);
        m.setRecipients(Message.RecipientType.TO, to);
        m.setSubject("test"); //$NON-NLS-1$
        m.setContent("test", "text/plain"); //$NON-NLS-1$ //$NON-NLS-2$
        Transport.send(m);

        Assert.assertTrue(mailServer.getReceivedEmailSize() > 0);
        @SuppressWarnings("rawtypes")
        Iterator iter = mailServer.getReceivedEmail();
        while (iter.hasNext()) {
            SmtpMessage email = (SmtpMessage) iter.next();
            System.out.println(email.getBody());
            Assert.assertEquals("test", email.getBody()); //$NON-NLS-1$
        }

    } catch (AddressException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (MessagingException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } finally {
        mailServer.stop();
    }

}

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

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

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

    matcher.init(matcherConfig);/*from w w w . j  av a2  s  .  c om*/

    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("test2@example.com"));
    recipients.add(new MailAddress("test5@example.com"));

    mail.setRecipients(recipients);

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

    assertEquals(2, result.size());
    assertTrue(result.contains(new MailAddress("test2@example.com")));
    assertTrue(result.contains(new MailAddress("test5@example.com")));

    DjigzoMailAttributes attributes = new DjigzoMailAttributesImpl(mail);

    Passwords passwords = attributes.getPasswords();

    assertNotNull(passwords);
    assertNotNull(passwords.get("test2@example.com"));
    assertEquals("test2", passwords.get("test2@example.com").getPassword());
    assertEquals("ID2", passwords.get("test2@example.com").getPasswordID());
    assertNotNull(passwords.get("test5@example.com"));
    assertEquals("test5", passwords.get("test5@example.com").getPassword());
    assertEquals("ID5", passwords.get("test5@example.com").getPasswordID());
}

From source file:org.wso2.carbon.apimgt.core.impl.NewApiVersionMailNotifier.java

@Override
public void sendNotifications(NotificationDTO notificationDTO) throws APIManagementException {

    Properties props = notificationDTO.getProperties();
    //get Notifier email List
    Set<String> emailList = getEmailNotifierList(notificationDTO);

    if (emailList.isEmpty()) {
        log.debug("Email Notifier Set is Empty");
        return;//from  w w w.j a  v  a2  s.  c om
    }
    for (String mail : emailList) {
        try {
            Authenticator auth = new SMTPAuthenticator();
            Session mailSession = Session.getDefaultInstance(props, auth);
            MimeMessage message = new MimeMessage(mailSession);
            notificationDTO.setTitle((String) notificationDTO.getProperty(NotifierConstants.TITLE_KEY));
            notificationDTO.setMessage((String) notificationDTO.getProperty(NotifierConstants.TEMPLATE_KEY));
            notificationDTO = loadMailTemplate(notificationDTO);
            message.setSubject(notificationDTO.getTitle());
            message.setContent(notificationDTO.getMessage(), NotifierConstants.TEXT_TYPE);
            message.setFrom(new InternetAddress(mailConfigurations.getFromUser()));
            message.addRecipient(Message.RecipientType.TO, new InternetAddress(mail));
            Transport.send(message);
        } catch (MessagingException e) {
            log.error("Exception Occurred during Email notification Sending", e);
        }

    }
}

From source file:org.apache.james.core.builder.MimeMessageBuilder.java

public MimeMessage build() throws MessagingException {
    Preconditions.checkState(!(text.isPresent() && content.isPresent()),
            "Can not get at the same time a text and a content");
    MimeMessage mimeMessage = new MimeMessage(Session.getInstance(new Properties()));
    if (text.isPresent()) {
        mimeMessage.setContent(text.get(), textContentType.orElse(DEFAULT_TEXT_PLAIN_UTF8_TYPE));
    }//from  ww w.java  2  s  .c o  m
    if (content.isPresent()) {
        mimeMessage.setContent(content.get());
    }
    if (sender.isPresent()) {
        mimeMessage.setSender(sender.get());
    }
    if (subject.isPresent()) {
        mimeMessage.setSubject(subject.get());
    }
    ImmutableList<InternetAddress> fromAddresses = from.build();
    if (!fromAddresses.isEmpty()) {
        mimeMessage.addFrom(fromAddresses.toArray(new InternetAddress[fromAddresses.size()]));
    }
    List<InternetAddress> toAddresses = to.build();
    if (!toAddresses.isEmpty()) {
        mimeMessage.setRecipients(Message.RecipientType.TO,
                toAddresses.toArray(new InternetAddress[toAddresses.size()]));
    }
    List<InternetAddress> ccAddresses = cc.build();
    if (!ccAddresses.isEmpty()) {
        mimeMessage.setRecipients(Message.RecipientType.CC,
                ccAddresses.toArray(new InternetAddress[ccAddresses.size()]));
    }
    List<InternetAddress> bccAddresses = bcc.build();
    if (!bccAddresses.isEmpty()) {
        mimeMessage.setRecipients(Message.RecipientType.BCC,
                bccAddresses.toArray(new InternetAddress[bccAddresses.size()]));
    }

    MimeMessage wrappedMessage = MimeMessageWrapper.wrap(mimeMessage);

    List<Header> headerList = headers.build();
    for (Header header : headerList) {
        if (header.name.equals("Message-ID") || header.name.equals("Date")) {
            wrappedMessage.setHeader(header.name, header.value);
        } else {
            wrappedMessage.addHeader(header.name, header.value);
        }
    }
    wrappedMessage.saveChanges();

    return wrappedMessage;
}

From source file:org.apache.mailet.base.test.MimeMessageBuilder.java

public MimeMessage build() throws MessagingException {
    Preconditions.checkState(!(text.isPresent() && content.isPresent()),
            "Can not get at the same time a text and a content");
    MimeMessage mimeMessage = new MimeMessage(Session.getInstance(new Properties()));
    if (text.isPresent()) {
        BodyPart bodyPart = new MimeBodyPart();
        bodyPart.setText(text.get());/*w w w  .j  a v a 2s. co m*/
        mimeMessage.setContent(bodyPart, "text/plain");
    }
    if (content.isPresent()) {
        mimeMessage.setContent(content.get());
    }
    if (sender.isPresent()) {
        mimeMessage.setSender(sender.get());
    }
    if (from.isPresent()) {
        mimeMessage.setFrom(from.get());
    }
    if (subject.isPresent()) {
        mimeMessage.setSubject(subject.get());
    }
    List<InternetAddress> toAddresses = to.build();
    if (!toAddresses.isEmpty()) {
        mimeMessage.setRecipients(Message.RecipientType.TO,
                toAddresses.toArray(new InternetAddress[toAddresses.size()]));
    }
    List<InternetAddress> ccAddresses = cc.build();
    if (!ccAddresses.isEmpty()) {
        mimeMessage.setRecipients(Message.RecipientType.CC,
                ccAddresses.toArray(new InternetAddress[ccAddresses.size()]));
    }
    List<InternetAddress> bccAddresses = bcc.build();
    if (!bccAddresses.isEmpty()) {
        mimeMessage.setRecipients(Message.RecipientType.BCC,
                bccAddresses.toArray(new InternetAddress[bccAddresses.size()]));
    }
    List<Header> headerList = headers.build();
    for (Header header : headerList) {
        mimeMessage.addHeader(header.name, header.value);
    }
    mimeMessage.saveChanges();
    return mimeMessage;
}

From source file:mitm.common.mail.MailUtilsTest.java

@Test
public void testSaveNewMessage() throws IOException, MessagingException {
    File outputFile = File.createTempFile("mailUtilsTest", ".eml");

    outputFile.deleteOnExit();//from  ww w. ja v  a2  s  . co  m

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

    message.addFrom(new InternetAddress[] { new InternetAddress("test@example.com") });
    message.addRecipients(RecipientType.TO, "recipient@example.com");
    message.setContent("test body", "text/plain");
    message.saveChanges();

    MailUtils.writeMessage(message, new FileOutputStream(outputFile));

    MimeMessage loadedMessage = MailUtils.loadMessage(outputFile);

    String recipients = ArrayUtils.toString(loadedMessage.getRecipients(RecipientType.TO));

    assertEquals("{recipient@example.com}", recipients);

    String from = ArrayUtils.toString(loadedMessage.getFrom());

    assertEquals("{test@example.com}", from);
}

From source file:mitm.common.mail.MailUtilsTest.java

@Test
public void testSaveNewMessageRaw() throws IOException, MessagingException {
    File outputFile = File.createTempFile("mailUtilsTestRaw", ".eml");

    outputFile.deleteOnExit();//from   ww  w.  j a  v  a  2 s . com

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

    message.addFrom(new InternetAddress[] { new InternetAddress("test@example.com") });
    message.addRecipients(RecipientType.TO, "recipient@example.com");
    message.setContent("test body", "text/plain");
    message.saveChanges();

    MailUtils.writeMessageRaw(message, new FileOutputStream(outputFile));

    MimeMessage loadedMessage = MailUtils.loadMessage(outputFile);

    String recipients = ArrayUtils.toString(loadedMessage.getRecipients(RecipientType.TO));

    assertEquals("{recipient@example.com}", recipients);

    String from = ArrayUtils.toString(loadedMessage.getFrom());

    assertEquals("{test@example.com}", from);
}