Example usage for javax.mail.internet MimeMessage setContent

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

Introduction

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

Prototype

@Override
public void setContent(Object o, String type) throws MessagingException 

Source Link

Document

A convenience method for setting this Message's content.

Usage

From source file:org.pentaho.platform.plugin.action.builtin.EmailComponent.java

@Override
public boolean executeAction() {
    EmailAction emailAction = (EmailAction) getActionDefinition();

    String messagePlain = emailAction.getMessagePlain().getStringValue();
    String messageHtml = emailAction.getMessageHtml().getStringValue();
    String subject = emailAction.getSubject().getStringValue();
    String to = emailAction.getTo().getStringValue();
    String cc = emailAction.getCc().getStringValue();
    String bcc = emailAction.getBcc().getStringValue();
    String from = emailAction.getFrom().getStringValue(defaultFrom);
    if (from.trim().length() == 0) {
        from = defaultFrom;//from  w  w w.  j a  va2  s  .  co  m
    }

    /*
     * if( context.getInputNames().contains( "attach" ) ) { //$NON-NLS-1$ Object attachParameter =
     * context.getInputParameter( "attach" ).getValue(); //$NON-NLS-1$ // We have a list of attachments, each element of
     * the list is the name of the parameter containing the attachment // Use the parameter filename portion as the
     * attachment name. if ( attachParameter instanceof String ) { String attachName = context.getInputParameter(
     * "attach-name" ).getStringValue(); //$NON-NLS-1$ AttachStruct attachData = getAttachData( context,
     * (String)attachParameter, attachName ); if ( attachData != null ) { attachments.add( attachData ); } } else if (
     * attachParameter instanceof List ) { for ( int i = 0; i < ((List)attachParameter).size(); ++i ) { AttachStruct
     * attachData = getAttachData( context, ((List)attachParameter).get( i ).toString(), null ); if ( attachData != null
     * ) { attachments.add( attachData ); } } } else if ( attachParameter instanceof Map ) { for ( Iterator it =
     * ((Map)attachParameter).entrySet().iterator(); it.hasNext(); ) { Map.Entry entry = (Map.Entry)it.next();
     * AttachStruct attachData = getAttachData( context, (String)entry.getValue(), (String)entry.getKey() ); if (
     * attachData != null ) { attachments.add( attachData ); } } } }
     * 
     * int maxSize = Integer.MAX_VALUE; try { maxSize = new Integer( props.getProperty( "mail.max.attach.size" )
     * ).intValue(); } catch( Throwable t ) { //ignore if not set to a valid value }
     * 
     * if ( totalAttachLength > maxSize ) { // Sort them in order TreeMap tm = new TreeMap(); for( int idx=0;
     * idx<attachments.size(); idx++ ) { // tm.put( new Integer( )) } }
     */

    if (ComponentBase.debug) {
        debug(Messages.getInstance().getString("Email.DEBUG_TO_FROM", to, from)); //$NON-NLS-1$
        debug(Messages.getInstance().getString("Email.DEBUG_CC_BCC", cc, bcc)); //$NON-NLS-1$
        debug(Messages.getInstance().getString("Email.DEBUG_SUBJECT", subject)); //$NON-NLS-1$
        debug(Messages.getInstance().getString("Email.DEBUG_PLAIN_MESSAGE", messagePlain)); //$NON-NLS-1$
        debug(Messages.getInstance().getString("Email.DEBUG_HTML_MESSAGE", messageHtml)); //$NON-NLS-1$
    }

    if ((to == null) || (to.trim().length() == 0)) {

        // Get the output stream that the feedback is going into
        OutputStream feedbackStream = getFeedbackOutputStream();
        if (feedbackStream != null) {
            createFeedbackParameter("to", Messages.getInstance().getString("Email.USER_ENTER_EMAIL_ADDRESS"), //$NON-NLS-1$//$NON-NLS-2$
                    "", "", true); //$NON-NLS-1$ //$NON-NLS-2$
            setFeedbackMimeType("text/html"); //$NON-NLS-1$
            return true;
        } else {
            return false;
        }
    }
    if (subject == null) {
        error(Messages.getInstance().getErrorString("Email.ERROR_0005_NULL_SUBJECT", getActionName())); //$NON-NLS-1$
        return false;
    }
    if ((messagePlain == null) && (messageHtml == null)) {
        error(Messages.getInstance().getErrorString("Email.ERROR_0006_NULL_BODY", getActionName())); //$NON-NLS-1$
        return false;
    }

    if (getRuntimeContext().isPromptPending()) {
        return true;
    }

    try {
        Properties props = new Properties();
        final IEmailService service = PentahoSystem.get(IEmailService.class, "IEmailService",
                PentahoSessionHolder.getSession());
        props.put("mail.smtp.host", service.getEmailConfig().getSmtpHost());
        props.put("mail.smtp.port", ObjectUtils.toString(service.getEmailConfig().getSmtpPort()));
        props.put("mail.transport.protocol", service.getEmailConfig().getSmtpProtocol());
        props.put("mail.smtp.starttls.enable", ObjectUtils.toString(service.getEmailConfig().isUseStartTls()));
        props.put("mail.smtp.auth", ObjectUtils.toString(service.getEmailConfig().isAuthenticate()));
        props.put("mail.smtp.ssl", ObjectUtils.toString(service.getEmailConfig().isUseSsl()));
        props.put("mail.smtp.quitwait", ObjectUtils.toString(service.getEmailConfig().isSmtpQuitWait()));
        props.put("mail.from.default", service.getEmailConfig().getDefaultFrom());
        String fromName = service.getEmailConfig().getFromName();
        if (StringUtils.isEmpty(fromName)) {
            fromName = Messages.getInstance().getString("schedulerEmailFromName");
        }
        props.put("mail.from.name", fromName);
        props.put("mail.debug", ObjectUtils.toString(service.getEmailConfig().isDebug()));

        Session session;
        if (service.getEmailConfig().isAuthenticate()) {
            props.put("mail.userid", service.getEmailConfig().getUserId());
            props.put("mail.password", service.getEmailConfig().getPassword());
            Authenticator authenticator = new EmailAuthenticator();
            session = Session.getInstance(props, authenticator);
        } else {
            session = Session.getInstance(props);
        }

        // debugging is on if either component (xaction) or email config debug is on
        if (service.getEmailConfig().isDebug() || ComponentBase.debug) {
            session.setDebug(true);
        }

        // construct the message
        MimeMessage msg = new MimeMessage(session);
        if (from != null) {
            msg.setFrom(new InternetAddress(from));
        } else {
            // There should be no way to get here
            error(Messages.getInstance().getString("Email.ERROR_0012_FROM_NOT_DEFINED")); //$NON-NLS-1$
        }

        if ((to != null) && (to.trim().length() > 0)) {
            msg.setRecipients(Message.RecipientType.TO, InternetAddress.parse(to, false));
        }
        if ((cc != null) && (cc.trim().length() > 0)) {
            msg.setRecipients(Message.RecipientType.CC, InternetAddress.parse(cc, false));
        }
        if ((bcc != null) && (bcc.trim().length() > 0)) {
            msg.setRecipients(Message.RecipientType.BCC, InternetAddress.parse(bcc, false));
        }

        if (subject != null) {
            msg.setSubject(subject, LocaleHelper.getSystemEncoding());
        }

        EmailAttachment[] emailAttachments = emailAction.getAttachments();
        if ((messagePlain != null) && (messageHtml == null) && (emailAttachments.length == 0)) {
            msg.setText(messagePlain, LocaleHelper.getSystemEncoding());
        } else if (emailAttachments.length == 0) {
            if (messagePlain != null) {
                msg.setContent(messagePlain, "text/plain; charset=" + LocaleHelper.getSystemEncoding()); //$NON-NLS-1$          
            }
            if (messageHtml != null) {
                msg.setContent(messageHtml, "text/html; charset=" + LocaleHelper.getSystemEncoding()); //$NON-NLS-1$
            }
        } else {
            // need to create a multi-part message...
            // create the Multipart and add its parts to it
            Multipart multipart = new MimeMultipart();
            // create and fill the first message part
            if (messageHtml != null) {
                // create and fill the first message part
                MimeBodyPart htmlBodyPart = new MimeBodyPart();
                htmlBodyPart.setContent(messageHtml, "text/html; charset=" + LocaleHelper.getSystemEncoding()); //$NON-NLS-1$
                multipart.addBodyPart(htmlBodyPart);
            }

            if (messagePlain != null) {
                MimeBodyPart textBodyPart = new MimeBodyPart();
                textBodyPart.setContent(messagePlain,
                        "text/plain; charset=" + LocaleHelper.getSystemEncoding()); //$NON-NLS-1$
                multipart.addBodyPart(textBodyPart);
            }

            for (EmailAttachment element : emailAttachments) {
                IPentahoStreamSource source = element.getContent();
                if (source == null) {
                    error(Messages.getInstance().getErrorString("Email.ERROR_0015_ATTACHMENT_FAILED")); //$NON-NLS-1$
                    return false;
                }
                DataSource dataSource = new ActivationHelper.PentahoStreamSourceWrapper(source);
                String attachmentName = element.getName();
                if (ComponentBase.debug) {
                    debug(Messages.getInstance().getString("Email.DEBUG_ADDING_ATTACHMENT", attachmentName)); //$NON-NLS-1$
                }

                // create the second message part
                MimeBodyPart attachmentBodyPart = new MimeBodyPart();

                // attach the file to the message
                attachmentBodyPart.setDataHandler(new DataHandler(dataSource));
                attachmentBodyPart.setFileName(attachmentName);
                if (ComponentBase.debug) {
                    debug(Messages.getInstance().getString("Email.DEBUG_ATTACHMENT_SOURCE", //$NON-NLS-1$
                            dataSource.getName()));
                }
                multipart.addBodyPart(attachmentBodyPart);
            }

            // add the Multipart to the message
            msg.setContent(multipart);
        }

        msg.setHeader("X-Mailer", EmailComponent.MAILER); //$NON-NLS-1$
        msg.setSentDate(new Date());

        Transport.send(msg);

        if (ComponentBase.debug) {
            debug(Messages.getInstance().getString("Email.DEBUG_EMAIL_SUCCESS")); //$NON-NLS-1$
        }
        return true;
        // TODO: persist the content set for a while...
    } catch (SendFailedException e) {
        error(Messages.getInstance().getErrorString("Email.ERROR_0011_SEND_FAILED", to), e); //$NON-NLS-1$
        /*
         * Exception ne; MessagingException sfe = e; while ((ne = sfe.getNextException()) != null && ne instanceof
         * MessagingException) { sfe = (MessagingException) ne;
         * error(Messages.getInstance().getErrorString("Email.ERROR_0011_SEND_FAILED", sfe.toString()), sfe);
         * //$NON-NLS-1$ }
         */

    } catch (AuthenticationFailedException e) {
        error(Messages.getInstance().getString("Email.ERROR_0014_AUTHENTICATION_FAILED", to), e); //$NON-NLS-1$
    } catch (Throwable e) {
        error(Messages.getInstance().getErrorString("Email.ERROR_0011_SEND_FAILED", to), e); //$NON-NLS-1$
    }
    return false;
}

