Example usage for javax.mail.internet MimeMessage MimeMessage

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

Introduction

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

Prototype

public MimeMessage(MimeMessage source) throws MessagingException 

Source Link

Document

Constructs a new MimeMessage with content initialized from the source MimeMessage.

Usage

From source file:mitm.application.djigzo.james.matchers.HasValidPasswordTest.java

@Test
public void testExpired() throws MessagingException, EncryptorException {
    HasValidPassword matcher = new HasValidPassword();

    MockMatcherConfig matcherConfig = new MockMatcherConfig("test", "matchOnError=false", mailetContext);

    matcher.init(matcherConfig);//from   w w w. j a va2  s.  co  m

    Mail mail = new MockMail();

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

    message.setContent("test", "text/plain");
    message.setFrom(new InternetAddress("123456@example.com"));

    message.saveChanges();

    mail.setMessage(message);

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

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

    mail.setRecipients(recipients);

    Collection<?> result = matcher.match(mail);

    assertEquals(0, result.size());
}

From source file:it.eng.spagobi.tools.scheduler.dispatcher.UniqueMailDocumentDispatchChannel.java

/** AFter all files are stored in temporary tabe takes them and sens as zip or as separate attachments
 * //from   w  w w .j ava2 s .  co m
 * @param mailOptions
 * @return
 */

