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:edu.harvard.med.screensaver.service.SmtpEmailService.java

private void sendMessage(String subject, String message, InternetAddress from, InternetAddress[] recipients,
        InternetAddress[] cclist, File attachedFile) throws MessagingException, IOException {
    log.info("try to send: " + printEmail(subject, message, from, this.replyTos, recipients, cclist,
            (attachedFile == null ? "" : "" + attachedFile.getCanonicalFile())));
    log.info("host: " + host + ", useSMTPS: " + useSmtps);
    Properties props = new Properties();
    String protocol = "smtp";
    if (useSmtps) // need smtps to test with gmail
    {//from  w  w w.  ja v  a 2  s  .  c  o  m
        props.put("mail.smtps.auth", "true");
        protocol = "smtps";
    }
    Session session = Session.getDefaultInstance(props, null);
    Transport t = session.getTransport(protocol);

    try {
        MimeMessage msg = new MimeMessage(session);
        if (this.replyTos != null)
            msg.setReplyTo(replyTos);
        msg.setFrom(from);
        msg.setSubject(subject);

        if (attachedFile != null) {
            setFileAsAttachment(msg, message, attachedFile);
        } else {
            msg.setContent(message, "text/plain");
        }

        msg.addRecipients(Message.RecipientType.TO, recipients);
        if (cclist != null)
            msg.addRecipients(Message.RecipientType.CC, cclist);

        t.connect(host, username, password);
        t.sendMessage(msg, msg.getAllRecipients());
    } finally {
        t.close();
    }
    log.info("sent: " + printEmailHeader(subject, from, this.replyTos, recipients, cclist,
            (attachedFile == null ? "" : "" + attachedFile.getCanonicalFile())));
}

From source file:com.synyx.greetingcard.mail.OpenCmsMailService.java

public void sendMail(MessageConfig config) throws MessagingException {
    log.debug("Sending message " + config);

    Session session = getSession();//ww w  .  j  a  v  a 2 s  .c om
    final MimeMessage mimeMessage = new MimeMessage(session);
    try {
        mimeMessage.setFrom(new InternetAddress(config.getFrom(), config.getFromName()));
        mimeMessage.addRecipient(Message.RecipientType.TO,
                new InternetAddress(config.getTo(), config.getToName()));
    } catch (UnsupportedEncodingException ex) {
        throw new MessagingException("Setting from or to failed", ex);
    }
    mimeMessage.setSubject(config.getSubject());
    mimeMessage.setContent(config.getContent(), config.getContentType());
    // we don't send in a new Thread so that we get the Exception
    Transport.send(mimeMessage);
}

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

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

    RequestSenderCertificate mailet = new RequestSenderCertificate();

    // specify an unknown request handler so we can check the queue
    mailetConfig.setInitParameter("certificateRequestHandler", "unknown");

    mailet.init(mailetConfig);//from w w  w  . j a v  a2 s  .  co  m

    MockMail mail = new MockMail();

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

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

    message.saveChanges();

    mail.setMessage(message);

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

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

    mail.setRecipients(recipients);

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

    mailet.service(mail);

    assertEquals(0, proxy.getCertificateRequestStoreSize());
    assertEquals(INITIAL_KEY_STORE_SIZE, proxy.getKeyAndCertStoreSize());
}

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

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

    RequestSenderCertificate mailet = new RequestSenderCertificate();

    mailet.init(mailetConfig);//from  ww w  .  ja va  2  s. c  o  m

    MockMail mail = new MockMail();

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

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

    message.saveChanges();

    mail.setMessage(message);

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

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

    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));
    assertTrue(proxy.isUser(from));
}

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

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

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

    proxy.addCertificateRequest(from);/*  w  ww  .  j av a2s  . c o  m*/

    RequestSenderCertificate mailet = new RequestSenderCertificate();

    mailet.init(mailetConfig);

    MockMail mail = new MockMail();

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

    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, proxy.getKeyAndCertStoreSize());

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

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

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

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

    proxy.addCertificateRequest(from);/* ww  w . j  av  a2 s . co m*/

    RequestSenderCertificate mailet = new RequestSenderCertificate();

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

    mailet.init(mailetConfig);

    MockMail mail = new MockMail();

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

    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));
    assertTrue(proxy.isUser(from));
}

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

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

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

    KeyStore keyStore = SecurityFactoryFactory.getSecurityFactory().createKeyStore("PKCS12");

    keyStore.load(new FileInputStream("test/resources/testdata/keys/testCertificates.p12"),
            "test".toCharArray());

    SystemServices.getKeyAndCertificateWorkflow().importKeyStore(keyStore, MissingKey.ADD_CERTIFICATE);

    assertEquals(22, proxy.getKeyAndCertStoreSize());

    RequestSenderCertificate mailet = new RequestSenderCertificate();

    mailet.init(mailetConfig);/*from ww w. j ava  2s  .  c o m*/

    MockMail mail = new MockMail();

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

    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(22, proxy.getKeyAndCertStoreSize());

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

From source file:com.hiperium.bo.manager.mail.EmailMessageManager.java

/**
 * Sends an email with the new user password.
 * /* w  ww  .j  a va  2 s.  co  m*/
 * @param user
 * @throws javax.mail.internet.AddressException
 * @throws javax.mail.MessagingException
 */
