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:com.haulmont.cuba.core.app.EmailSender.java

protected MimeMessage createMimeMessage(SendingMessage sendingMessage) throws MessagingException {
    MimeMessage msg = mailSender.createMimeMessage();
    assignRecipient(sendingMessage, msg);
    msg.setSubject(sendingMessage.getCaption(), StandardCharsets.UTF_8.name());
    msg.setSentDate(timeSource.currentTimestamp());

    assignFromAddress(sendingMessage, msg);
    addHeaders(sendingMessage, msg);//from  w w w  .  j  av a 2  s  .  com

    MimeMultipart content = new MimeMultipart("mixed");
    MimeMultipart textPart = new MimeMultipart("related");

    setMimeMessageContent(sendingMessage, content, textPart);

    for (SendingAttachment attachment : sendingMessage.getAttachments()) {
        MimeBodyPart attachmentPart = createAttachmentPart(attachment);

        if (attachment.getContentId() == null) {
            content.addBodyPart(attachmentPart);
        } else
            textPart.addBodyPart(attachmentPart);
    }

    msg.setContent(content);
    msg.saveChanges();
    return msg;
}

From source file:com.zimbra.cs.service.FeedManager.java

private static ParsedMessage generateMessage(String title, String content, String ctype, InternetAddress addr,
        Date date, List<Enclosure> attach) throws ServiceException {
    // cull out invalid enclosures
    if (attach != null) {
        for (Iterator<Enclosure> it = attach.iterator(); it.hasNext();) {
            if (it.next().getLocation() == null) {
                it.remove();// www .j  av a  2s .  c o  m
            }
        }
    }
    boolean hasAttachments = attach != null && !attach.isEmpty();

    // clean up whitespace in the title
    if (title != null) {
        title = title.replaceAll("\\s+", " ");
    }

    // create the MIME message and wrap it
    try {
        MimeMessage mm = new Mime.FixedMimeMessage(JMSession.getSession());
        MimePart body = hasAttachments ? new ZMimeBodyPart() : (MimePart) mm;
        body.setText(content, "utf-8");
        body.setHeader("Content-Type", ctype);

        if (hasAttachments) {
            // encode each enclosure as an attachment with Content-Location set
            MimeMultipart mmp = new ZMimeMultipart("mixed");
            mmp.addBodyPart((BodyPart) body);
            for (Enclosure enc : attach) {
                MimeBodyPart part = new ZMimeBodyPart();
                part.setText("");
                part.addHeader("Content-Location", enc.getLocation());
                part.addHeader("Content-Type", enc.getContentType());
                if (enc.getDescription() != null) {
                    part.addHeader("Content-Description", enc.getDescription());
                }
                part.addHeader("Content-Disposition", "attachment");
                mmp.addBodyPart(part);
            }
            mm.setContent(mmp);
        }

        mm.setSentDate(date);
        mm.addFrom(new InternetAddress[] { addr });
        mm.setSubject(title, "utf-8");
        // more stuff here!
        mm.saveChanges();
        return new ParsedMessage(mm, date.getTime(), false);
    } catch (MessagingException e) {
        throw ServiceException.PARSE_ERROR("error wrapping feed item in MimeMessage", e);
    }
}

From source file:eu.scape_project.pw.idp.UserManager.java

/**
 * Method responsible for sending a email to the user, including a link to
 * activate his user account./*w  w w  . j  ava  2s. com*/
 * 
 * @param user
 *            User the activation mail should be sent to
 * @param serverString
 *            Name and port of the server the user was added.
 * @throws CannotSendMailException
 *             if the mail could not be sent
 */
public void sendActivationMail(IdpUser user, String serverString) throws CannotSendMailException {

    try {
        Properties props = System.getProperties();

        props.put("mail.smtp.host", config.getString("mail.smtp.host"));
        Session session = Session.getDefaultInstance(props, null);

        MimeMessage message = new MimeMessage(session);
        message.setFrom(new InternetAddress(config.getString("mail.from")));
        message.setRecipient(RecipientType.TO, new InternetAddress(user.getEmail()));
        message.setSubject("Please confirm your Planningsuite user account");

        StringBuilder builder = new StringBuilder();
        builder.append("Dear " + user.getFirstName() + " " + user.getLastName() + ", \n\n");
        builder.append("Please use the following link to confirm your Planningsuite user account: \n");
        builder.append("http://" + serverString + "/idp/activateUser.jsf?uid=" + user.getActionToken());
        builder.append("\n\n--\n");
        builder.append("Your Planningsuite team");

        message.setText(builder.toString());
        message.saveChanges();

        Transport.send(message);
        log.debug("Activation mail sent successfully to {}", user.getEmail());
    } catch (Exception e) {
        log.error("Error at sending activation mail to {}", user.getEmail());
        throw new CannotSendMailException("Error at sending activation mail to " + user.getEmail(), e);
    }
}

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