public boolean sendFiles(Map<String, Object> mailOptions) {

    logger.debug("IN");
    try {
        final String DEFAULT_SSL_FACTORY = "javax.net.ssl.SSLSocketFactory";
        final String CUSTOM_SSL_FACTORY = "it.eng.spagobi.commons.services.DummySSLSocketFactory";

        String tempFolderPath = (String) mailOptions.get(TEMP_FOLDER_PATH);

        File tempFolder = new File(tempFolderPath);

        if (!tempFolder.exists() || !tempFolder.isDirectory()) {
            logger.error("Temp Folder " + tempFolderPath
                    + " does not exist or is not a directory: stop sending mail");
            return false;
        }

        String smtphost = null;
        String pass = null;
        String smtpssl = null;
        String trustedStorePath = null;
        String user = null;
        String from = null;
        int smtpPort = 25;

        try {

            smtphost = SingletonConfig.getInstance().getConfigValue("MAIL.PROFILES.scheduler.smtphost");
            String smtpportS = SingletonConfig.getInstance().getConfigValue("MAIL.PROFILES.scheduler.smtpport");
            smtpssl = SingletonConfig.getInstance().getConfigValue("MAIL.PROFILES.scheduler.useSSL");
            logger.debug(smtphost + " " + smtpportS + " use SSL: " + smtpssl);
            //Custom Trusted Store Certificate Options
            trustedStorePath = SingletonConfig.getInstance().getConfigValue("MAIL.PROFILES.trustedStore.file");

            if ((smtphost == null) || smtphost.trim().equals(""))
                throw new Exception("Smtp host not configured");
            if ((smtpportS == null) || smtpportS.trim().equals("")) {
                throw new Exception("Smtp host not configured");
            } else {
                smtpPort = Integer.parseInt(smtpportS);
            }

            from = SingletonConfig.getInstance().getConfigValue("MAIL.PROFILES.scheduler.from");
            if ((from == null) || from.trim().equals(""))
                from = "spagobi.scheduler@eng.it";
            user = SingletonConfig.getInstance().getConfigValue("MAIL.PROFILES.scheduler.user");
            if ((user == null) || user.trim().equals("")) {
                logger.debug("Smtp user not configured");
                user = null;
            }
            //   throw new Exception("Smtp user not configured");
            pass = SingletonConfig.getInstance().getConfigValue("MAIL.PROFILES.scheduler.password");
            if ((pass == null) || pass.trim().equals("")) {
                logger.debug("Smtp password not configured");
            }
            //   throw new Exception("Smtp password not configured");
        } catch (Exception e) {
            logger.error("Some E-mail configuration not set in table sbi_config: check you have all settings.",
                    e);
            throw new Exception(
                    "Some E-mail configuration not set in table sbi_config: check you have all settings.");
        }

        String mailSubj = mailOptions.get(MAIL_SUBJECT) != null ? (String) mailOptions.get(MAIL_SUBJECT) : null;
        Map parametersMap = mailOptions.get(PARAMETERS_MAP) != null ? (Map) mailOptions.get(PARAMETERS_MAP)
                : null;
        mailSubj = StringUtilities.substituteParametersInString(mailSubj, parametersMap, null, false);

        String mailTxt = mailOptions.get(MAIL_TXT) != null ? (String) mailOptions.get(MAIL_TXT) : null;
        String[] recipients = mailOptions.get(RECIPIENTS) != null ? (String[]) mailOptions.get(RECIPIENTS)
                : null;

        //Set the host smtp address
        Properties props = new Properties();
        props.put("mail.smtp.host", smtphost);
        props.put("mail.smtp.p   ort", Integer.toString(smtpPort));

        // open session
        Session session = null;

        // create autheticator object
        Authenticator auth = null;
        if (user != null) {
            auth = new SMTPAuthenticator(user, pass);
            props.put("mail.smtp.auth", "true");
            //SSL Connection
            if (smtpssl.equals("true")) {
                Security.addProvider(new com.sun.net.ssl.internal.ssl.Provider());
                //props.put("mail.smtp.debug", "true");          
                props.put("mail.smtps.auth", "true");
                props.put("mail.smtps.socketFactory.port", Integer.toString(smtpPort));
                if ((!StringUtilities.isEmpty(trustedStorePath))) {
                    /* Dynamic configuration of trustedstore for CA
                     * Using Custom SSLSocketFactory to inject certificates directly from specified files
                     */
                    //System.setProperty("java.security.debug","certpath");
                    //System.setProperty("javax.net.debug","ssl ");
                    props.put("mail.smtps.socketFactory.class", CUSTOM_SSL_FACTORY);

                } else {
                    //System.setProperty("java.security.debug","certpath");
                    //System.setProperty("javax.net.debug","ssl ");
                    props.put("mail.smtps.socketFactory.class", DEFAULT_SSL_FACTORY);
                }
                props.put("mail.smtp.socketFactory.fallback", "false");
            }

            //session = Session.getDefaultInstance(props, auth);
            session = Session.getInstance(props, auth);
            //session.setDebug(true);
            //session.setDebugOut(null);
            logger.info("Session.getInstance(props, auth)");

        } else {
            //session = Session.getDefaultInstance(props);
            session = Session.getInstance(props);
            logger.info("Session.getInstance(props)");
        }

        // create a message
        Message msg = new MimeMessage(session);
        // set the from and to address
        InternetAddress addressFrom = new InternetAddress(from);
        msg.setFrom(addressFrom);
        InternetAddress[] addressTo = new InternetAddress[recipients.length];
        for (int i = 0; i < recipients.length; i++) {
            addressTo[i] = new InternetAddress(recipients[i]);
        }
        msg.setRecipients(Message.RecipientType.TO, addressTo);
        // Setting the Subject and Content Type

        String subject = mailSubj;

        String nameSuffix = mailOptions.get(NAME_SUFFIX) != null ? (String) mailOptions.get(NAME_SUFFIX) : null;
        Boolean reportNameInSubject = mailOptions.get(REPORT_NAME_IN_SUBJECT) != null
                && !mailOptions.get(REPORT_NAME_IN_SUBJECT).toString().equals("")
                        ? (Boolean) mailOptions.get(REPORT_NAME_IN_SUBJECT)
                        : null;
        //Boolean descriptionSuffix =mailOptions.get(DESCRIPTION_SUFFIX) != null && !mailOptions.get(DESCRIPTION_SUFFIX).toString().equals("")? (Boolean) mailOptions.get(DESCRIPTION_SUFFIX) : null;
        String zipFileName = mailOptions.get(ZIP_FILE_NAME) != null ? (String) mailOptions.get(ZIP_FILE_NAME)
                : "Zipped Documents";
        String contentType = mailOptions.get(CONTENT_TYPE) != null ? (String) mailOptions.get(CONTENT_TYPE)
                : null;
        String fileExtension = mailOptions.get(FILE_EXTENSION) != null
                ? (String) mailOptions.get(FILE_EXTENSION)
                : null;

        if (reportNameInSubject) {
            subject += " " + nameSuffix;
        }

        msg.setSubject(subject);
        // create and fill the first message part
        MimeBodyPart mbp1 = new MimeBodyPart();
        mbp1.setText(mailTxt);

        // attach the file to the message

        boolean isZipDocument = mailOptions.get(IS_ZIP_DOCUMENT) != null
                ? (Boolean) mailOptions.get(IS_ZIP_DOCUMENT)
                : false;
        zipFileName = mailOptions.get(ZIP_FILE_NAME) != null ? (String) mailOptions.get(ZIP_FILE_NAME)
                : "Zipped Documents";

        // create the Multipart and add its parts to it
        Multipart mp = new MimeMultipart();

        mp.addBodyPart(mbp1);

        if (isZipDocument) {
            logger.debug("Make zip");
            // create the second message part
            MimeBodyPart mbp2 = new MimeBodyPart();
            mbp2 = zipAttachment(zipFileName, mailOptions, tempFolder);
            mp.addBodyPart(mbp2);
        } else {
            logger.debug("Attach single files");
            SchedulerDataSource sds = null;
            MimeBodyPart bodyPart = null;
            try {
                String[] entries = tempFolder.list();

                for (int i = 0; i < entries.length; i++) {
                    logger.debug("Attach file " + entries[i]);
                    File f = new File(tempFolder + File.separator + entries[i]);

                    byte[] content = getBytesFromFile(f);

                    bodyPart = new MimeBodyPart();

                    sds = new SchedulerDataSource(content, contentType, entries[i]);
                    //sds = new SchedulerDataSource(content, contentType, entries[i] + fileExtension);

                    bodyPart.setDataHandler(new DataHandler(sds));
                    bodyPart.setFileName(sds.getName());

                    mp.addBodyPart(bodyPart);
                }

            } catch (Exception e) {
                logger.error("Error while attaching files", e);
            }

        }

        // add the Multipart to the message
        msg.setContent(mp);
        logger.debug("Preparing to send mail");
        // send message
        if ((smtpssl.equals("true")) && (!StringUtilities.isEmpty(user)) && (!StringUtilities.isEmpty(pass))) {
            logger.debug("Smtps mode active user " + user);
            //USE SSL Transport comunication with SMTPS
            Transport transport = session.getTransport("smtps");
            transport.connect(smtphost, smtpPort, user, pass);
            transport.sendMessage(msg, msg.getAllRecipients());
            transport.close();
        } else {
            logger.debug("Smtp mode");
            //Use normal SMTP
            Transport.send(msg);
        }

        //         logger.debug("delete tempFolder path "+tempFolder.getPath());
        //         boolean deleted = tempFolder.delete();
        //         logger.debug("Temp folder deleted "+deleted);

    } catch (Exception e) {
        logger.error("Error while sending schedule result mail", e);
        return false;
    } finally {
        logger.debug("OUT");
    }
    return true;
}

