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:eu.scape_project.planning.application.Feedback.java

/**
 * Method responsible for sending feedback per mail.
 * /*from   w w w . ja  v  a 2  s.  c  o  m*/
 * @param userEmail
 *            email address of the user.
 * @param userComments
 *            comments from the user
 * @param location
 *            the location of the application where the error occurred
 * @param applicationName
 *            the name of the application
 * @throws MailException
 *             if the feedback could not be sent
 */
public void sendFeedback(String userEmail, String userComments, String location, String applicationName)
        throws MailException {

    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(config.getString("mail.feedback")));

        message.setSubject("[" + applicationName + "] from " + location);

        StringBuilder builder = new StringBuilder();
        builder.append("Date: ").append(dateFormat.format(new Date())).append("\n\n");

        // User info
        if (user == null) {
            builder.append("No user available.\n\n");
        } else {
            builder.append("User: ").append(user.getUsername()).append("\n");
            if (user.getUserGroup() != null) {
                builder.append("Group: ").append(user.getUserGroup().getName()).append("\n");
            }
        }
        builder.append("UserMail: ").append(userEmail).append("\n\n");

        // Comments
        builder.append("Comments:\n");
        builder.append(SEPARATOR_LINE);
        builder.append(userComments).append("\n");
        builder.append(SEPARATOR_LINE).append("\n");
        message.setText(builder.toString());
        message.saveChanges();

        Transport.send(message);

        log.debug("Feedback mail sent successfully to {}", config.getString("mail.feedback"));
    } catch (MessagingException e) {
        log.error("Error sending feedback mail to {}", config.getString("mail.feedback"), e);
        throw new MailException("Error sending feedback mail to " + config.getString("mail.feedback"), e);
    }
}

From source file:com.blackducksoftware.tools.commonframework.standard.email.CFEmailNotifier.java

/**
 * This is the actual java mail execution.
 *
 * @param notification/*from  w w  w  .  j  a v  a 2s .  c o  m*/
 */
private void send(EmailTemplate notification) {

    String from = notification.getFrom();
    String to = notification.getTo();
    String subject = notification.getSubject();
    String style = notification.getStyle();

    // body of the email is set and all substitutions of variables are made
    String body = notification.getBody();

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

    // Setup mail server

    props.put("mail.smtp.host", smtpHost);
    props.put("mail.smtps.port", smtpPort);
    props.put("mail.smtps.auth", smtpUseAuth ? "true" : "false");

    // if (smtpUseAuth) {
    //
    // props.setProperty("mail.smtp.auth", smtpUseAuth + "");
    // props.setProperty("mail.username", smtpUsername);
    // props.setProperty("mail.password", smtpPassword);
    //
    // }

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

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

    try {
        // Set the RFC 822 "From" header field using the
        // value of the InternetAddress.getLocalAddress method.
        message.setFrom(new InternetAddress(from));
        // Add the given addresses to the specified recipient type.
        message.addRecipients(Message.RecipientType.TO, InternetAddress.parse(to));

        // Set the "Subject" header field.
        message.setSubject(subject);

        // Sets the given String as this part's content,
        // with a MIME type of "text/html".
        message.setContent(style + body, "text/html");

        if (smtpUseAuth) {
            // Send message
            Transport tr = session.getTransport(smtpProtocol);
            tr.connect(smtpHost, smtpPort, smtpUsername, smtpPassword);

            message.saveChanges();
            tr.sendMessage(message, message.getAllRecipients());
            tr.close();
        } else {
            Transport.send(message);
        }
    } catch (AddressException e) {
        log.error("Email Exception: Cannot connect to email host: " + smtpHost, e);
    } catch (MessagingException e) {
        log.error("Email Exception: Cannot send email message", e);
    }

}

From source file:com.meltmedia.cadmium.email.TestingMessageTransformer.java