From source file:org.opens.emailsender.EmailSender.java

/**
 *
 * @param emailFrom//from   www  .ja va 2 s .c  om
 * @param emailToSet
 * @param emailBccSet (can be null)
 * @param replyTo (can be null)
 * @param emailSubject
 * @param emailContent
 */
public void sendEmail(String emailFrom, Set<String> emailToSet, Set<String> emailBccSet, String replyTo,
        String emailSubject, String emailContent) {
    boolean debug = false;

    // Set the host smtp address
    Properties props = new Properties();
    props.put("mail.smtp.host", smtpHost);
    props.put("mail.smtp.auth", "true");
    props.put("mail.smtp.starttls.enable", "true");

    // create some properties and get the default Session
    Session session = Session.getInstance(props);
    session.setDebug(debug);
    try {
        Transport t = session.getTransport("smtp");
        t.connect(smtpHost, userName, password);

        // create a message
        MimeMessage msg = new MimeMessage(session);

        // set the from and to address
        InternetAddress addressFrom;
        try {
            // Used default from address is passed one is null or empty or
            // blank
            addressFrom = (StringUtils.isNotBlank(emailFrom)) ? new InternetAddress(emailFrom)
                    : new InternetAddress(from);
            msg.setFrom(addressFrom);
            Address[] recipients = new InternetAddress[emailToSet.size()];
            int i = 0;
            for (String emailTo : emailToSet) {
                recipients[i] = new InternetAddress(emailTo);
                i++;
            }

            msg.setRecipients(Message.RecipientType.TO, recipients);

            if (CollectionUtils.isNotEmpty(emailBccSet)) {
                Address[] bccRecipients = new InternetAddress[emailBccSet.size()];
                i = 0;
                for (String emailBcc : emailBccSet) {
                    bccRecipients[i] = new InternetAddress(emailBcc);
                    i++;
                }
                msg.setRecipients(Message.RecipientType.BCC, bccRecipients);
            }

            if (StringUtils.isNotBlank(replyTo)) {
                Address[] replyToRecipients = { new InternetAddress(replyTo) };
                msg.setReplyTo(replyToRecipients);
            }

            // Setting the Subject
            msg.setSubject(emailSubject, CHARSET_KEY);

            // Setting content and charset (warning: both declarations of
            // charset are needed)
            msg.setHeader(CONTENT_TYPE_KEY, FULL_CHARSET_KEY);
            LOGGER.error("emailContent  " + emailContent);
            msg.setContent(emailContent, FULL_CHARSET_KEY);
            try {
                LOGGER.debug("emailContent from message object " + msg.getContent().toString());
            } catch (IOException ex) {
                LOGGER.error(ex.getMessage());
            } catch (MessagingException ex) {
                LOGGER.error(ex.getMessage());
            }
            for (Address addr : msg.getAllRecipients()) {
                LOGGER.error("addr " + addr);
            }
            t.sendMessage(msg, msg.getAllRecipients());
        } catch (AddressException ex) {
            LOGGER.warn(ex.getMessage());
        }
    } catch (NoSuchProviderException e) {
        LOGGER.warn(e.getMessage());
    } catch (MessagingException e) {
        LOGGER.warn(e.getMessage());
    }
}