@Override
public void serviceMail(Mail mail) {
    try {//from ww w  .j a va 2s.  co m
        MimeMessage sourceMessage = mail.getMessage();

        MimeMessage newMessage = retainMessageID
                ? new MimeMessageWithID(MailSession.getDefaultSession(), sourceMessage.getMessageID())
                : new MimeMessage(MailSession.getDefaultSession());

        if (StringUtils.isNotEmpty(filename)) {
            newMessage.setFileName(filename);
        }

        Multipart mp = new MimeMultipart();

        HeaderMatcher contentMatcher = new ContentHeaderNameMatcher();

        mp.addBodyPart(BodyPartUtils.makeContentBodyPart(sourceMessage, contentMatcher));

        newMessage.setContent(mp);

        /* 
         * create a matcher that matches on everything expect content-* 
         */
        HeaderMatcher nonContentMatcher = new NotHeaderNameMatcher(contentMatcher);

        /* 
         * copy all non-content headers from source message to the new message 
         */
        HeaderUtils.copyHeaders(sourceMessage, newMessage, nonContentMatcher);

        newMessage.saveChanges();

        mail.setMessage(newMessage);
    } catch (MessagingException e) {
        getLogger().error("Error attaching the message.", e);
    } catch (IOException e) {
        getLogger().error("Error attaching the message.", e);
    }
}

From source file:edu.wisc.bnsemail.dao.SmtpBusinessEmailUpdateNotifier.java

@Override
public void notifyEmailUpdated(String oldAddress, String newAddress) {
    try {/*from w w w  .  ja  va 2 s. co  m*/
        //Create the message body
        final MimeBodyPart msg = new MimeBodyPart();
        msg.setContent(
                "Your Business Email Address has changed\n" + "\n" + "Old Email Address: " + oldAddress + "\n"
                        + "New Email Address: " + newAddress + "\n" + "\n"
                        + "If you have any questions, please contact your Human Resources department.",
                "text/plain");

        final MimeMessage message = this.javaMailSender.createMimeMessage();
        final Address[] recipients;
        if (StringUtils.isNotEmpty(oldAddress)) {
            recipients = new Address[] { new InternetAddress(oldAddress), new InternetAddress(newAddress) };
        } else {
            recipients = new Address[] { new InternetAddress(newAddress) };
        }
        message.setRecipients(RecipientType.TO, recipients);
        message.setFrom(new InternetAddress("payroll@ohr.wisc.edu"));
        message.setSubject("Business Email Address Change");

        // sign the message body
        if (this.smimeSignedGenerator != null) {
            final MimeMultipart mm = this.smimeSignedGenerator.generate(msg, "BC");
            message.setContent(mm, mm.getContentType());
        }
        // no signing keystore configured, send the message unsigned
        else {
            message.setContent(msg.getContent(), msg.getContentType());
        }

        message.saveChanges();

        this.javaMailSender.send(message);

        this.logger.info("Sent notification of email address change from {} to {}", oldAddress, newAddress);
    } catch (Exception e) {
        this.logger.error(
                "Failed to send notification email for change from " + oldAddress + " to " + newAddress, e);
    }
}

From source file:com.duroty.service.Mailet.java

/**
 * DOCUMENT ME!//from w  w  w .  j ava  2  s. c o  m
 *
 * @param id DOCUMENT ME!
 * @param message DOCUMENT ME!
 */
private void saveInReplyTo(String id, MimeMessage message) {
    try {
        String[] inReplyTos = message.getHeader(RFC2822Headers.IN_REPLY_TO);

        String messageId = message.getMessageID();

        if ((inReplyTos == null) || (inReplyTos.length <= 0)) {
            if (messageId != null) {
                message.addHeader(RFC2822Headers.IN_REPLY_TO, messageId);
                message.saveChanges();
            }
        }

        String[] references = message.getHeader(RFC2822Headers.REFERENCES);

        if ((references == null) || (references.length <= 0)) {
            message.addHeader(RFC2822Headers.REFERENCES, messageId);
            message.saveChanges();
        }
    } catch (Exception e) {
    }
}

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