public MimeMessage transform(MimeMessage message) throws MessagingException {
    MimeBodyPart sentToBodyPart = newSentToBodyPart(message);
    MimeBodyPart originalBodyPart = newOriginalBodyPart(message);

    // create a new multipart content for this message.
    MimeMultipart multipart = new MimeMultipart(EmailUtil.SUBTYPE_MIXED);

    // add the parts to the body.
    multipart.addBodyPart(originalBodyPart);
    multipart.addBodyPart(sentToBodyPart);

    // get the new values for all of the headers.
    InternetAddress newFromAddress = newFromAddress(message);
    InternetAddress[] newToAddresses = newToAddresses(message);
    InternetAddress[] newCcAddresses = newCcAddresses(message);
    InternetAddress[] newBccAddresses = newBccAddresses(message);
    String newSubject = newSubject(message);

    // update the message.
    message.setFrom(newFromAddress);// ww  w  . j  a  va2s . c  o m
    message.setRecipients(Message.RecipientType.TO, newToAddresses);
    message.setRecipients(Message.RecipientType.CC, newCcAddresses);
    message.setRecipients(Message.RecipientType.BCC, newBccAddresses);
    message.setSubject(newSubject);
    message.setContent(multipart);

    // save the message.
    message.saveChanges();

    if (getLogProperty()) {
        try {
            ByteArrayOutputStream out = new ByteArrayOutputStream();
            message.writeTo(out);
            log.info("Email Message Sent:\n{}", out.toString());
        } catch (IOException ioe) {
            throw new MessagingException("Exception thrown while writing message to log.", ioe);
        }
    }
    if (!getSendProperty()) {
        message = null;
    }

    // return the message.
    return message;
}

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

/**Enwrapps the data into a signed MIME message structure and returns it*/
private void enwrappInMessageAndSign(AS2Message message, Part contentPart, Partner sender, Partner receiver)
        throws Exception {
    AS2MessageInfo info = (AS2MessageInfo) message.getAS2Info();
    MimeMessage messagePart = new MimeMessage(Session.getInstance(System.getProperties(), null));
    //sign message if this is requested
    if (info.getSignType() != AS2Message.SIGNATURE_NONE) {
        MimeMultipart signedPart = this.signContentPart(contentPart, sender, receiver);
        if (this.logger != null) {
            String signAlias = this.signatureCertManager.getAliasByFingerprint(sender.getSignFingerprintSHA1());
            this.logger.log(Level.INFO,
                    this.rb.getResourceString("message.signed",
                            new Object[] { info.getMessageId(), signAlias,
                                    this.rbMessage.getResourceString("signature." + receiver.getSignType()) }),
                    info);/*from  w  w w . j a  v  a  2 s.c  o  m*/
        }
        messagePart.setContent(signedPart);
        messagePart.saveChanges();
    } else {
        //unsigned message
        if (contentPart instanceof MimeBodyPart) {
            MimeMultipart unsignedPart = new MimeMultipart();
            unsignedPart.addBodyPart((MimeBodyPart) contentPart);
            if (this.logger != null) {
                this.logger.log(Level.INFO,
                        this.rb.getResourceString("message.notsigned", new Object[] { info.getMessageId() }),
                        info);
            }
            messagePart.setContent(unsignedPart);
        } else if (contentPart instanceof MimeMultipart) {
            messagePart.setContent((MimeMultipart) contentPart);
        } else if (contentPart instanceof MimeMessage) {
            messagePart = (MimeMessage) contentPart;
        } else {
            throw new IllegalArgumentException("enwrappInMessageAndSign: Unable to set the content of a "
                    + contentPart.getClass().getName());
        }
        messagePart.saveChanges();
    }
    //store signed or unsigned data
    ByteArrayOutputStream signedOut = new ByteArrayOutputStream();
    //normally the content type header is folded (which is correct but some products are not able to parse this properly)
    //Now take the content-type, unfold it and write it
    Enumeration headerLines = messagePart.getMatchingHeaderLines(new String[] { "Content-Type" });
    LineOutputStream los = new LineOutputStream(signedOut);
    while (headerLines.hasMoreElements()) {
        //requires java mail API >= 1.4
        String nextHeaderLine = MimeUtility.unfold((String) headerLines.nextElement());
        //write the line only if the as2 message is encrypted. If the as2 message is unencrypted this header is added later
        //in the class MessageHttpUploader
        if (info.getEncryptionType() != AS2Message.ENCRYPTION_NONE) {
            los.writeln(nextHeaderLine);
        }
        //store the content line in the as2 message object, this value is required later in MessageHttpUploader
        message.setContentType(nextHeaderLine.substring(nextHeaderLine.indexOf(':') + 1));
    }
    messagePart.writeTo(signedOut, new String[] { "Message-ID", "Mime-Version", "Content-Type" });
    signedOut.flush();
    signedOut.close();
    message.setDecryptedRawData(signedOut.toByteArray());
}

From source file:eu.scape_project.planning.user.Groups.java

/**
 * Sends an invitation mail to the user.
 * //from   w  ww  .j av a2s  .  c om
 * @param toUser
 *            the recipient of the mail
 * @param serverString
 *            the server string
 * @return true if the mail was sent successfully, false otherwise
 * @throws InvitationMailException
 *             if the invitation mail could not be send
 */