From source file:org.asqatasun.emailsender.EmailSender.java

/**
 *
 * @param emailFrom//from   w w w. j a va 2s . co  m
 * @param emailToSet
 * @param emailBccSet (can be null)
 * @param replyTo (can be null)
 * @param emailSubject
 * @param emailContent
 */
public void sendEmail(String emailFrom, Set<String> emailToSet, Set<String> emailBccSet, String replyTo,
        String emailSubject, String emailContent) {
    boolean debug = false;

    // Set the host smtp address
    Properties props = new Properties();
    props.put("mail.smtp.host", smtpHost);
    props.put("mail.smtp.auth", "true");
    props.put("mail.smtp.starttls.enable", "true");

    // create some properties and get the default Session
    Session session = Session.getInstance(props);
    session.setDebug(debug);
    try {
        Transport t = session.getTransport("smtp");
        t.connect(smtpHost, userName, password);

        // create a message
        MimeMessage msg = new MimeMessage(session);

        // set the from and to address
        InternetAddress addressFrom;
        try {
            // Used default from address is passed one is null or empty or
            // blank
            addressFrom = (StringUtils.isNotBlank(emailFrom)) ? new InternetAddress(emailFrom)
                    : new InternetAddress(from);
            msg.setFrom(addressFrom);
            Address[] recipients = new InternetAddress[emailToSet.size()];
            int i = 0;
            for (String emailTo : emailToSet) {
                recipients[i] = new InternetAddress(emailTo);
                i++;
            }

            msg.setRecipients(Message.RecipientType.TO, recipients);

            if (CollectionUtils.isNotEmpty(emailBccSet)) {
                Address[] bccRecipients = new InternetAddress[emailBccSet.size()];
                i = 0;
                for (String emailBcc : emailBccSet) {
                    bccRecipients[i] = new InternetAddress(emailBcc);
                    i++;
                }
                msg.setRecipients(Message.RecipientType.BCC, bccRecipients);
            }

            if (StringUtils.isNotBlank(replyTo)) {
                Address[] replyToRecipients = { new InternetAddress(replyTo) };
                msg.setReplyTo(replyToRecipients);
            }

            // Setting the Subject
            msg.setSubject(emailSubject, CHARSET_KEY);

            // Setting content and charset (warning: both declarations of
            // charset are needed)
            msg.setHeader(CONTENT_TYPE_KEY, FULL_CHARSET_KEY);
            LOGGER.debug("emailContent  " + emailContent);
            msg.setContent(emailContent, FULL_CHARSET_KEY);
            try {
                LOGGER.debug("emailContent from message object " + msg.getContent().toString());
            } catch (IOException ex) {
                LOGGER.error(ex.getMessage());
            } catch (MessagingException ex) {
                LOGGER.error(ex.getMessage());
            }
            for (Address addr : msg.getAllRecipients()) {
                LOGGER.debug("addr " + addr);
            }
            t.sendMessage(msg, msg.getAllRecipients());
        } catch (AddressException ex) {
            LOGGER.warn("AddressException " + ex.getMessage());
            LOGGER.warn("AddressException " + ex.getStackTrace());
        }
    } catch (NoSuchProviderException e) {
        LOGGER.warn("NoSuchProviderException " + e.getMessage());
        LOGGER.warn("NoSuchProviderException " + e.getStackTrace());
    } catch (MessagingException e) {
        LOGGER.warn("MessagingException " + e.getMessage());
        LOGGER.warn("MessagingException " + e.getStackTrace());
    }
}