@Test
public void testInvalidOriginator() throws Exception {
    MockMailetConfig mailetConfig = new MockMailetConfig("test");

    SendMailEventListenerImpl listener = new SendMailEventListenerImpl();

    mailetConfig.getMailetContext().setSendMailEventListener(listener);

    Notify mailet = new Notify();

    mailetConfig.setInitParameter("template", "encryption-notification.ftl");
    mailetConfig.setInitParameter("recipients", "originator");
    mailetConfig.setInitParameter("processor", "testProcessor");
    mailetConfig.setInitParameter("passThrough", "false");

    mailet.init(mailetConfig);// w  w w .  j av a2s.  co  m

    MockMail mail = new MockMail();

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

    message.setContent("test\n", "text/plain");
    message.setHeader("From", "!@#$%^&*(");

    message.saveChanges();

    mail.setMessage(message);

    Set<MailAddress> recipients = new HashSet<MailAddress>();

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

    mail.setRecipients(recipients);

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

    mailet.service(mail);

    MailUtils.validateMessage(mail.getMessage());

    assertEquals(0, listener.getSenders().size());
    assertEquals(0, listener.getRecipients().size());
    assertEquals(0, listener.getStates().size());
    assertEquals(0, listener.getMessages().size());
    assertEquals(0, listener.getMails().size());

    assertNull(mail.getState());
}

From source file:eu.scape_project.pw.idp.UserManager.java

/**
 * Sends the user a link to reset the password.
 * /*from   w w w.  ja  v a2  s .c  om*/
 * @param user
 *            the user
 * @param serverString
 *            host and port of the server
 * @throws CannotSendMailException
 *             if the password reset mail could not be sent
 */
public void sendPasswordResetMail(IdpUser user, String serverString) throws CannotSendMailException {
    try {
        Properties props = System.getProperties();

        props.put("mail.smtp.host", config.getString("mail.smtp.host"));
        Session session = Session.getDefaultInstance(props, null);

        MimeMessage message = new MimeMessage(session);
        message.setFrom(new InternetAddress(config.getString("mail.from")));
        message.setRecipient(RecipientType.TO, new InternetAddress(user.getEmail()));
        message.setSubject("Planningsuite password recovery");

        StringBuilder builder = new StringBuilder();
        builder.append("Dear " + user.getFirstName() + " " + user.getLastName() + ", \n\n");
        builder.append("You have requested help recovering the password for the Plato user ");
        builder.append(user.getUsername()).append(".\n\n");
        builder.append("Please use the following link to reset your Planningsuite password: \n");
        builder.append("http://" + serverString + "/idp/resetPassword.jsf?uid=" + user.getActionToken());
        builder.append("\n\n--\n");
        builder.append("Your Planningsuite team");

        message.setText(builder.toString());
        message.saveChanges();

        Transport.send(message);
        log.debug("Sent password reset mail to " + user.getEmail());

    } catch (Exception e) {
        log.error("Error at sending password reset mail to {}", user.getEmail());
        throw new CannotSendMailException("Error at sending password reset mail to " + user.getEmail());
    }
}

From source file:de.mendelson.comm.as2.message.AS2MessageParser.java

/**Verifies the signature of the passed signed part*/
public MimeBodyPart verifySignedPart(Part signedPart, byte[] data, String contentType,
        X509Certificate certificate) throws Exception {
    BCCryptoHelper helper = new BCCryptoHelper();
    String signatureTransferEncoding = null;
    MimeMultipart checkPart = (MimeMultipart) signedPart.getContent();
    //it is sure that it is a signed part: set the type to multipart if the
    //parser has problems parsing it. Don't know why sometimes a parsing fails for
    //MimeBodyPart. This check looks if the parser is able to find more than one subpart
    if (checkPart.getCount() == 1) {
        MimeMultipart multipart = new MimeMultipart(new ByteArrayDataSource(data, contentType));
        MimeMessage possibleSignedMessage = new MimeMessage(Session.getInstance(System.getProperties(), null));
        possibleSignedMessage.setContent(multipart, multipart.getContentType());
        possibleSignedMessage.saveChanges();
        //overwrite the formerly found signed part
        signedPart = helper.getSignedEmbeddedPart(possibleSignedMessage);
    }//from w  w w. jav  a  2s . c  om
    //get the content encoding of the signature
    MimeMultipart signedMultiPart = (MimeMultipart) signedPart.getContent();
    //body part 1 is always the signature
    String encodingHeader[] = signedMultiPart.getBodyPart(1).getHeader("Content-Transfer-Encoding");
    if (encodingHeader != null) {
        signatureTransferEncoding = encodingHeader[0];
    }
    return (helper.verify(signedPart, signatureTransferEncoding, certificate));
}

From source file:com.duroty.utils.mail.MessageUtilities.java

/**
 * DOCUMENT ME!//from w w  w.jav a  2s .co  m
 *
 * @param message DOCUMENT ME!
 *
 * @throws javax.mail.MessagingException DOCUMENT ME!
 */
public static void clearAllHeaders(MimeMessage message) throws javax.mail.MessagingException {
    Enumeration headers = message.getAllHeaders();

    while (headers.hasMoreElements()) {
        Header header = (Header) headers.nextElement();

        try {
            message.removeHeader(header.getName());
        } catch (javax.mail.MessagingException me) {
        }
    }

    message.saveChanges();
}