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:org.sakaiproject.email.impl.BasicEmailService.java

protected void sendMessageAndLog(InternetAddress from, InternetAddress[] to, String subject,
        Map<RecipientType, InternetAddress[]> headerTo, long start, MimeMessage msg, Session session)
        throws MessagingException {
    long preSend = 0;
    if (M_log.isDebugEnabled())
        preSend = System.currentTimeMillis();

    if (allowTransport) {
        msg.saveChanges();

        Transport transport = session.getTransport(protocol);

        if (m_smtpUser != null && m_smtpPassword != null)
            transport.connect(m_smtp, m_smtpUser, m_smtpPassword);
        else/*w w  w .j av a2s.  c  o m*/
            transport.connect();

        transport.sendMessage(msg, to);

        transport.close();
    }

    long end = 0;
    if (M_log.isDebugEnabled())
        end = System.currentTimeMillis();

    if (M_log.isInfoEnabled()) {
        StringBuilder buf = new StringBuilder();
        buf.append("Email.sendMail: from: ");
        buf.append(from);
        buf.append(" subject: ");
        buf.append(subject);
        buf.append(" to:");
        for (int i = 0; i < to.length; i++) {
            buf.append(" ");
            buf.append(to[i]);
        }
        if (headerTo != null) {
            if (headerTo.containsKey(RecipientType.TO)) {
                buf.append(" headerTo{to}:");
                InternetAddress[] headerToTo = headerTo.get(RecipientType.TO);
                for (int i = 0; i < headerToTo.length; i++) {
                    buf.append(" ");
                    buf.append(headerToTo[i]);
                }
            }
            if (headerTo.containsKey(RecipientType.CC)) {
                buf.append(" headerTo{cc}:");
                InternetAddress[] headerToCc = headerTo.get(RecipientType.CC);
                for (int i = 0; i < headerToCc.length; i++) {
                    buf.append(" ");
                    buf.append(headerToCc[i]);
                }
            }
            if (headerTo.containsKey(RecipientType.BCC)) {
                buf.append(" headerTo{bcc}:");
                InternetAddress[] headerToBcc = headerTo.get(RecipientType.BCC);
                for (int i = 0; i < headerToBcc.length; i++) {
                    buf.append(" ");
                    buf.append(headerToBcc[i]);
                }
            }
        }
        try {
            if (msg.getContent() instanceof Multipart) {
                Multipart parts = (Multipart) msg.getContent();
                buf.append(" with ").append(parts.getCount() - 1).append(" attachments");
            }
        } catch (IOException ioe) {
        }

        if (M_log.isDebugEnabled()) {
            buf.append(" time: ");
            buf.append("" + (end - start));
            buf.append(" in send: ");
            buf.append("" + (end - preSend));
        }

        M_log.info(buf.toString());
    }
}

From source file:org.sakaiproject.tool.assessment.util.SamigoEmailService.java