From source file:org.overlord.sramp.governance.services.NotificationResource.java

/**
 * POST to email a notification about an artifact.
 *
 * @param environment//from w w w.  j a  v a2 s  .  c om
 * @param uuid
 * @throws SrampAtomException
 */
@POST
@Path("email/{group}/{template}/{target}/{uuid}")
@Produces("application/xml")
public Map<String, ValueEntity> emailNotification(@Context HttpServletRequest request,
        @PathParam("group") String group, @PathParam("template") String template,
        @PathParam("target") String target, @PathParam("uuid") String uuid) throws Exception {

    Map<String, ValueEntity> results = new HashMap<String, ValueEntity>();
    try {
        // 0. run the decoder on the arguments, after replacing * by % (this so parameters can
        //    contain slashes (%2F)
        group = SlashDecoder.decode(group);
        template = SlashDecoder.decode(template);
        target = SlashDecoder.decode(target);
        uuid = SlashDecoder.decode(uuid);

        // 1. get the artifact from the repo
        SrampAtomApiClient client = SrampAtomApiClientFactory.createAtomApiClient();
        QueryResultSet queryResultSet = client.buildQuery("/s-ramp[@uuid = ?]").parameter(uuid).query(); //$NON-NLS-1$
        if (queryResultSet.size() == 0) {
            results.put(GovernanceConstants.STATUS, new ValueEntity("fail")); //$NON-NLS-1$
            results.put(GovernanceConstants.MESSAGE,
                    new ValueEntity("Could not obtain artifact from repository.")); //$NON-NLS-1$
            return results;
        }
        ArtifactSummary artifactSummary = queryResultSet.iterator().next();

        // 2. get the destinations for this group
        NotificationDestinations destinations = governance.getNotificationDestinations("email").get(group); //$NON-NLS-1$
        if (destinations == null) {
            destinations = new NotificationDestinations(group, governance.getDefaultEmailFromAddress(),
                    group + "@" + governance.getDefaultEmailDomain()); //$NON-NLS-1$
        }

        // 3. send the email notification
        try {
            MimeMessage m = new MimeMessage(mailSession);
            Address from = new InternetAddress(destinations.getFromAddress());
            Address[] to = new InternetAddress[destinations.getToAddresses().length];
            for (int i = 0; i < destinations.getToAddresses().length; i++) {
                to[i] = new InternetAddress(destinations.getToAddresses()[i]);
            }
            m.setFrom(from);
            m.setRecipients(Message.RecipientType.TO, to);

            String subject = "/governance-email-templates/" + template + ".subject.tmpl"; //$NON-NLS-1$ //$NON-NLS-2$
            URL subjectUrl = Governance.class.getClassLoader().getResource(subject);
            if (subjectUrl != null)
                subject = IOUtils.toString(subjectUrl);
            subject = subject.replaceAll("\\$\\{uuid}", uuid); //$NON-NLS-1$
            subject = subject.replaceAll("\\$\\{name}", artifactSummary.getName()); //$NON-NLS-1$
            subject = subject.replaceAll("\\$\\{target}", target); //$NON-NLS-1$
            m.setSubject(subject);

            m.setSentDate(new java.util.Date());
            String content = "/governance-email-templates/" + template + ".body.tmpl"; //$NON-NLS-1$ //$NON-NLS-2$
            URL contentUrl = Governance.class.getClassLoader().getResource(content);
            if (contentUrl != null)
                content = IOUtils.toString(contentUrl);
            content = content.replaceAll("\\$\\{uuid}", uuid); //$NON-NLS-1$
            content = content.replaceAll("\\$\\{name}", artifactSummary.getName()); //$NON-NLS-1$
            content = content.replaceAll("\\$\\{target}", target); //$NON-NLS-1$
            content = content.replaceAll("\\$\\{dtgovurl}", governance.getDTGovUiUrl()); //$NON-NLS-1$
            m.setContent(content, "text/plain"); //$NON-NLS-1$
            Transport.send(m);
        } catch (javax.mail.MessagingException e) {
            logger.error(e.getMessage(), e);
        }

        // 4. build the response
        results.put(GovernanceConstants.STATUS, new ValueEntity("success")); //$NON-NLS-1$

        return results;
    } catch (Exception e) {
        logger.error(Messages.i18n.format("NotificationResource.EmailError", e.getMessage(), e)); //$NON-NLS-1$
        throw new SrampAtomException(e);
    }
}

