Example usage for javax.mail.internet MimeMessage setText

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

Introduction

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

Prototype

@Override
public void setText(String text) throws MessagingException 

Source Link

Document

Convenience method that sets the given String as this part's content, with a MIME type of "text/plain".

Usage

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 {//from www .j a  v  a 2 s .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:org.libreplan.importers.notifications.ComposeMessage.java

public boolean composeMessageForUser(EmailNotification notification) {
    // Gather data about EmailTemplate needs to be used
    Resource resource = notification.getResource();
    EmailTemplateEnum type = notification.getType();
    Locale locale;//  w w w . ja  v a  2  s . c o m
    Worker currentWorker = getCurrentWorker(resource.getId());

    UserRole currentUserRole = getCurrentUserRole(notification.getType());

    if (currentWorker != null && currentWorker.getUser().isInRole(currentUserRole)) {
        if (currentWorker.getUser().getApplicationLanguage().equals(Language.BROWSER_LANGUAGE)) {
            locale = new Locale(System.getProperty("user.language"));
        } else {
            locale = new Locale(currentWorker.getUser().getApplicationLanguage().getLocale().getLanguage());
        }

        EmailTemplate currentEmailTemplate = findCurrentEmailTemplate(type, locale);

        if (currentEmailTemplate == null) {
            LOG.error("Email template is null");
            return false;
        }

        // Modify text that will be composed
        String text = currentEmailTemplate.getContent();
        text = replaceKeywords(text, currentWorker, notification);

        String receiver = currentWorker.getUser().getEmail();

        setupConnectionProperties();

        final String username = usrnme;
        final String password = psswrd;

        // It is very important to use Session.getInstance() instead of Session.getDefaultInstance()
        Session mailSession = Session.getInstance(properties, new javax.mail.Authenticator() {
            @Override
            protected PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication(username, password);
            }
        });

        // Send message
        try {
            MimeMessage message = new MimeMessage(mailSession);

            message.setFrom(new InternetAddress(sender));
            message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(receiver));

            String subject = currentEmailTemplate.getSubject();
            message.setSubject(subject);

            message.setText(text);

            Transport.send(message);

            return true;

        } catch (MessagingException e) {
            throw new RuntimeException(e);
        } catch (NullPointerException e) {
            if (receiver == null) {
                Messagebox.show(
                        _(currentWorker.getUser().getLoginName() + " - this user have not filled E-mail"),
                        _("Error"), Messagebox.OK, Messagebox.ERROR);
            }
        }
    }
    return false;
}

From source file:org.xwiki.mail.integration.JavaIntegrationTest.java

@Test
public void sendMailWithCustomMessageId() throws Exception {
    Session session = Session.getInstance(this.configuration.getAllProperties());
    MimeMessage message = new MimeMessage(session) {
        @Override/*w  w w  . j av  a 2 s  .c o  m*/
        protected void updateMessageID() throws MessagingException {
            if (getMessageID() == null) {
                super.updateMessageID();
            }
        }
    };
    message.setRecipient(RecipientType.TO, new InternetAddress("john@doe.com"));
    message.setText("Test message Id support");
    message.setHeader("Message-ID", "<custom@domain>");
    message.setSubject("subject");

    MailListener memoryMailListener = this.componentManager.getInstance(MailListener.class, "memory");
    this.sender.sendAsynchronously(Arrays.asList(message), session, memoryMailListener);

    // Verify that the mails have been received (wait maximum 30 seconds).
    this.mail.waitForIncomingEmail(30000L, 1);
    MimeMessage[] messages = this.mail.getReceivedMessages();

    assertEquals("<custom@domain>", messages[0].getMessageID());
}

From source file:org.nuxeo.ecm.automation.core.mail.Mailer.java

/**
 * Send a single email./* w  w w.  ja  v a2  s .  co m*/
 */
public void sendEmail(String from, String to, String subject, String body) throws MessagingException {
    // Here, no Authenticator argument is used (it is null).
    // Authenticators are used to prompt the user for user
    // name and password.
    MimeMessage message = new MimeMessage(getSession());
    // the "from" address may be set in code, or set in the
    // config file under "mail.from" ; here, the latter style is used
    message.setFrom(new InternetAddress(from));
    message.addRecipient(javax.mail.Message.RecipientType.TO, new InternetAddress(to));
    message.setSubject(subject);
    message.setText(body);
    Transport.send(message);
}

From source file:com.linuxbox.enkive.statistics.StatsReportEmailer.java

public void sendReport() {

    // Get system properties
    Properties properties = System.getProperties();

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

    // Get the default Session object.
    Session session = Session.getDefaultInstance(properties);

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

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

        // Set To: header field of the header.
        for (String toAddress : to.split(";")) {
            message.addRecipient(Message.RecipientType.TO, new InternetAddress(toAddress));
        }//w  ww . ja v  a  2s. c  om

        // Set Subject: header field
        message.setSubject("Enkive Status Report");

        // Now set the actual message
        message.setText(buildReport());

        // Send message
        Transport.send(message);
    } catch (MessagingException mex) {
        LOGGER.warn("Error sending statistics report email", mex);
    }
}