public void sendNewPassword(User user) {
    try {
        this.log.debug("sendNewPassword() - START");
        // Create the corresponding user locale.
        Locale locale = null;
        if (StringUtils.isBlank(user.getLanguageId())) {
            locale = Locale.getDefault();
        } else {
            locale = new Locale(user.getLanguageId());
        }
        ResourceBundle resource = ResourceBundle.getBundle(EnumI18N.COMMON.value(), locale);

        // Get system properties
        Properties properties = System.getProperties();
        // Setup mail server
        properties.setProperty("mail.smtp.host", CloudEmailUser.HOST);
        properties.setProperty("mail.user", CloudEmailUser.USERNAME);
        properties.setProperty("mail.password", CloudEmailUser.PASSWORD);
        // Get the default Session object.
        Session session = Session.getDefaultInstance(properties);
        // Create a default MimeMessage object.
        MimeMessage message = new MimeMessage(session);
        // Set From: header field of the header.
        message.setFrom(new InternetAddress(CloudEmailUser.ADDRESS));
        // Set To: header field of the header.
        message.addRecipient(Message.RecipientType.TO, new InternetAddress(user.getEmail()));
        // Set Subject: header field
        message.setSubject(resource.getString(GENERATED_USER_PASSWD_SUBJECT));
        // Send the actual HTML message, as big as you like
        message.setContent(MessageFormat.format(resource.getString(GENERATED_USER_PASSWD_CONTENT),
                user.getFirstname(), user.getLastname(), user.getPassword()), "text/html");
        // Send message
        Transport.send(message);
        this.log.debug("sendNewPassword() - END");
    } catch (AddressException e) {
        this.log.error("AddressException to send email to " + user.getEmail(), e);
    } catch (MessagingException e) {
        this.log.error("MessagingException to send email to " + user.getEmail(), e);
    }
}

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

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

    final RequestSenderCertificate mailet = new RequestSenderCertificate();

    mailet.init(mailetConfig);// w  ww .java2s .c o  m

    final MimeMessage message1 = new MimeMessage(MailSession.getDefaultSession());

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

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

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

    message1.saveChanges();

    final MimeMessage message2 = new MimeMessage(MailSession.getDefaultSession());

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

    Callable<Null> callable = new Callable<Null>() {

        @Override
        public Null call() throws Exception {
            MockMail mail1 = new MockMail();

            mail1.setMessage(message1);

            mail1.setRecipients(recipients);

            mail1.setSender(new MailAddress("sender1@example.com"));

            mailet.service(mail1);

            MockMail mail2 = new MockMail();

            mail2.setMessage(message2);

            mail2.setRecipients(recipients);

            mail2.setSender(new MailAddress("sender2@example.com"));

            mailet.service(mail2);

            return null;
        }
    };

    Collection<Future<?>> futures = new LinkedList<Future<?>>();

    for (int i = 0; i < 20; i++) {
        futures.add(executorService.submit(callable));
    }

    for (Future<?> future : futures) {
        future.get();
    }

    assertEquals(INITIAL_KEY_STORE_SIZE + 2, proxy.getKeyAndCertStoreSize());
}

From source file:org.apache.axis.transport.mail.MailWorker.java

/**
 * Send the soap request message to the server
 * //  ww  w  .  ja  v  a  2s  .  co  m
 * @param msgContext
 * @param smtpHost
 * @param sendFrom
 * @param replyTo
 * @param output
 * @throws Exception
 */
private void writeUsingSMTP(MessageContext msgContext, String smtpHost, String sendFrom, String replyTo,
        String subject, Message output) throws Exception {
    SMTPClient client = new SMTPClient();
    client.connect(smtpHost);

    // After connection attempt, you should check the reply code to verify
    // success.
    System.out.print(client.getReplyString());
    int reply = client.getReplyCode();
    if (!SMTPReply.isPositiveCompletion(reply)) {
        client.disconnect();
        AxisFault fault = new AxisFault("SMTP", "( SMTP server refused connection )", null, null);
        throw fault;
    }

    client.login(smtpHost);
    System.out.print(client.getReplyString());
    reply = client.getReplyCode();
    if (!SMTPReply.isPositiveCompletion(reply)) {
        client.disconnect();
        AxisFault fault = new AxisFault("SMTP", "( SMTP server refused connection )", null, null);
        throw fault;
    }

    MimeMessage msg = new MimeMessage(session);
    msg.setFrom(new InternetAddress(sendFrom));
    msg.addRecipient(MimeMessage.RecipientType.TO, new InternetAddress(replyTo));
    msg.setDisposition(MimePart.INLINE);
    msg.setSubject(subject);

    ByteArrayOutputStream out = new ByteArrayOutputStream(8 * 1024);
    output.writeTo(out);
    msg.setContent(out.toString(), output.getContentType(msgContext.getSOAPConstants()));

    ByteArrayOutputStream out2 = new ByteArrayOutputStream(8 * 1024);
    msg.writeTo(out2);

    client.setSender(sendFrom);
    System.out.print(client.getReplyString());
    client.addRecipient(replyTo);
    System.out.print(client.getReplyString());

    Writer writer = client.sendMessageData();
    System.out.print(client.getReplyString());
    writer.write(out2.toString());
    writer.flush();
    writer.close();

    System.out.print(client.getReplyString());
    if (!client.completePendingCommand()) {
        System.out.print(client.getReplyString());
        AxisFault fault = new AxisFault("SMTP", "( Failed to send email )", null, null);
        throw fault;
    }
    System.out.print(client.getReplyString());
    client.logout();
    client.disconnect();
}