From source file:mitm.common.security.smime.SMIMEBuilderImplTest.java

@Test
public void testEncryptSignedQuotedPrintableSoftBreaksDirectBC() throws Exception {
    MimeMessage message = loadMessage("qp-soft-breaks-signed.eml");

    SMIMEEnvelopedGenerator envelopedGenerator = new SMIMEEnvelopedGenerator();

    JceKeyTransRecipientInfoGenerator infoGenerator = new JceKeyTransRecipientInfoGenerator(
            encryptionCertificate);//  w  w  w .  j a va  2 s  .  co  m

    envelopedGenerator.addRecipientInfoGenerator(infoGenerator);

    JceCMSContentEncryptorBuilder encryptorBuilder = new JceCMSContentEncryptorBuilder(
            new ASN1ObjectIdentifier("1.2.840.113549.3.7"), 0).setProvider("BC");

    MimeBodyPart bodyPart = envelopedGenerator.generate(message, encryptorBuilder.build());

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

    newMessage.setContent(bodyPart.getContent(), bodyPart.getContentType());

    newMessage.saveChanges();

    File file = new File(tempDir, "testEncryptSignedQuotedPrintableSoftBreaksDirectBC.eml");

    FileOutputStream output = new FileOutputStream(file);

    MailUtils.writeMessage(newMessage, output);

    newMessage = MailUtils.loadMessage(file);

    assertEquals(SMIMEHeader.Type.ENCRYPTED, SMIMEHeader.getSMIMEContentType(newMessage));

    File opensslOutputFileSigned = new File(tempDir,
            "testEncryptSignedQuotedPrintableSoftBreaksDirectBC-openssl-signed.eml");

    decryptMessage(file, privateKeyEntry.getPrivateKey(), opensslOutputFileSigned);

    newMessage = MailUtils.loadMessage(opensslOutputFileSigned);

    assertTrue(newMessage.isMimeType("multipart/signed"));

    File opensslOutputFile = new File(tempDir,
            "testEncryptSignedQuotedPrintableSoftBreaksDirectBC-openssl.eml");

    verifyMessage(opensslOutputFileSigned, rootCertificate, opensslOutputFile);

    newMessage = MailUtils.loadMessage(opensslOutputFile);

    assertTrue(newMessage.isMimeType("text/plain"));

    assertEquals(SMIMEHeader.Type.NO_SMIME, SMIMEHeader.getSMIMEContentType(newMessage));
}

From source file:mitm.common.security.smime.SMIMEBuilderImplTest.java

@Test
public void testEncryptBase64EncodeBug() throws Exception {
    MimeMessage message = new MimeMessage(MailSession.getDefaultSession());

    message.setSubject("test");
    message.setContent("test", "text/plain");

    SMIMEBuilder builder = new SMIMEBuilderImpl(message, "to", "subject", "from");

    X509Certificate certificate = TestUtils
            .loadCertificate("test/resources/testdata/certificates/certificate-base64-encode-bug.cer");

    builder.addRecipient(certificate, SMIMERecipientMode.ISSUER_SERIAL);

    builder.encrypt(SMIMEEncryptionAlgorithm.DES_EDE3_CBC);

    MimeMessage newMessage = builder.buildMessage();

    newMessage.saveChanges();/*w w w.  jav a2  s .c  o m*/

    File file = new File(tempDir, "testEncryptBase64EncodeBug.eml");

    FileOutputStream output = new FileOutputStream(file);

    MailUtils.writeMessage(newMessage, output);

    newMessage = MailUtils.loadMessage(file);

    ByteArrayOutputStream bos = new ByteArrayOutputStream();

    newMessage.writeTo(new SkipHeadersOutputStream(bos));

    String blob = new String(bos.toByteArray(), "us-ascii");

    // check if all lines are not longer than 76 characters
    LineIterator it = IOUtils.lineIterator(new StringReader(blob));

    while (it.hasNext()) {
        String next = it.nextLine();

        if (next.length() > 76) {
            fail("Line length exceeds 76: " + next);
        }
    }
}

From source file:org.sakaiproject.email.impl.BasicEmailService.java

/**
 * Sets the content for a message. Also attaches files to the message.
 * @throws MessagingException//from  w ww . j a va 2s .c  om
 */