From source file:com.openkm.util.MailUtils.java

/**
 * Create a mail./*from www  .ja v a2s.co  m*/
 * 
 * @param fromAddress Origin address.
 * @param toAddress Destination addresses.
 * @param subject The mail subject.
 * @param text The mail body.
 * @throws MessagingException If there is any error.
 */
private static MimeMessage create(String fromAddress, Collection<String> toAddress, String subject, String text,
        Collection<String> docsPath, List<File> tmpAttachments) throws MessagingException,
        PathNotFoundException, AccessDeniedException, RepositoryException, IOException, DatabaseException {
    log.debug("create({}, {}, {}, {}, {})", new Object[] { fromAddress, toAddress, subject, text, docsPath });
    Session mailSession = getMailSession();
    MimeMessage msg = new MimeMessage(mailSession);

    if (fromAddress != null && Config.SEND_MAIL_FROM_USER) {
        InternetAddress from = new InternetAddress(fromAddress);
        msg.setFrom(from);
    } else {
        msg.setFrom();
    }

    InternetAddress[] to = new InternetAddress[toAddress.size()];
    int idx = 0;

    for (Iterator<String> it = toAddress.iterator(); it.hasNext();) {
        to[idx++] = new InternetAddress(it.next());
    }

    // Build a multiparted mail with HTML and text content for better SPAM behaviour
    Multipart content = new MimeMultipart();

    // HTML Part
    MimeBodyPart htmlPart = new MimeBodyPart();
    StringBuilder htmlContent = new StringBuilder();
    htmlContent.append("<!DOCTYPE html PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\">\n");
    htmlContent.append("<html>\n<head>\n");
    htmlContent.append("<meta content=\"text/html;charset=UTF-8\" http-equiv=\"Content-Type\"/>\n");
    htmlContent.append("</head>\n<body>\n");
    htmlContent.append(text);
    htmlContent.append("\n</body>\n</html>");
    htmlPart.setContent(htmlContent.toString(), "text/html;charset=UTF-8");
    htmlPart.setHeader("Content-Type", "text/html;charset=UTF-8");
    htmlPart.setDisposition(Part.INLINE);
    content.addBodyPart(htmlPart);
    idx = 0;

    if (docsPath != null) {
        for (String docPath : docsPath) {
            InputStream is = null;
            FileOutputStream fos = null;
            String docName = PathUtils.getName(docPath);

            try {
                final Document doc = OKMDocument.getInstance().getProperties(null, docPath);
                is = OKMDocument.getInstance().getContent(null, docPath, false);
                final File tmpAttch = tmpAttachments.get(idx++);
                fos = new FileOutputStream(tmpAttch);
                IOUtils.copy(is, fos);
                fos.flush();

                // Document attachment part
                MimeBodyPart docPart = new MimeBodyPart();
                DataSource source = new FileDataSource(tmpAttch.getPath()) {
                    public String getContentType() {
                        return doc.getMimeType();
                    }
                };

                docPart.setDataHandler(new DataHandler(source));
                docPart.setFileName(MimeUtility.encodeText(docName));
                docPart.setDisposition(Part.ATTACHMENT);
                content.addBodyPart(docPart);
            } finally {
                IOUtils.closeQuietly(is);
                IOUtils.closeQuietly(fos);
            }
        }
    }

    msg.setHeader("MIME-Version", "1.0");
    msg.setHeader("Content-Type", content.getContentType());
    msg.addHeader("Charset", "UTF-8");
    msg.setRecipients(Message.RecipientType.TO, to);
    msg.setSubject(subject, "UTF-8");
    msg.setSentDate(new Date());
    msg.setContent(content);
    msg.saveChanges();

    log.debug("create: {}", msg);
    return msg;
}

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