public String sendMail() {
    try {/*  www.j  a v  a2  s  .c o m*/
        Properties props = new Properties();

        // Server
        if (smtpServer == null || smtpServer.equals("")) {
            log.info("samigo.email.smtpServer is not set");
            smtpServer = ServerConfigurationService.getString("smtp@org.sakaiproject.email.api.EmailService");
            if (smtpServer == null || smtpServer.equals("")) {
                log.info("smtp@org.sakaiproject.email.api.EmailService is not set");
                log.error(
                        "Please set the value of samigo.email.smtpServer or smtp@org.sakaiproject.email.api.EmailService");
                return "error";
            }
        }
        props.setProperty("mail.smtp.host", smtpServer);

        // Port
        if (smtpPort == null || smtpPort.equals("")) {
            log.warn("samigo.email.smtpPort is not set. The default port 25 will be used.");
        } else {
            props.setProperty("mail.smtp.port", smtpPort);
        }

        props.put("mail.smtp.sendpartial", "true");

        Session session = Session.getInstance(props, null);
        session.setDebug(true);
        MimeMessage msg = new MimeMessage(session);

        InternetAddress fromIA = new InternetAddress(fromEmailAddress, fromName);
        msg.setFrom(fromIA);

        //msg.addHeaderLine("Subject: " + subject);
        msg.setSubject(subject, "UTF-8");
        String noReplyEmaillAddress = ServerConfigurationService.getString("setup.request",
                "no-reply@" + ServerConfigurationService.getServerName());
        msg.addHeaderLine("To: " + noReplyEmaillAddress);
        msg.setText(message, "UTF-8");
        msg.addHeaderLine("Content-Type: text/html");

        ArrayList<InternetAddress> toIAList = new ArrayList<InternetAddress>();
        String email = "";
        Iterator iter = toEmailAddressList.iterator();
        while (iter.hasNext()) {
            try {
                email = (String) iter.next();
                toIAList.add(new InternetAddress(email));
            } catch (AddressException ae) {
                log.error("invalid email address: " + email);
            }
        }

        InternetAddress[] toIA = new InternetAddress[toIAList.size()];
        int count = 0;
        Iterator iter2 = toIAList.iterator();
        while (iter2.hasNext()) {
            toIA[count++] = (InternetAddress) iter2.next();
        }

        try {
            Transport transport = session.getTransport("smtp");
            msg.saveChanges();
            transport.connect();

            try {
                transport.sendMessage(msg, toIA);
            } catch (SendFailedException e) {
                log.debug("SendFailedException: " + e);
                return "error";
            } catch (MessagingException e) {
                log.warn("1st MessagingException: " + e);
                return "error";
            }
            transport.close();
        } catch (MessagingException e) {
            log.warn("2nd MessagingException:" + e);
            return "error";
        }

    } catch (UnsupportedEncodingException ue) {
        log.warn("UnsupportedEncodingException:" + ue);
        ue.printStackTrace();

    } catch (MessagingException me) {
        log.warn("3rd MessagingException:" + me);
        return "error";
    }
    return "send";
}

From source file:org.sigmah.server.mail.MailSenderImpl.java

@Override
public void sendFile(Email email, String fileName, InputStream fileStream) throws EmailException {
    final String user = email.getAuthenticationUserName();
    final String password = email.getAuthenticationPassword();

    final Properties properties = new Properties();
    properties.setProperty(MAIL_TRANSPORT_PROTOCOL, TRANSPORT_PROTOCOL);
    properties.setProperty(MAIL_SMTP_HOST, email.getHostName());
    properties.setProperty(MAIL_SMTP_PORT, Integer.toString(email.getSmtpPort()));

    final StringBuilder toBuilder = new StringBuilder();
    for (final String to : email.getToAddresses()) {
        if (toBuilder.length() > 0) {
            toBuilder.append(',');
        }//w  w w .  j a va 2 s .c o m
        toBuilder.append(to);
    }

    final StringBuilder ccBuilder = new StringBuilder();
    if (email.getCcAddresses().length > 0) {
        for (final String cc : email.getCcAddresses()) {
            if (ccBuilder.length() > 0) {
                ccBuilder.append(',');
            }
            ccBuilder.append(cc);
        }
    }

    final Session session = javax.mail.Session.getInstance(properties);
    try {
        final DataSource attachment = new ByteArrayDataSource(fileStream,
                FileType.fromExtension(FileType.getExtension(fileName), FileType._DEFAULT).getContentType());

        final Transport transport = session.getTransport();

        if (password != null) {
            transport.connect(user, password);
        } else {
            transport.connect();
        }

        final MimeMessage message = new MimeMessage(session);

        // Configures the headers.
        message.setFrom(new InternetAddress(email.getFromAddress(), false));
        message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(toBuilder.toString(), false));
        if (email.getCcAddresses().length > 0) {
            message.setRecipients(Message.RecipientType.CC, InternetAddress.parse(ccBuilder.toString(), false));
        }

        message.setSubject(email.getSubject(), email.getEncoding());

        // Html body part.
        final MimeMultipart textMultipart = new MimeMultipart("alternative");

        final MimeBodyPart htmlBodyPart = new MimeBodyPart();
        htmlBodyPart.setContent(email.getContent(), "text/html; charset=\"" + email.getEncoding() + "\"");
        textMultipart.addBodyPart(htmlBodyPart);

        final MimeBodyPart textBodyPart = new MimeBodyPart();
        textBodyPart.setContent(textMultipart);

        // Attachment body part.
        final MimeBodyPart attachmentPart = new MimeBodyPart();
        attachmentPart.setDataHandler(new DataHandler(attachment));
        attachmentPart.setFileName(fileName);
        attachmentPart.setDescription(fileName);

        // Mail multipart content.
        final MimeMultipart contentMultipart = new MimeMultipart("related");
        contentMultipart.addBodyPart(textBodyPart);
        contentMultipart.addBodyPart(attachmentPart);

        message.setContent(contentMultipart);
        message.saveChanges();

        // Sends the mail.
        transport.sendMessage(message, message.getAllRecipients());

    } catch (UnsupportedEncodingException ex) {
        throw new EmailException(
                "An error occured while encoding the mail content to '" + email.getEncoding() + "'.", ex);

    } catch (IOException ex) {
        throw new EmailException("An error occured while reading the attachment of an email.", ex);

    } catch (MessagingException ex) {
        throw new EmailException("An error occured while sending an email.", ex);
    }
}