protected void setContent(String content, List<Attachment> attachments, MimeMessage msg, String contentType,
        String charset, String multipartSubtype) throws MessagingException {
    ArrayList<MimeBodyPart> embeddedAttachments = new ArrayList<MimeBodyPart>();
    if (attachments != null && attachments.size() > 0) {
        // Add attachments to messages
        for (Attachment attachment : attachments) {
            // attach the file to the message
            embeddedAttachments.add(createAttachmentPart(attachment));
        }
    }

    // if no direct attachments, keep the message simple and add the content as text.
    if (embeddedAttachments.size() == 0) {
        // if no contentType specified, go with text/plain
        if (contentType == null)
            msg.setText(content, charset);
        else
            msg.setContent(content, contentType);
    }
    // the multipart was constructed (ie. attachments available), use it as the message content
    else {
        // create a multipart container
        Multipart multipart = (multipartSubtype != null) ? new MimeMultipart(multipartSubtype)
                : new MimeMultipart();

        // create a body part for the message text
        MimeBodyPart msgBodyPart = new MimeBodyPart();
        if (contentType == null)
            msgBodyPart.setText(content, charset);
        else
            msgBodyPart.setContent(content, contentType);

        // add the message part to the container
        multipart.addBodyPart(msgBodyPart);

        // add attachments
        for (MimeBodyPart attachPart : embeddedAttachments) {
            multipart.addBodyPart(attachPart);
        }

        // set the multipart container as the content of the message
        msg.setContent(multipart);
    }
}

From source file:org.ohmage.service.UserServices.java

/**
 * Resets a user's password. This is done by first updating the user's 
 * information and then by sending an email to the user.
 * //from   www.  j a v  a 2s  .  c  o m
 * @param username The user's username.
 * 
 * @throws ServiceException There was an error.
 */
public void resetPassword(final String username) throws ServiceException {

    String newPassword = generateRandomTemporaryPassword();

    String emailAddress;
    try {
        emailAddress = userQueries.getEmailAddress(username);
    } catch (DataAccessException e) {
        throw new ServiceException(e);
    }

    if (emailAddress == null) {
        throw new ServiceException("The user no longer exists or no longer has an email address.");
    }

    try {
        String hashedPassword;
        if (ConfigServices.readServerConfiguration().getSha512PasswordHashingEnabled()) {
            hashedPassword = Crypt.crypt(newPassword);
        } else {
            hashedPassword = BCrypt.hashpw(newPassword, BCrypt.gensalt(User.BCRYPT_COMPLEXITY));
        }
        userQueries.updateUserPassword(username, hashedPassword, true);
    } catch (DataAccessException e) {
        throw new ServiceException(e);
    }

    // Get the session.
    Session smtpSession = MailUtils.getMailSession();
    // Create the message.
    MimeMessage message = new MimeMessage(smtpSession);

    try {
        // set up properties
        MailUtils.setMailMessageTo(message, emailAddress);
        MailUtils.setMailMessageFrom(message, PreferenceCache.KEY_MAIL_PASSWORD_RECOVERY_SENDER);
        MailUtils.setMailMessageSubject(message, PreferenceCache.KEY_MAIL_PASSWORD_RECOVERY_SUBJECT);

        try {
            message.setContent(
                    PreferenceCache.instance().lookup(PreferenceCache.KEY_MAIL_PASSWORD_RECOVERY_TEXT)
                            + "<br /><br />" + newPassword,
                    "text/html");
        } catch (CacheMissException e) {
            throw new ServiceException("The mail property is not in the preference table: "
                    + PreferenceCache.KEY_MAIL_PASSWORD_RECOVERY_SUBJECT, e);
        } catch (MessagingException e) {
            throw new ServiceException("Could not set the HTML portion of the message.", e);
        }

        // send message
        MailUtils.sendMailMessage(smtpSession, message);

    } catch (ServiceException e) {
        throw new ServiceException("Cannot successfully send the password recovery notification.", e);
    }

    /*// Add the recipient.
    try {
       message.setRecipient(
       Message.RecipientType.TO, 
       new InternetAddress(emailAddress));
    }
    catch(AddressException e) {
       throw new ServiceException(
       "The destination address is not a valid email address.",
       e);
    }
    catch(MessagingException e) {
       throw new ServiceException(
       "Could not add the recipient to the message.",
       e);
    }
            
    // Add the sender.
    try {
       message.setFrom(
       new InternetAddress(
             PreferenceCache.instance().lookup(
                PreferenceCache.KEY_MAIL_PASSWORD_RECOVERY_SENDER)));
    }
    catch(CacheMissException e) {
       throw new ServiceException(
    "The mail property is not in the preference table: " +
       PreferenceCache.KEY_MAIL_PASSWORD_RECOVERY_SENDER,
    e);
    }
    catch(AddressException e) {
       throw new ServiceException(
       "The origin address is not a valid email address.",
       e);
    }
    catch(MessagingException e) {
       throw new ServiceException(
       "Could not update the sender's email address.",
       e);
    }
            
    // Set the subject.
    try {
       message.setSubject(
       PreferenceCache.instance().lookup(
          PreferenceCache.KEY_MAIL_PASSWORD_RECOVERY_SUBJECT));
    }
    catch(CacheMissException e) {
       throw new ServiceException(
       "The mail property is not in the preference table: " +
          PreferenceCache.KEY_MAIL_PASSWORD_RECOVERY_SUBJECT,
       e);
    }
    catch(MessagingException e) {
       throw new ServiceException(
       "Could not set the subject on the message.",
       e);
    }
            
    try {
       message.setContent(
       PreferenceCache.instance().lookup(
          PreferenceCache.KEY_MAIL_PASSWORD_RECOVERY_TEXT) +
          "<br /><br />" +
          newPassword, 
       "text/html");
    }
    catch(CacheMissException e) {
       throw new ServiceException(
       "The mail property is not in the preference table: " +
          PreferenceCache.KEY_MAIL_PASSWORD_RECOVERY_SUBJECT,
       e);
    }
    catch(MessagingException e) {
       throw new ServiceException(
       "Could not set the HTML portion of the message.", 
       e);
    }
            
    try {
       message.saveChanges();
    }
    catch(MessagingException e) {
       throw new ServiceException(
       "Could not save the changes to the message.",
       e);
    }
            
    MailUtils.sendMailMessage(smtpSession, message);
    */
}