@Override
public void serviceMail(Mail mail) {
    try {//w ww.  j  a v a  2  s.com
        final InternetAddress originator = messageOriginatorIdentifier.getOriginator(mail);

        KeyAndCertificate signingKeyAndCertificate = actionExecutor
                .executeTransaction(new DatabaseAction<KeyAndCertificate>() {
                    @Override
                    public KeyAndCertificate doAction(Session session) throws DatabaseException {
                        Session previousSession = sessionManager.getSession();

                        sessionManager.setSession(session);

                        try {
                            return getSigningKeyAndCertificateAction(session, originator);
                        } finally {
                            sessionManager.setSession(previousSession);
                        }
                    }
                }, ACTION_RETRIES /* retry on a ConstraintViolationException */);

        MimeMessage message = mail.getMessage();

        if (signingKeyAndCertificate != null && message != null) {
            SMIMEBuilder sMIMEBuilder = new SMIMEBuilderImpl(message, protectedHeaders);

            sMIMEBuilder.setUseDeprecatedContentTypes(useDeprecatedContentTypes);

            X509Certificate signingCertificate = signingKeyAndCertificate.getCertificate();

            PrivateKey privateKey = signingKeyAndCertificate.getPrivateKey();

            if (privateKey != null && signingCertificate != null) {
                X509Certificate[] chain = getCertificateChain(signingCertificate);

                sMIMEBuilder.addCertificates(chain);

                SMIMESigningAlgorithm localAlgorithm = getSigningAlgorithm(mail);

                sMIMEBuilder.addSigner(privateKey, signingCertificate, localAlgorithm);

                getLogger().debug("Signing message. Signing algorithm: {}, Sign mode: {}", localAlgorithm,
                        signMode);

                sMIMEBuilder.sign(signMode);

                MimeMessage signed = sMIMEBuilder.buildMessage();

                if (signed != null) {
                    signed.saveChanges();

                    /*
                     * A new MimeMessage instance will be created. This makes ure that the 
                     * MimeMessage can be written by James (using writeTo()). The message-ID
                     * of the source message will be retained if told to do so
                     */
                    signed = retainMessageID ? new MimeMessageWithID(signed, message.getMessageID())
                            : new MimeMessage(signed);

                    mail.setMessage(signed);
                }
            } else {
                if (privateKey == null) {
                    getLogger().warn("PrivateKey is missing. Message cannot be signed.");
                }

                if (signingCertificate == null) {
                    getLogger().warn("signingCertificate is missing. Message cannot be signed.");
                }
            }
        } else {
            getLogger().debug("No signing certificate found, or message is null.");
        }
    } catch (MessagingException e) {
        getLogger().error("Error reading the message.", e);
    } catch (DatabaseException e) {
        getLogger().error("Error getting signing keyAndCertificate.", e);
    } catch (IOException e) {
        getLogger().error("Error signing the message.", e);
    } catch (SMIMEBuilderException e) {
        getLogger().error("Error signing the message.", e);
    }
}

