Example usage for javax.mail.internet MimeMessage saveChanges

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

Introduction

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

Prototype

@Override
public void saveChanges() throws MessagingException 

Source Link

Document

Updates the appropriate header fields of this message to be consistent with the message's contents.

Usage

From source file:mitm.application.djigzo.mail.repository.MailRepositoryEventListenerImpl.java

private void sendNotification(Notification notification, MailRepositoryItem item, Set<String> recipients,
        String templateSource) {/*from   ww  w .j  a va2 s .co m*/
    SimpleHash root = new SimpleHash();
    SimpleHash org = new SimpleHash();

    org.put("subject", StringUtils.defaultString(item.getSubject()));
    org.put("id", StringUtils.defaultString(item.getID()));
    org.put("from", StringUtils.defaultString(item.getFromHeader()));
    org.put("messageID", StringUtils.defaultString(item.getMessageID()));

    root.put("org", org);
    root.put("recipients", recipients);

    try {
        ByteArrayOutputStream bos = new ByteArrayOutputStream();

        Writer writer = new OutputStreamWriter(bos);

        Template template = templateBuilder.createTemplate(new StringReader(templateSource));

        template.process(root, writer);

        MimeMessage message = MailUtils.byteArrayToMessage(bos.toByteArray());

        message.saveChanges();

        MailUtils.validateMessage(message);

        MailImpl mail = new MailImpl(MailetUtils.createUniqueMailName(), null,
                MailAddressUtils.toMailAddressList(recipients), message);

        mail.setState(newMailProcessor);

        JamesStoreManager storemanager = new JamesStoreManager(serviceManager);

        try {
            storemanager.store(mail);
        } finally {
            mail.dispose();
        }
    } catch (IOException e) {
        logger.error("Error creating the notification template.", e);
    } catch (TemplateException e) {
        logger.error("The template is not a valid Freemarker template or variables are missing.", e);
    } catch (MessagingException e) {
        logger.error("The resulting mime message is not valid.", e);
    } catch (ServiceException e) {
        logger.error("Error getting the JamesStoreManager.", e);
    }
}

From source file:com.enjoyxstudy.selenium.autoexec.mail.MailSender.java

/**
 * @param mimeMessage//from  ww  w  . j  a v  a2  s.c o  m
 * @throws MessagingException
 */
private void _send(MimeMessage mimeMessage) throws MessagingException {

    Transport transport = null;

    try {

        transport = session.getTransport();
        transport.connect();

        mimeMessage.setSentDate(new Date());
        mimeMessage.saveChanges();

        transport.sendMessage(mimeMessage, mimeMessage.getAllRecipients());
    } finally {
        if (transport != null && transport.isConnected()) {
            transport.close();
        }
    }
}

From source file:io.kamax.mxisd.threepid.connector.email.EmailSmtpConnector.java

@Override
public void send(String senderAddress, String senderName, String recipient, String content) {
    if (StringUtils.isBlank(senderAddress)) {
        throw new FeatureNotAvailable("3PID Email identity: sender address is empty - "
                + "You must set a value for notifications to work");
    }//from w w w .  j av  a 2 s .c o m

    if (StringUtils.isBlank(content)) {
        throw new InternalServerError("Notification content is empty");
    }

    try {
        InternetAddress sender = new InternetAddress(senderAddress, senderName);
        MimeMessage msg = new MimeMessage(session, IOUtils.toInputStream(content, StandardCharsets.UTF_8));
        msg.setHeader("X-Mailer", "mxisd"); // FIXME set version
        msg.setSentDate(new Date());
        msg.setFrom(sender);
        msg.setRecipients(Message.RecipientType.TO, recipient);
        msg.saveChanges();

        log.info("Sending invite to {} via SMTP using {}:{}", recipient, cfg.getHost(), cfg.getPort());
        SMTPTransport transport = (SMTPTransport) session.getTransport("smtp");
        transport.setStartTLS(cfg.getTls() > 0);
        transport.setRequireStartTLS(cfg.getTls() > 1);

        log.info("Connecting to {}:{}", cfg.getHost(), cfg.getPort());
        transport.connect(cfg.getHost(), cfg.getPort(), cfg.getLogin(), cfg.getPassword());
        try {
            transport.sendMessage(msg, InternetAddress.parse(recipient));
            log.info("Invite to {} was sent", recipient);
        } finally {
            transport.close();
        }
    } catch (UnsupportedEncodingException | MessagingException e) {
        throw new RuntimeException("Unable to send e-mail invite to " + recipient, e);
    }
}

From source file:davmail.smtp.TestSmtp.java