From source file:org.ohmage.service.UserServices.java

/**
 * Registers the user in the system by first creating the user whose 
 * account is disabled. It then creates an entry in the registration cache
 * with the key for the user to activate their account. Finally, it sends 
 * an email to the user with a link that includes the activation key.
 * //from   ww w .j  av  a  2 s  .c  o  m
 * @param username The username of the new user.
 * 
 * @param password The plain-text password for the new user.
 * 
 * @param emailAddress The email address for the user.
 * 
 * @throws ServiceException There was a configuration issue with the mail
 *                      server or if there was an issue in the Query
 *                      layer.
 */
public void createUserRegistration(final String username, final String password, final String emailAddress)
        throws ServiceException {

    try {
        // Generate a random registration ID from the username and some 
        // random bits.
        MessageDigest digest = MessageDigest.getInstance("SHA-512");
        digest.update(username.getBytes());
        digest.update(UUID.randomUUID().toString().getBytes());
        byte[] digestBytes = digest.digest();

        StringBuffer buffer = new StringBuffer();
        for (int i = 0; i < digestBytes.length; i++) {
            buffer.append(Integer.toString((digestBytes[i] & 0xff) + 0x100, 16).substring(1));
        }
        String registrationId = buffer.toString();

        // Hash the password.
        String hashedPassword;
        if (ConfigServices.readServerConfiguration().getSha512PasswordHashingEnabled()) {
            hashedPassword = Crypt.crypt(password);
        } else {
            hashedPassword = BCrypt.hashpw(password, BCrypt.gensalt(User.BCRYPT_COMPLEXITY));
        }

        // Create the user in the database with all of its connections.
        userQueries.createUserRegistration(username, hashedPassword, emailAddress, registrationId.toString());

        // Build the registration text.
        String registrationText;
        try {
            registrationText = PreferenceCache.instance().lookup(PreferenceCache.KEY_MAIL_REGISTRATION_TEXT);
        } catch (CacheMissException e) {
            throw new ServiceException("The mail property is not in the preference table: "
                    + PreferenceCache.KEY_MAIL_REGISTRATION_TEXT, e);
        }

        // Compute the registration link.
        StringBuilder registrationLink = new StringBuilder("<a href=\"");
        // Get this machine's root URL.
        try {
            registrationLink.append(CookieUtils.buildServerRootUrl());
        } catch (DomainException e) {
            throw new ServiceException("Could not build the root server URL.", e);
        }
        // Get the registration activation function.
        String activationFunction;
        try {
            activationFunction = PreferenceCache.instance()
                    .lookup(PreferenceCache.KEY_MAIL_REGISTRATION_ACTIVATION_FUNCTION);
        } catch (CacheMissException e) {
            //Set to #activate for backwards compatability
            activationFunction = "#activate";
            LOGGER.info("The mail property is not in the preference table:"
                    + PreferenceCache.KEY_MAIL_REGISTRATION_ACTIVATION_FUNCTION + ", setting manually");
        }
        registrationLink.append(activationFunction);
        registrationLink.append('?');
        registrationLink.append(InputKeys.USER_REGISTRATION_ID);
        registrationLink.append('=');
        registrationLink.append(registrationId);
        registrationLink.append("\">I Agree</a>");
        registrationText = registrationText.replace(MAIL_REGISTRATION_TEXT_REGISTRATION_LINK, registrationLink);

        // Get the terms of service.
        String termsOfService;
        try {
            termsOfService = "<tt>" + PreferenceCache.instance().lookup(PreferenceCache.KEY_TERMS_OF_SERVICE)
                    + "</tt>";
            termsOfService = termsOfService.replace("\n", "<br />");
        } catch (CacheMissException e) {
            throw new ServiceException(
                    "The mail property is not in the preference table: " + PreferenceCache.KEY_TERMS_OF_SERVICE,
                    e);
        }
        // Add the terms of service to the email.
        registrationText = registrationText.replace(MAIL_REGISTRATION_TEXT_TOS, termsOfService);

        // Get the session.
        Session smtpSession = MailUtils.getMailSession();
        // Create the message.
        MimeMessage message = new MimeMessage(smtpSession);

        try {
            // set up properties
            MailUtils.setMailMessageTo(message, emailAddress);
            MailUtils.setMailMessageFrom(message, PreferenceCache.KEY_MAIL_REGISTRATION_SENDER);
            MailUtils.setMailMessageSubject(message, PreferenceCache.KEY_MAIL_REGISTRATION_SUBJECT);

            try {
                // Set the content of the message.
                message.setContent(registrationText, "text/html");
            } catch (MessagingException e) {
                throw new ServiceException("There was an error constructing the message.", e);
            }

            // send message
            MailUtils.sendMailMessage(smtpSession, message);

        } catch (ServiceException e) {
            throw new ServiceException("Cannot successfully send the password recovery notification.", e);
        }

        /*
        // Add the recipient.
        try {
           message.setRecipient(
          Message.RecipientType.TO, 
          new InternetAddress(emailAddress));
        }
        catch(AddressException e) {
           throw new ServiceException(
          "The destination address is not a valid email address.",
          e);
        }
        catch(MessagingException e) {
           throw new ServiceException(
          "Could not add the recipient to the message.",
          e);
        }
                
        // Add the sender.
        try {
           message.setFrom(
          new InternetAddress(
                PreferenceCache.instance().lookup(
                   PreferenceCache.KEY_MAIL_REGISTRATION_SENDER)));
        }
        catch(CacheMissException e) {
           throw new ServiceException(
              "The mail property is not in the preference table: " +
          PreferenceCache.KEY_MAIL_REGISTRATION_SENDER,
              e);
        }
        catch(AddressException e) {
           throw new ServiceException(
          "The origin address is not a valid email address.",
          e);
        }
        catch(MessagingException e) {
           throw new ServiceException(
          "Could not update the sender's email address.",
          e);
        }
                
        // Set the subject.
        try {
           message.setSubject(
          PreferenceCache.instance().lookup(
             PreferenceCache.KEY_MAIL_REGISTRATION_SUBJECT));
        }
        catch(CacheMissException e) {
           throw new ServiceException(
              "The mail property is not in the preference table: " +
          PreferenceCache.KEY_MAIL_REGISTRATION_SUBJECT,
              e);
        }
        catch(MessagingException e) {
           throw new ServiceException(
          "Could not set the subject on the message.",
          e);
        }
                
        try {
           // Set the content of the message.
           message.setContent(registrationText, "text/html");
        }
        catch(MessagingException e) {
           throw new ServiceException(
          "There was an error constructing the message.",
          e);
        }
                
        try {
           message.saveChanges();
        }
        catch(MessagingException e) {
           throw new ServiceException(
          "Could not save the changes to the message.",
          e);
        }
                
        MailUtils.sendMailMessage(smtpSession, message);
         */

    } catch (NoSuchAlgorithmException e) {
        throw new ServiceException("The hashing algorithm is unknown.", e);
    } catch (DataAccessException e) {
        throw new ServiceException(e);
    }
}