private void sendInvitationMail(User toUser, GroupInvitation invitation, String serverString)
        throws InvitationMailException {
    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(invitation.getEmail()));
        message.setSubject(
                user.getFullName() + " invited you to join the Plato group " + user.getUserGroup().getName());

        StringBuilder builder = new StringBuilder();
        builder.append("Dear " + toUser.getFullName() + ", \n\n");
        builder.append("The Plato user " + user.getFullName() + " has invited you to join the group "
                + user.getUserGroup().getName() + ".\n");
        builder.append("Please log in and use the following link to accept the invitation: \n");
        builder.append("http://" + serverString + "/plato/user/groupInvitation.jsf?uid="
                + invitation.getInvitationActionToken());
        builder.append("\n\n--\n");
        builder.append("Your Planningsuite team");

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

        Transport.send(message);
        log.debug("Group invitation mail sent successfully to " + invitation.getEmail());

    } catch (Exception e) {
        log.error("Error sending group invitation mail to " + invitation.getEmail(), e);
        throw new InvitationMailException(e);
    }
}

From source file:be.fedict.eid.pkira.blm.model.mail.MailHandlerBean.java

@Override
@TransactionAttribute(TransactionAttributeType.REQUIRED)
public void onMessage(Message arg0) {
    ObjectMessage objectMessage = (ObjectMessage) arg0;
    try {//from   w  w w.j av  a 2s.  co m
        Mail mail = (Mail) objectMessage.getObject();

        // Get properties
        String mailProtocol = getMailProtocol();
        String mailServer = getSmtpServer();
        String mailUser = getSmtpUser();
        String mailPort = getSmtpPort();
        String mailPassword = getSmtpPassword();

        // Initialize a mail session
        Properties props = new Properties();
        props.put("mail." + mailProtocol + ".host", mailServer);
        props.put("mail." + mailProtocol + ".port", mailPort);
        Session session = Session.getInstance(props);

        // Create the message
        MimeMessage msg = new MimeMessage(session);
        msg.setFrom(new InternetAddress(mail.getSender()));
        for (String recipient : mail.getRecipients()) {
            msg.addRecipient(RecipientType.TO, new InternetAddress(recipient));
        }
        msg.setSubject(mail.getSubject(), "UTF-8");

        Multipart multipart = new MimeMultipart();
        msg.setContent(multipart);

        // Set the email message text and attachment
        MimeBodyPart messagePart = new MimeBodyPart();
        messagePart.setContent(mail.getBody(), mail.getContentType());
        multipart.addBodyPart(messagePart);

        if (mail.getAttachmentData() != null) {
            ByteArrayDataSource byteArrayDataSource = new ByteArrayDataSource(mail.getAttachmentData(),
                    mail.getAttachmentContentType());
            DataHandler dataHandler = new DataHandler(byteArrayDataSource);
            MimeBodyPart attachmentPart = new MimeBodyPart();
            attachmentPart.setDataHandler(dataHandler);
            attachmentPart.setFileName(mail.getAttachmentFileName());

            multipart.addBodyPart(attachmentPart);
        }

        // Open transport and send message
        Transport transport = session.getTransport(mailProtocol);
        if (StringUtils.isNotBlank(mailUser)) {
            transport.connect(mailUser, mailPassword);
        } else {
            transport.connect();
        }
        msg.saveChanges();
        transport.sendMessage(msg, msg.getAllRecipients());
    } catch (JMSException e) {
        errorLogger.logError(ApplicationComponent.MAIL, "Cannot handle the object message from the queue", e);
        throw new RuntimeException(e);
    } catch (MessagingException e) {
        errorLogger.logError(ApplicationComponent.MAIL, "Cannot send a mail message", e);
        throw new RuntimeException(e);
    }
}

From source file:eu.planets_project.pp.plato.action.session.ExceptionAction.java