From source file:com.gtwm.jasperexecute.RunJasperReports.java

public void emailReport(String emailHost, String emailUser, String emailPass, Set<String> emailRecipients,
        String emailSender, String emailSubject, List<String> attachmentFileNames) throws MessagingException {
    Properties props = new Properties();
    //props.setProperty("mail.debug", "true");
    props.setProperty("mail.smtp.host", emailHost);
    if (emailUser != null) {
        props.setProperty("mail.smtp.auth", "true");
    }//  ww w.j  a v  a  2  s  . c  o  m
    Authenticator emailAuthenticator = new EmailAuthenticator(emailUser, emailPass);
    Session mailSession = Session.getDefaultInstance(props, emailAuthenticator);
    MimeMessage message = new MimeMessage(mailSession);
    message.setSubject(emailSubject);
    for (String emailRecipient : emailRecipients) {
        Address toAddress = new InternetAddress(emailRecipient);
        message.addRecipient(Message.RecipientType.TO, toAddress);
    }
    Address fromAddress = new InternetAddress(emailSender);
    message.setFrom(fromAddress);
    // Message text
    Multipart multipart = new MimeMultipart();
    BodyPart textBodyPart = new MimeBodyPart();
    textBodyPart.setText("Database report attached\n\n");
    multipart.addBodyPart(textBodyPart);
    // Attachments
    for (String attachmentFileName : attachmentFileNames) {
        BodyPart attachmentBodyPart = new MimeBodyPart();
        DataSource source = new FileDataSource(attachmentFileName);
        attachmentBodyPart.setDataHandler(new DataHandler(source));
        String fileNameWithoutPath = attachmentFileName.replaceAll("^.*\\/", "");
        fileNameWithoutPath = fileNameWithoutPath.replaceAll("^.*\\\\", "");
        attachmentBodyPart.setFileName(fileNameWithoutPath);
        multipart.addBodyPart(attachmentBodyPart);
    }
    // add parts to message
    message.setContent(multipart);
    // send via SMTP
    Transport transport = mailSession.getTransport("smtp");
    // transport.connect(emailHost, emailUser, emailPass);
    transport.connect();
    transport.sendMessage(message, message.getAllRecipients());
    transport.close();
}

From source file:mitm.application.djigzo.james.matchers.HasValidPasswordTest.java

@Test
public void testUnknownUser() throws MessagingException, EncryptorException {
    HasValidPassword matcher = new HasValidPassword();

    MockMatcherConfig matcherConfig = new MockMatcherConfig("test", "matchOnError=false", mailetContext);

    matcher.init(matcherConfig);/* w w w .j  av a 2  s.com*/

    Mail mail = new MockMail();

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

    message.setContent("test", "text/plain");
    message.setFrom(new InternetAddress("123456@example.com"));

    message.saveChanges();

    mail.setMessage(message);

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

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

    mail.setRecipients(recipients);

    Collection<?> result = matcher.match(mail);

    assertEquals(0, result.size());
}

From source file:com.sat.common.CustomReport.java

/**
 * Sendmail./*from   w  w  w  .  ja v a2 s . co m*/
 * 
 * @param msg
 *            the msg
 * @throws AddressException
 *             the address exception
 * @throws IOException
 *             Signals that an I/O exception has occurred.
 */