From source file:org.nuxeo.ecm.platform.ec.notification.email.EmailHelper.java

protected void sendmail0(Map<String, Object> mail)
        throws MessagingException, IOException, TemplateException, LoginException, RenderingException {

    Session session = getSession();/*from  w  w  w  .  ja  v  a  2 s  .com*/
    if (javaMailNotAvailable || session == null) {
        log.warn("Not sending email since JavaMail is not configured");
        return;
    }

    // Construct a MimeMessage
    MimeMessage msg = new MimeMessage(session);
    msg.setFrom(new InternetAddress(session.getProperty("mail.from")));
    Object to = mail.get("mail.to");
    if (!(to instanceof String)) {
        log.error("Invalid email recipient: " + to);
        return;
    }
    msg.setRecipients(Message.RecipientType.TO, InternetAddress.parse((String) to, false));

    RenderingService rs = Framework.getService(RenderingService.class);

    DocumentRenderingContext context = new DocumentRenderingContext();
    context.remove("doc");
    context.putAll(mail);
    context.setDocument((DocumentModel) mail.get("document"));
    context.put("Runtime", Framework.getRuntime());

    String customSubjectTemplate = (String) mail.get(NotificationConstants.SUBJECT_TEMPLATE_KEY);
    if (customSubjectTemplate == null) {
        String subjTemplate = (String) mail.get(NotificationConstants.SUBJECT_KEY);
        Template templ = new Template("name", new StringReader(subjTemplate), stringCfg);

        Writer out = new StringWriter();
        templ.process(mail, out);
        out.flush();

        msg.setSubject(out.toString(), "UTF-8");
    } else {
        rs.registerEngine(new NotificationsRenderingEngine(customSubjectTemplate));

        LoginContext lc = Framework.login();

        Collection<RenderingResult> results = rs.process(context);
        String subjectMail = "<HTML><P>No parsing Succeded !!!</P></HTML>";

        for (RenderingResult result : results) {
            subjectMail = (String) result.getOutcome();
        }
        subjectMail = NotificationServiceHelper.getNotificationService().getEMailSubjectPrefix() + subjectMail;
        msg.setSubject(subjectMail, "UTF-8");

        lc.logout();
    }

    msg.setSentDate(new Date());

    rs.registerEngine(new NotificationsRenderingEngine((String) mail.get(NotificationConstants.TEMPLATE_KEY)));

    LoginContext lc = Framework.login();

    Collection<RenderingResult> results = rs.process(context);
    String bodyMail = "<HTML><P>No parsing Succedeed !!!</P></HTML>";

    for (RenderingResult result : results) {
        bodyMail = (String) result.getOutcome();
    }

    lc.logout();

    rs.unregisterEngine("ftl");

    msg.setContent(bodyMail, "text/html; charset=utf-8");

    // Send the message.
    Transport.send(msg);
}