@RaiseEvent("exceptionHandled")
public String sendMail() {
    try {//w w  w.  ja v  a 2 s.co m
        log.debug(body);
        Properties props = System.getProperties();
        Properties mailProps = new Properties();
        mailProps.load(ExceptionAction.class.getResourceAsStream("/mail.properties"));
        props.put("mail.smtp.host", mailProps.getProperty("SMTPSERVER"));
        Session session = Session.getDefaultInstance(props, null);
        MimeMessage message = new MimeMessage(session);
        message.setFrom(new InternetAddress(mailProps.getProperty("FROM")));
        message.setRecipient(RecipientType.TO, new InternetAddress(mailProps.getProperty("TO")));
        String exceptionType = "Unknown";
        String exceptionMessage = "";
        String stackTrace = "";

        String host = ((HttpServletRequest) facesContext.getExternalContext().getRequest()).getLocalName();

        if (lastHandledException != null) {
            exceptionType = lastHandledException.getClass().getCanonicalName();
            exceptionMessage = lastHandledException.getMessage();
            StringWriter writer = new StringWriter();
            lastHandledException.printStackTrace(new PrintWriter(writer));
            stackTrace = writer.toString();
        }

        message.setSubject("[PlatoError] " + exceptionType + " at " + host);
        StringBuilder builder = new StringBuilder();
        builder.append("Date: " + format.format(new Date()) + "\n");
        builder.append("User: " + ((user == null) ? "Unknown" : user.getUsername()) + "\n");
        builder.append("ExceptionType: " + exceptionType + "\n");
        builder.append("ExceptionMessage: " + exceptionMessage + "\n\n");

        builder.append("UserMail:" + separatorLine + this.userEmail + separatorLine + "\n");
        builder.append("User Description:" + separatorLine + this.body + separatorLine + "\n");
        builder.append(stackTrace);
        message.setText(builder.toString());
        message.saveChanges();
        Transport.send(message);
        this.lastHandledException = null;
        facesContext.addMessage(null, new FacesMessage(FacesMessage.SEVERITY_INFO, "Bugreport sent.",
                "Thank you for your feedback. We will try to analyse and resolve the issue as soon as possible."));
    } catch (Exception e) {
        log.debug(e.getMessage(), e);
        facesContext.addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR,
                "Bugreport couldn't be sent",
                "Because of an enternal error your bug report couldn't be sent. We apologise for this and hope you are willing to inform us about this so we can fix the problem. "
                        + "Please send an email to plato@ifs.tuwien.ac.at with a "
                        + "description of what you have been doing at the time of the error."
                        + "Thank you very much!"));
        return null;
    }
    return "home";
}

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

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

    SendMailEventListenerImpl listener = new SendMailEventListenerImpl();

    mailetConfig.getMailetContext().setSendMailEventListener(listener);

    Mailet mailet = new PDFEncrypt();

    String template = FileUtils.readFileToString(new File("test/resources/templates/pdf-attachment.ftl"));

    autoTransactDelegator.setGlobalProperty("pdfTemplate", template);
    autoTransactDelegator.setGlobalProperty("user.serverSecret", "123", true /* encrypt */);
    autoTransactDelegator.setGlobalProperty("user.pdf.replyAllowed", "true");
    autoTransactDelegator.setGlobalProperty("user.pdf.replyURL", "http://127.0.0.1");

    autoTransactDelegator.setProperty("m.brinkers@pobox.com", "user.pdf.replyAllowed", "true");

    mailetConfig.setInitParameter("log", "starting");
    mailetConfig.setInitParameter("template", "encrypted-pdf.ftl");
    mailetConfig.setInitParameter("templateProperty", "pdfTemplate");
    mailetConfig.setInitParameter("encryptedProcessor", "encryptedProcessor");
    mailetConfig.setInitParameter("notEncryptedProcessor", "notEncryptedProcessor");
    mailetConfig.setInitParameter("passwordMode", "multiple");

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

    MockMail mail = new MockMail();

    mail.setState(Mail.DEFAULT);

    Passwords passwords = new Passwords();

    PasswordContainer container = new PasswordContainer("test", "test ID");

    passwords.put("m.brinkers@pobox.com", container);

    new DjigzoMailAttributesImpl(mail).setPasswords(passwords);

    MimeMessage message = MailUtils.loadMessage(new File(testBase, "mail/normal-message-with-attach.eml"));

    message.setFrom(new InternetAddress("&*^&*^&*", false));

    message.saveChanges();

    mail.setMessage(message);

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

    recipients.add(new MailAddress("m.bRINKERs@pobox.com"));

    mail.setRecipients(recipients);

    mail.setSender(null);

    mailet.service(mail);

    MailUtils.validateMessage(mail.getMessage());

    TestUtils.saveMessages(tempDir, "testUserTemplateEncryptPDF", listener.getMessages());

    assertEquals(1, listener.getMessages().size());
    assertEquals("encryptedProcessor", listener.getStates().get(0));
    assertEquals(1, listener.getRecipients().get(0).size());
    assertTrue(listener.getRecipients().get(0).contains(new MailAddress("m.bRINKERs@pobox.com")));
    assertNull(listener.getSenders().get(0));
    assertEquals(Mail.DEFAULT, mail.getState());

    message = listener.getMessages().get(0);

    assertNotNull(message);

    MailUtils.validateMessage(message);

    checkEncryption(message, "test", false);
}