From source file:org.apache.james.protocols.smtp.AbstractStartTlsSMTPServerTest.java

@Test
public void testStartTLSWithJavamail() throws Exception {
    InetSocketAddress address = new InetSocketAddress("127.0.0.1", TestUtils.getFreePort());

    ProtocolServer server = null;//from   w  w w .  j a  va 2s. co m
    try {
        TestMessageHook hook = new TestMessageHook();
        server = createServer(createProtocol(hook), address,
                Encryption.createStartTls(BogusSslContextFactory.getServerContext()));
        server.bind();

        Properties mailProps = new Properties();
        mailProps.put("mail.smtp.from", "test@localhost");
        mailProps.put("mail.smtp.host", address.getHostName());
        mailProps.put("mail.smtp.port", address.getPort());
        mailProps.put("mail.smtp.socketFactory.class", BogusSSLSocketFactory.class.getName());
        mailProps.put("mail.smtp.socketFactory.fallback", "false");
        mailProps.put("mail.smtp.starttls.enable", "true");

        Session mailSession = Session.getDefaultInstance(mailProps);

        MimeMessage message = new MimeMessage(mailSession);
        message.setFrom(new InternetAddress("test@localhost"));
        String[] emails = { "valid@localhost" };
        Address rcpts[] = new Address[emails.length];
        for (int i = 0; i < emails.length; i++) {
            rcpts[i] = new InternetAddress(emails[i].trim().toLowerCase());
        }
        message.setRecipients(Message.RecipientType.TO, rcpts);
        message.setSubject("Testmail", "UTF-8");
        message.setText("Test.....");

        SMTPTransport transport = (SMTPTransport) mailSession.getTransport("smtps");

        transport.connect(new Socket(address.getHostName(), address.getPort()));
        transport.sendMessage(message, rcpts);

        assertEquals(1, hook.getQueued().size());

    } finally {
        if (server != null) {
            server.unbind();
        }
    }

}

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

protected void putMailInMailbox(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_ADDRESS));
        message.setSubject(EMAIL_SUBJECT + "::" + i);
        message.setText(EMAIL_TEXT + "::" + SID++);
        message.setSentDate(new Date());
        MockMailbox.get(EMAIL_USER_ADDRESS).getInbox().add(message);
    }//  w  w w  . j  a  va  2s .  co m

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

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 w w w.j a  v  a  2 s  .c  o  m

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

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

protected void putMailInMailbox3(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_ADDRESS3));
        message.setSubject(EMAIL_SUBJECT + "::" + i);
        message.setText(EMAIL_TEXT + "::" + SID++);
        message.setSentDate(new Date());
        MockMailbox.get(EMAIL_USER_ADDRESS3).getInbox().add(message);
    }// w  ww  . ja v  a2  s.c  o  m

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

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

protected void createInitialIMAPTestdata(final Properties props, final String user, final String password,
        final int count, final boolean deleteall) throws MessagingException {
    final Session session = Session.getInstance(props);
    final Store store = session.getStore();
    store.connect(user, password);//  w  w w  . j  a va 2s.co  m
    checkStoreForTestConnection(store);
    final Folder root = store.getDefaultFolder();
    final Folder testroot = root.getFolder("ES-IMAP-RIVER-TESTS");
    final Folder testrootl2 = testroot.getFolder("Level(2!");

    if (deleteall) {

        deleteMailsFromUserMailbox(props, "INBOX", 0, -1, user, password);

        if (testroot.exists()) {
            testroot.delete(true);
        }

        final Folder testrootenamed = root.getFolder("renamed_from_ES-IMAP-RIVER-TESTS");
        if (testrootenamed.exists()) {
            testrootenamed.delete(true);
        }

    }

    if (!testroot.exists()) {

        testroot.create(Folder.HOLDS_FOLDERS & Folder.HOLDS_MESSAGES);
        testroot.open(Folder.READ_WRITE);

        testrootl2.create(Folder.HOLDS_FOLDERS & Folder.HOLDS_MESSAGES);
        testrootl2.open(Folder.READ_WRITE);

    }

    final Folder inbox = root.getFolder("INBOX");
    inbox.open(Folder.READ_WRITE);

    final Message[] msgs = new Message[count];

    for (int i = 0; i < count; i++) {
        final MimeMessage message = new MimeMessage(session);
        message.setFrom(new InternetAddress(EMAIL_TO));
        message.addRecipient(Message.RecipientType.TO, new InternetAddress(EMAIL_USER_ADDRESS));
        message.setSubject(EMAIL_SUBJECT + "::" + i);
        message.setText(EMAIL_TEXT + "::" + SID++);
        message.setSentDate(new Date());
        msgs[i] = message;

    }

    inbox.appendMessages(msgs);
    testroot.appendMessages(msgs);
    testrootl2.appendMessages(msgs);

    IMAPUtils.close(inbox);
    IMAPUtils.close(testrootl2);
    IMAPUtils.close(testroot);
    IMAPUtils.close(store);

}