public static void sendmail(String msg) throws AddressException, IOException {

    ConfigFileHandlerManager miscConfigFileHandlerManager = new ConfigFileHandlerManager();
    miscConfigFileHandlerManager.loadPropertiesBasedonPropertyFileName("com.cisco.lms.lms");
    Validate miscValidate = new Validate();

    String from = miscValidate.readsystemvariable("MAIL.FROM");
    String host = miscValidate.readsystemvariable("MAIL.SMTP.HOST");
    String to = miscValidate.readsystemvariable("MAIL.TO");

    String subject = miscValidate.readsystemvariable("MAIL.SUBJECT");
    String personal = miscValidate.readsystemvariable("MAIL.FROM.PERSONAL");

    // Mail to details
    Properties properties = System.getProperties();
    properties.setProperty("mail.smtp.host", host);
    javax.mail.Session session = javax.mail.Session.getDefaultInstance(properties);

    // compose the message
    try {
        MimeMessage message = new MimeMessage(session);
        message.setFrom(new InternetAddress(from, personal));

        message.addRecipients(Message.RecipientType.TO, to);
        message.setSubject(subject);
        Multipart mp = new MimeMultipart();
        MimeBodyPart htmlPart = new MimeBodyPart();
        htmlPart.setContent(msg, "text/html");
        mp.addBodyPart(htmlPart);
        message.setContent(mp);
        Transport.send(message);
        System.out.println(msg);
        System.out.println("message sent successfully....");

    } catch (MessagingException mex) {
        mex.printStackTrace();
    } catch (Exception e) {
        System.out.println("\tException in sending mail to configured mailers list");
    }
}

From source file:Implement.Service.AdminServiceImpl.java

@Override
public boolean sendPackageApprovedEmail(PackageApprovedEmailData emailData) throws MessagingException {
    String path = System.getProperty("catalina.base");
    MimeBodyPart logo = new MimeBodyPart();
    // attach the file to the message
    DataSource source = new FileDataSource(new File(path + "/webapps/Images/Email/logoIcon.png"));
    logo.setDataHandler(new DataHandler(source));
    logo.setFileName("logoIcon.png");
    logo.setDisposition(MimeBodyPart.INLINE);
    logo.setHeader("Content-ID", "<logo_Icon>"); // cid:image_cid

    MimeBodyPart facebook = new MimeBodyPart();
    // attach the file to the message
    source = new FileDataSource(new File(path + "/webapps/Images/Email/facebookIcon.png"));
    facebook.setDataHandler(new DataHandler(source));
    facebook.setFileName("facebookIcon.png");
    facebook.setDisposition(MimeBodyPart.INLINE);
    facebook.setHeader("Content-ID", "<fb_Icon>"); // cid:image_cid

    MimeBodyPart twitter = new MimeBodyPart();
    // attach the file to the message
    source = new FileDataSource(new File(path + "/webapps/Images/Email/twitterIcon.png"));
    twitter.setDataHandler(new DataHandler(source));
    twitter.setFileName("twitterIcon.png");
    twitter.setDisposition(MimeBodyPart.INLINE);
    twitter.setHeader("Content-ID", "<twitter_Icon>"); // cid:image_cid

    MimeBodyPart insta = new MimeBodyPart();
    // attach the file to the message
    source = new FileDataSource(new File(path + "/webapps/Images/Email/instaIcon.png"));
    insta.setDataHandler(new DataHandler(source));
    insta.setFileName("instaIcon.png");
    insta.setDisposition(MimeBodyPart.INLINE);
    insta.setHeader("Content-ID", "<insta_Icon>"); // cid:image_cid

    MimeBodyPart youtube = new MimeBodyPart();
    // attach the file to the message
    source = new FileDataSource(new File(path + "/webapps/Images/Email/youtubeIcon.png"));
    youtube.setDataHandler(new DataHandler(source));
    youtube.setFileName("youtubeIcon.png");
    youtube.setDisposition(MimeBodyPart.INLINE);
    youtube.setHeader("Content-ID", "<yt_Icon>"); // cid:image_cid

    MimeBodyPart pinterest = new MimeBodyPart();
    // attach the file to the message
    source = new FileDataSource(new File(path + "/webapps/Images/Email/pinterestIcon.png"));
    pinterest.setDataHandler(new DataHandler(source));
    pinterest.setFileName("pinterestIcon.png");
    pinterest.setDisposition(MimeBodyPart.INLINE);
    pinterest.setHeader("Content-ID", "<pin_Icon>"); // cid:image_cid

    String content = "<div style=' width: 507px;background-color: #f2f2f4;'>"
            + "    <div style='padding: 30px 0;text-align: center; color: #fff; background-color: #ff514e;font-size: 30px;font-weight: bold;'>"
            + "        <img style=' text-align:center;' width=57 height=57 src='cid:logo_Icon'/>"
            + "        <p style='margin:25px 0px 0px 0px;'> Package Approved! </p>" + "    </div>"
            + "    <div style=' padding: 50px;margin-bottom: 20px;'>" + "        <div id='email-form'>"
            + "            <div style='margin-bottom: 20px'>" + "                Hi " + emailData.getLastName()
            + " ,<br/>" + "                Your package " + emailData.getLastestPackageName()
            + " has been approved" + "            </div>" + "            <div style='margin-bottom: 20px'>"
            + "                Thanks,<br/>" + "                Youtripper team\n" + "            </div>"
            + "        </div>" + "        <div style='border-top: solid 1px #c4c5cc;text-align:center;'>"
            + "            <p style='text-align: center; color: #3b3e53;margin-top: 10px;margin-bottom: 0px;font-size: 10px;'>Sent from Youtripper.com</p>"
            + "            <div>"
            + "                <a href='https://www.facebook.com/youtrippers/'><img style='margin:10px;' src='cid:fb_Icon' alt=''/></a>"
            + "                <a href='https://twitter.com/youtrippers'><img style='margin:10px;' src='cid:twitter_Icon' alt=''/></a>"
            + "                <a href='https://www.instagram.com/youtrippers/'><img style='margin:10px;' src='cid:insta_Icon' alt=''/></a>"
            + "                <a href='https://www.youtube.com/channel/UCtd4xd_SSjRR9Egug7tXIWA'><img style='margin:10px;' src='cid:yt_Icon' alt=''/></a>"
            + "                <a href='https://www.pinterest.com/youtrippers/'><img style='margin:10px;' src='cid:pin_Icon' alt=''/></a>"
            + "            </div>"
            + "            <p>Youtripper Ltd., 56 Soi Seri Villa, Srinakarin Rd., Nongbon,"
            + "                <br>Pravet, Bangkok, Thailand 10250</p>" + "        </div>" + "    </div>"
            + "</div>";

    MimeBodyPart mbp1 = new MimeBodyPart();
    mbp1.setText(content, "US-ASCII", "html");

    Multipart mp = new MimeMultipart("related");
    mp.addBodyPart(mbp1);//  ww  w.  ja  v a  2 s  . co m
    mp.addBodyPart(logo);
    mp.addBodyPart(facebook);
    mp.addBodyPart(twitter);
    mp.addBodyPart(insta);
    mp.addBodyPart(youtube);
    mp.addBodyPart(pinterest);

    final String username = "noreply@youtripper.com";
    final String password = "Tripper190515";
    Properties props = new Properties();
    props.put("mail.smtp.auth", "true");
    props.put("mail.smtp.starttls.enable", "true");
    props.put("mail.smtp.host", "mail.youtripper.com");

    Session session = Session.getInstance(props, new javax.mail.Authenticator() {
        protected PasswordAuthentication getPasswordAuthentication() {
            return new PasswordAuthentication(username, password);
        }
    });

    Message message = new MimeMessage(session);
    message.setFrom(new InternetAddress("noreply@youtripper.com"));
    message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(emailData.getEmail()));
    message.setSubject("Package Approved!");
    message.setContent(mp);
    message.saveChanges();
    Transport.send(message);
    return true;
}

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