From source file:com.xpn.xwiki.plugin.mailsender.MailSenderPlugin.java

/**
 * Creates a MIME message (message with binary content carrying capabilities) from an existing Mail
 * //  w  ww  .  java  2  s.  co  m
 * @param mail The original Mail object
 * @param session Mail session
 * @return The MIME message
 */
private MimeMessage createMimeMessage(Mail mail, Session session, XWikiContext context)
        throws MessagingException, XWikiException, IOException {
    // this will also check for email error
    InternetAddress from = new InternetAddress(mail.getFrom());
    String recipients = mail.getHeader("To");
    if (StringUtils.isBlank(recipients)) {
        recipients = mail.getTo();
    } else {
        recipients = mail.getTo() + "," + recipients;
    }
    InternetAddress[] to = toInternetAddresses(recipients);
    recipients = mail.getHeader("Cc");
    if (StringUtils.isBlank(recipients)) {
        recipients = mail.getCc();
    } else {
        recipients = mail.getCc() + "," + recipients;
    }
    InternetAddress[] cc = toInternetAddresses(recipients);
    recipients = mail.getHeader("Bcc");
    if (StringUtils.isBlank(recipients)) {
        recipients = mail.getBcc();
    } else {
        recipients = mail.getBcc() + "," + recipients;
    }
    InternetAddress[] bcc = toInternetAddresses(recipients);

    if ((to == null) && (cc == null) && (bcc == null)) {
        LOGGER.info("No recipient -> skipping this email");
        return null;
    }

    MimeMessage message = new MimeMessage(session);
    message.setSentDate(new Date());
    message.setFrom(from);

    if (to != null) {
        message.setRecipients(javax.mail.Message.RecipientType.TO, to);
    }

    if (cc != null) {
        message.setRecipients(javax.mail.Message.RecipientType.CC, cc);
    }

    if (bcc != null) {
        message.setRecipients(javax.mail.Message.RecipientType.BCC, bcc);
    }

    message.setSubject(mail.getSubject(), EMAIL_ENCODING);

    for (Map.Entry<String, String> header : mail.getHeaders().entrySet()) {
        message.setHeader(header.getKey(), header.getValue());
    }

    if (mail.getHtmlPart() != null || mail.getAttachments() != null) {
        Multipart multipart = createMimeMultipart(mail, context);
        message.setContent(multipart);
    } else {
        message.setText(mail.getTextPart());
    }

    message.setSentDate(new Date());
    message.saveChanges();
    return message;
}

From source file:eu.scape_project.planning.user.Groups.java

/**
 * Sends an invitation mail to the user.
 * //from   w ww.  j a v  a2s. c o m
 * @param toUser
 *            the recipient of the mail
 * @param serverString
 *            the server string
 * @return true if the mail was sent successfully, false otherwise
 * @throws InvitationMailException
 *             if the invitation mail could not be send
 */
private void sendInvitationMail(GroupInvitation invitation, String serverString)
        throws InvitationMailException {
    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(invitation.getEmail()));
        message.setSubject(
                user.getFullName() + " invited you to join the Plato group " + user.getUserGroup().getName());

        StringBuilder builder = new StringBuilder();
        builder.append("Hello, \n\n");
        builder.append("The Plato user " + user.getFullName() + " has invited you to join the group "
                + user.getUserGroup().getName() + ".\n\n");
        builder.append(
                "You do not seem to be a Plato user. If you would like to accept the invitation, please first create an account at http://"
                        + serverString + "/idp/addUser.jsf.\n");
        builder.append(
                "If you have an account, please log in and use the following link to accept the invitation: \n");
        builder.append("http://" + serverString + "/plato/user/groupInvitation.jsf?uid="
                + invitation.getInvitationActionToken());
        builder.append("\n\n--\n");
        builder.append("Your Planningsuite team");

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

        Transport.send(message);
        log.debug("Group invitation mail sent successfully to " + invitation.getEmail());

    } catch (MessagingException e) {
        log.error("Error sending group invitation mail to " + invitation.getEmail(), e);
        throw new InvitationMailException(e);
    }
}