public void sendAndCheckMessage(MimeMessage mimeMessage, String from, String bcc)
        throws IOException, MessagingException, InterruptedException {
    // generate message id
    mimeMessage.saveChanges();
    // mimeMessage.writeTo(System.out);

    // copy Message-id to references header
    mimeMessage.addHeader("references", mimeMessage.getHeader("message-id")[0]);
    if (from != null) {
        writeLine("MAIL FROM:" + from);
    } else {//from  w  ww .j  a  va 2 s.c o  m
        writeLine("MAIL FROM:" + session.getEmail());
    }
    readLine();
    if (bcc != null) {
        writeLine("RCPT TO:" + bcc);
        readLine();
    }
    writeLine("RCPT TO:" + Settings.getProperty("davmail.to"));
    readLine();
    writeLine("DATA");
    assertEquals("354 Start mail input; end with <CRLF>.<CRLF>", readLine());
    mimeMessage.writeTo(new DoubleDotOutputStream(socketOutputStream));
    writeLine("");
    writeLine(".");
    assertEquals("250 Queued mail for delivery", readLine());
    // wait for asynchronous message send
    ExchangeSession.MessageList messages = null;
    for (int i = 0; i < 5; i++) {
        messages = session.searchMessages("Sent",
                session.headerIsEqualTo("references", mimeMessage.getMessageID()));
        if (messages.size() > 0) {
            break;
        }
        Thread.sleep(1000);
    }
    assertEquals(1, messages.size());
    ExchangeSession.Message sentMessage = messages.get(0);
    sentMessage.getMimeMessage().writeTo(System.out);
    assertEquals(mimeMessage.getDataHandler().getContent(),
            sentMessage.getMimeMessage().getDataHandler().getContent());
}

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

@Test
public void testUnknownCharsetAddHeader() throws IOException, MessagingException {
    MimeMessage message = loadMessage("unknown-charset.eml");

    message.addHeader("X-Test", "test");

    message.saveChanges();

    MailUtils.validateMessage(message);// w  w  w .j a  v a2s .  c om
}

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

@Test
public void testUnknownContentTypeAddHeader() throws IOException, MessagingException {
    MimeMessage message = loadMessage("unknown-content-type.eml");

    message.addHeader("X-Test", "test");

    message.saveChanges();

    MailUtils.validateMessage(message);/*from  w w w . j a  va 2 s . c  om*/
}

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

@Test
public void testConvert8BitTo7BitMultipart() throws IOException, MessagingException {
    MimeMessage message = loadMessage("8bit-multipart.eml");

    assertTrue(MailUtils.convertTo7Bit(message));

    message.saveChanges();

    MailUtils.validateMessage(message);/*from w ww.j  a v a 2  s  . c  o m*/

    File file = new File("test/tmp/testConvert8BitTo7BitMultipart.eml");

    MailUtils.writeMessage(message, file);

    String mime = FileUtils.readFileToString(file);

    assertTrue(mime.contains("X-MIME-Autoconverted: from 8bit to base64 by Djigzo"));
    assertTrue(mime.contains("X-MIME-Autoconverted: from 8bit to quoted-printable by Djigzo"));
    assertTrue(mime.contains("This is a test with unlauts: Sch=C3=B6n"));
    assertTrue(mime.contains("VGhpcyBpcyBhIHRlc3Qgd2l0aCB1bmxhdXRzOiBTY2jDtm4K"));
}

From source file:org.apache.james.transport.mailets.SerialiseToHTTP.java

private void addHeader(Mail mail, boolean success, String errorMessage) {
    try {//from   w ww  .ja  v a  2 s.  c om
        MimeMessage message = mail.getMessage();
        message.setHeader("X-toHTTP", (success ? "Succeeded" : "Failed"));
        if (!success && errorMessage != null && errorMessage.length() > 0) {
            message.setHeader("X-toHTTPFailure", errorMessage);
        }
        message.saveChanges();
    } catch (MessagingException e) {
        log(e.getMessage());
    }
}

From source file:org.apache.james.transport.mailets.HeadersToHTTP.java

private void addHeader(Mail mail, boolean success, String errorMessage) {
    try {//w w w. j a v a2 s .  c  o  m
        MimeMessage message = mail.getMessage();
        message.setHeader("X-headerToHTTP", (success ? "Succeeded" : "Failed"));
        if (!success && errorMessage != null && errorMessage.length() > 0) {
            message.setHeader("X-headerToHTTPFailure", errorMessage);
        }
        message.saveChanges();
    } catch (MessagingException e) {
        log(e.getMessage());
    }
}

From source file:easyproject.service.Mail.java

public void sendMail() {
    Properties props = new Properties();

    props.put("mail.debug", "true");
    props.put("mail.smtp.auth", true);
    props.put("mail.smtp.starttls.enable", true);
    props.put("mail.smtp.host", servidorSMTP);
    props.put("mail.smtp.port", puerto);

    Session session = Session.getInstance(props, null);

    try {/*from www. ja v a2s.  c  om*/
        MimeMessage message = new MimeMessage(session);

        message.addRecipient(Message.RecipientType.TO, new InternetAddress(destino));
        message.setSubject(asunto);
        message.setSentDate(new Date());
        message.setContent(mensaje, "text/html; charset=utf-8");

        Transport tr = session.getTransport("smtp");
        tr.connect(servidorSMTP, usuario, password);
        message.saveChanges();
        tr.sendMessage(message, message.getAllRecipients());
        tr.close();

    } catch (MessagingException e) {
        e.printStackTrace();
    }
}