@Test
public void testRequestCertificateInvalidOriginator() throws Exception {
    MockMailetConfig mailetConfig = new MockMailetConfig();

    RequestSenderCertificate mailet = new RequestSenderCertificate();

    mailet.init(mailetConfig);/*from w w w. j  av  a 2 s. com*/

    MockMail mail = new MockMail();

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

    String to = "to@example.com";

    message.setContent("test", "text/plain");
    message.setFrom(new InternetAddress("123"));

    message.saveChanges();

    mail.setMessage(message);

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

    recipients.add(new MailAddress(to));

    mail.setRecipients(recipients);

    mail.setSender(null);

    assertFalse(proxy.isUser(EmailAddressUtils.INVALID_EMAIL));
    assertFalse(proxy.isUser(to));

    mailet.service(mail);

    assertEquals(INITIAL_KEY_STORE_SIZE, proxy.getKeyAndCertStoreSize());

    assertFalse(proxy.isUser(to));
    assertFalse(proxy.isUser(EmailAddressUtils.INVALID_EMAIL));
}

From source file:com.eviware.soapui.impl.support.AbstractMockResponse.java

public String writeResponse(MockResult result, String responseContent) throws Exception {
    MimeMultipart mp = null;/*  w ww . ja  v a 2 s. c  o  m*/

    Operation operation = getMockOperation().getOperation();

    // variables needed for both multipart sections....
    boolean isXOP = isMtomEnabled() && isForceMtom();
    StringToStringMap contentIds = new StringToStringMap();

    // only support multipart for wsdl currently.....
    if (operation instanceof WsdlOperation) {
        if (operation == null) {
            throw new IllegalStateException("Missing WsdlOperation for mock response");
        }

        // preprocess only if neccessary
        if (isMtomEnabled() || isInlineFilesEnabled() || getAttachmentCount() > 0) {
            try {
                mp = new MimeMultipart();

                WsdlOperation wsdlOperation = ((WsdlOperation) operation);
                MessageXmlObject requestXmlObject = createMessageXmlObject(responseContent, wsdlOperation);
                MessageXmlPart[] requestParts = requestXmlObject.getMessageParts();
                for (MessageXmlPart requestPart : requestParts) {
                    if (prepareMessagePart(mp, contentIds, requestPart)) {
                        isXOP = true;
                    }
                }
                responseContent = requestXmlObject.getMessageContent();
            } catch (Exception e) {
                SoapUI.logError(e);
            }
        }

        responseContent = removeEmptyContent(responseContent);
    }

    if (isStripWhitespaces()) {
        responseContent = XmlUtils.stripWhitespaces(responseContent);
    }

    MockRequest request = result.getMockRequest();
    request.getHttpResponse().setStatus(this.getResponseHttpStatus());

    ByteArrayOutputStream outData = new ByteArrayOutputStream();

    // non-multipart request?
    String responseCompression = getResponseCompression();
    if (!isXOP && (mp == null || mp.getCount() == 0) && getAttachmentCount() == 0) {
        String encoding = getEncoding();
        if (responseContent == null) {
            responseContent = "";
        }

        byte[] content = encoding == null ? responseContent.getBytes() : responseContent.getBytes(encoding);

        if (!result.getResponseHeaders().containsKeyIgnoreCase("Content-Type")) {
            result.setContentType(getContentType());
        }

        String acceptEncoding = result.getMockRequest().getRequestHeaders().get("Accept-Encoding", "");
        if (AUTO_RESPONSE_COMPRESSION.equals(responseCompression) && acceptEncoding != null
                && acceptEncoding.toUpperCase().contains("GZIP")) {
            if (!headerExists("Content-Encoding", "gzip", result)) {
                result.addHeader("Content-Encoding", "gzip");
            }
            outData.write(CompressionSupport.compress(CompressionSupport.ALG_GZIP, content));
        } else if (AUTO_RESPONSE_COMPRESSION.equals(responseCompression) && acceptEncoding != null
                && acceptEncoding.toUpperCase().contains("DEFLATE")) {
            result.addHeader("Content-Encoding", "deflate");
            outData.write(CompressionSupport.compress(CompressionSupport.ALG_DEFLATE, content));
        } else {
            outData.write(content);
        }
    } else // won't get here if rest at the moment...
    {
        // make sure..
        if (mp == null) {
            mp = new MimeMultipart();
        }

        // init root part
        initRootPart(responseContent, mp, isXOP);

        // init mimeparts
        AttachmentUtils.addMimeParts(this, Arrays.asList(getAttachments()), mp, contentIds);

        // create request message
        MimeMessage message = new MimeMessage(AttachmentUtils.JAVAMAIL_SESSION);
        message.setContent(mp);
        message.saveChanges();
        MimeMessageMockResponseEntity mimeMessageRequestEntity = new MimeMessageMockResponseEntity(message,
                isXOP, this);

        result.addHeader("Content-Type", mimeMessageRequestEntity.getContentType().getValue());
        result.addHeader("MIME-Version", "1.0");
        mimeMessageRequestEntity.writeTo(outData);
    }

    if (outData.size() > 0) {
        byte[] data = outData.toByteArray();

        if (responseCompression.equals(CompressionSupport.ALG_DEFLATE)
                || responseCompression.equals(CompressionSupport.ALG_GZIP)) {
            result.addHeader("Content-Encoding", responseCompression);
            data = CompressionSupport.compress(responseCompression, data);
        }
        if (result.getResponseHeaders().get("Transfer-Encoding") == null) {
            result.addHeader("Content-Length", "" + data.length);
        }
        result.writeRawResponseData(data);
    }

    return responseContent;
}