From source file:org.springframework.mail.javamail.JavaMailSenderImpl.java

/**
 * Actually send the given array of MimeMessages via JavaMail.
 * @param mimeMessages MimeMessage objects to send
 * @param originalMessages corresponding original message objects
 * that the MimeMessages have been created from (with same array
 * length and indices as the "mimeMessages" array), if any
 * @throws org.springframework.mail.MailAuthenticationException
 * in case of authentication failure/*from   w ww.  java 2 s  . c  o  m*/
 * @throws org.springframework.mail.MailSendException
 * in case of failure when sending a message
 */
protected void doSend(MimeMessage[] mimeMessages, Object[] originalMessages) throws MailException {
    Map failedMessages = new HashMap();
    try {
        Transport transport = getTransport(getSession());
        transport.connect(getHost(), getPort(), getUsername(), getPassword());
        try {
            for (int i = 0; i < mimeMessages.length; i++) {
                MimeMessage mimeMessage = mimeMessages[i];
                try {
                    if (mimeMessage.getSentDate() == null) {
                        mimeMessage.setSentDate(new Date());
                    }
                    mimeMessage.saveChanges();
                    transport.sendMessage(mimeMessage, mimeMessage.getAllRecipients());
                } catch (MessagingException ex) {
                    Object original = (originalMessages != null ? originalMessages[i] : mimeMessage);
                    failedMessages.put(original, ex);
                }
            }
        } finally {
            transport.close();
        }
    } catch (AuthenticationFailedException ex) {
        throw new MailAuthenticationException(ex);
    } catch (MessagingException ex) {
        throw new MailSendException("Mail server connection failed", ex);
    }
    if (!failedMessages.isEmpty()) {
        throw new MailSendException(failedMessages);
    }
}

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

@Test
public void sendTextMail() throws Exception {
    // Step 1: Create a JavaMail Session
    Session session = Session.getInstance(this.configuration.getAllProperties());

    // Step 2: Create the Message to send
    MimeMessage message = new MimeMessage(session);
    message.setSubject("subject");
    message.setRecipient(RecipientType.TO, new InternetAddress("john@doe.com"));

    // Step 3: Add the Message Body
    Multipart multipart = new MimeMultipart("mixed");
    // Add text in the body
    multipart.addBodyPart(this.defaultBodyPartFactory.create("some text here",
            Collections.<String, Object>singletonMap("mimetype", "text/plain")));
    message.setContent(multipart);//from   w ww.j  a v a 2  s.c om

    // We also test using some default BCC addresses from configuration in this test
    this.configuration.setBCCAddresses(Arrays.asList("bcc1@doe.com", "bcc2@doe.com"));

    // Ensure we do not reuse the same message identifier for multiple similar messages in this test
    MimeMessage message2 = new MimeMessage(message);
    message2.saveChanges();
    MimeMessage message3 = new MimeMessage(message);
    message3.saveChanges();

    // Step 4: Send the mail and wait for it to be sent
    // Send 3 mails (3 times the same mail) to verify we can send several emails at once.
    MailListener memoryMailListener = this.componentManager.getInstance(MailListener.class, "memory");
    this.sender.sendAsynchronously(Arrays.asList(message, message2, message3), session, memoryMailListener);

    // Note: we don't test status reporting from the listener since this is already tested in the
    // ScriptingIntegrationTest test class.

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

    // Note: we're receiving 9 messages since we sent 3 with 3 recipients (2 BCC and 1 to)!
    assertEquals(9, messages.length);

    // Assert the email parts that are the same for all mails
    assertEquals("subject", messages[0].getHeader("Subject", null));
    assertEquals(1, ((MimeMultipart) messages[0].getContent()).getCount());
    BodyPart textBodyPart = ((MimeMultipart) messages[0].getContent()).getBodyPart(0);
    assertEquals("text/plain", textBodyPart.getHeader("Content-Type")[0]);
    assertEquals("some text here", textBodyPart.getContent());
    assertEquals("john@doe.com", messages[0].getHeader("To", null));

    // Note: We cannot assert that the BCC worked since by definition BCC information are not visible in received
    // messages ;) But we checked that we received 9 emails above so that's good enough.
}

From source file:se.inera.axel.shs.processor.ShsMessageMarshaller.java

public void marshal(ShsMessage shsMessage, OutputStream outputStream) throws IllegalMessageStructureException {
    log.trace("marshal(ShsMessage, OutputStream)");

    MimeMultipart multipart = new MimeMultipart();
    BodyPart bodyPart = new MimeBodyPart();

    try {/* www .j av  a2  s. c o  m*/

        ShsLabel label = shsMessage.getLabel();
        if (label == null) {
            throw new IllegalMessageStructureException("label not found in shs message");
        }

        Content content = label.getContent();
        if (content == null) {
            throw new IllegalMessageStructureException("label/content not found in shs label");
        } else {
            // we will update this according to our data parts below.
            content.getDataOrCompound().clear();

            String contentId = content.getContentId();
            content.setContentId(contentId.substring(0, Math.min(contentId.length(), MAX_LENGTH_CONTENT_ID)));
        }

        List<DataPart> dataParts = shsMessage.getDataParts();

        if (dataParts.isEmpty()) {
            throw new IllegalMessageStructureException("dataparts not found in message");
        }

        for (DataPart dp : dataParts) {
            Data data = new Data();

            data.setDatapartType(dp.getDataPartType());
            data.setFilename(dp.getFileName());
            if (dp.getContentLength() != null && dp.getContentLength() > 0)
                data.setNoOfBytes("" + dp.getContentLength());
            content.getDataOrCompound().add(data);
        }

        bodyPart.setContent(shsLabelMarshaller.marshal(label), "text/xml; charset=ISO-8859-1");
        bodyPart.setHeader("Content-Transfer-Encoding", "binary");

        multipart.addBodyPart(bodyPart);

        for (DataPart dataPart : dataParts) {

            bodyPart = new MimeBodyPart();

            bodyPart.setDisposition(Part.ATTACHMENT);
            if (StringUtils.isNotBlank(dataPart.getFileName())) {
                bodyPart.setFileName(dataPart.getFileName());
            }

            bodyPart.setDataHandler(dataPart.getDataHandler());

            if (dataPart.getTransferEncoding() != null) {
                bodyPart.addHeader("Content-Transfer-Encoding", dataPart.getTransferEncoding().toLowerCase());
            }
            multipart.addBodyPart(bodyPart);
        }

        MimeMessage mimeMessage = new MimeMessage(session);
        mimeMessage.setSubject("SHS Message");
        mimeMessage.addHeader("Content-Transfer-Encoding", "binary");

        mimeMessage.setContent(multipart);
        mimeMessage.saveChanges();

        String ignoreList[] = { "Message-ID" };

        mimeMessage.writeTo(outputStream, ignoreList);
        outputStream.flush();

    } catch (Exception e) {
        if (e instanceof IllegalMessageStructureException) {
            throw (IllegalMessageStructureException) e;
        }
        throw new IllegalMessageStructureException(e);
    }

}