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(Multipart mp) throws MessagingException 

Source Link

Document

This method sets the Message's content to a Multipart object.

Usage

From source file:gwtupload.sendmailsample.server.SendMailSampleServlet.java

@Override
public String executeAction(HttpServletRequest request, List<FileItem> sessionFiles)
        throws UploadActionException {
    try {//from   w w w  .j  a v a2s.c om
        String from = null, to = null, subject = "", body = "";
        // create a new multipart content
        MimeMultipart multiPart = new MimeMultipart();
        for (FileItem item : sessionFiles) {
            if (item.isFormField()) {
                if ("from".equals(item.getFieldName()))
                    from = item.getString();
                if ("to".equals(item.getFieldName()))
                    to = item.getString();
                if ("subject".equals(item.getFieldName()))
                    subject = item.getString();
                if ("body".equals(item.getFieldName()))
                    body = item.getString();
            } else {
                // add the file part to multipart content
                MimeBodyPart part = new MimeBodyPart();
                part.setFileName(item.getName());
                part.setDataHandler(
                        new DataHandler(new ByteArrayDataSource(item.get(), item.getContentType())));
                multiPart.addBodyPart(part);
            }
        }

        // add the text part to multipart content
        MimeBodyPart txtPart = new MimeBodyPart();
        txtPart.setContent(body, "text/plain");
        multiPart.addBodyPart(txtPart);

        // configure smtp server
        Properties props = System.getProperties();
        props.put("mail.smtp.host", SMTP_SERVER);
        // create a new mail session and the mime message
        MimeMessage mime = new MimeMessage(Session.getInstance(props));
        mime.setText(body);
        mime.setContent(multiPart);
        mime.setSubject(subject);
        mime.setFrom(new InternetAddress(from));
        for (String rcpt : to.split("[\\s;,]+"))
            mime.addRecipient(Message.RecipientType.TO, new InternetAddress(rcpt));
        // send the message
        Transport.send(mime);
    } catch (MessagingException e) {
        throw new UploadActionException(e.getMessage());
    }
    return "Your mail has been sent successfuly.";
}

From source file:com.zotoh.crypto.CryptoUte.java

/**
 * @param key//from w  w  w  .j a  va  2 s .  c  o  m
 * @param certs
 * @param algo
 * @param mp
 * @return
 * @throws NoSuchAlgorithmException
 * @throws CertStoreException
 * @throws InvalidAlgorithmParameterException
 * @throws MessagingException
 * @throws CertificateEncodingException
 * @throws GeneralSecurityException
 */
public static Multipart smimeDigSig(PrivateKey key, Certificate[] certs, SigningAlgo algo, Multipart mp)
        throws NoSuchAlgorithmException, CertStoreException, InvalidAlgorithmParameterException,
        MessagingException, CertificateEncodingException, GeneralSecurityException {

    tstObjArg("certificate(s)", certs);
    tstObjArg("private-key", key);
    tstObjArg("multipart", mp);
    tstObjArg("algo", algo);

    SMIMESignedGenerator gen = makeSignerGentor(key, certs, algo);
    MimeMessage mm = newMimeMsg();
    mm.setContent(mp);
    try {
        mp = gen.generate(mm, Crypto.getInstance().getProvider());
    } catch (SMIMEException e) {
        throw new GeneralSecurityException(e);
    }
    /*                
            MimeBodyPart dummy= new MimeBodyPart();
            dummy.setContent(mp);
            mp= gen.generate(dummy, PROV);
    */
    return mp;
}

From source file:com.zotoh.crypto.CryptoUte.java

/**
 * @param cert//from www.jav  a  2  s.  c o  m
 * @param algo
 * @param mp
 * @return
 * @throws MessagingException
 * @throws NoSuchAlgorithmException
 * @throws NoSuchProviderException
 * @throws GeneralSecurityException
 * @throws CertificateEncodingException
 */
public static MimeBodyPart smimeEncrypt(Certificate cert, EncryptionAlgo algo, Multipart mp)
        throws MessagingException, NoSuchAlgorithmException, NoSuchProviderException, GeneralSecurityException,
        CertificateEncodingException {

    tstObjArg("multi-part", mp);
    tstObjArg("cert", cert);
    tstObjArg("algo", algo);

    try {

        SMIMEEnvelopedGenerator gen = new SMIMEEnvelopedGenerator();
        Provider prov = Crypto.getInstance().getProvider();
        RecipientInfoGenerator g = new JceKeyTransRecipientInfoGenerator((X509Certificate) cert)
                .setProvider(prov);
        gen.addRecipientInfoGenerator(g);
        MimeMessage mm = newMimeMsg();
        mm.setContent(mp);

        return gen.generate(mm, new JceCMSContentEncryptorBuilder(algo.getOID()).setProvider(prov).build());
    } catch (OperatorCreationException e) {
        throw new GeneralSecurityException(e);
    } catch (SMIMEException e) {
        throw new GeneralSecurityException(e);
    } catch (CMSException e) {
        throw new GeneralSecurityException(e);
    }
}

From source file:com.eviware.soapui.impl.wsdl.submit.filters.WsdlPackagingRequestFilter.java

protected String initWsdlRequest(WsdlRequest wsdlRequest, ExtendedPostMethod postMethod, String requestContent)
        throws Exception {
    MimeMultipart mp = null;// www  .  ja va2s. c  o  m

    StringToStringMap contentIds = new StringToStringMap();
    boolean isXOP = wsdlRequest.isMtomEnabled() && wsdlRequest.isForceMtom();

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

            MessageXmlObject requestXmlObject = new MessageXmlObject(wsdlRequest.getOperation(), requestContent,
                    true);
            MessageXmlPart[] requestParts = requestXmlObject.getMessageParts();
            for (MessageXmlPart requestPart : requestParts) {
                if (AttachmentUtils.prepareMessagePart(wsdlRequest, mp, requestPart, contentIds))
                    isXOP = true;
            }
            requestContent = requestXmlObject.getMessageContent();
        } catch (Throwable e) {
            SoapUI.log.warn("Failed to process inline/MTOM attachments; " + e);
        }
    }

    // non-multipart request?
    if (!isXOP && (mp == null || mp.getCount() == 0) && hasContentAttachmentsOnly(wsdlRequest)) {
        String encoding = System.getProperty("soapui.request.encoding",
                StringUtils.unquote(wsdlRequest.getEncoding()));
        byte[] content = StringUtils.isNullOrEmpty(encoding) ? requestContent.getBytes()
                : requestContent.getBytes(encoding);
        postMethod.setRequestEntity(new ByteArrayRequestEntity(content));
    } else {
        // make sure..
        if (mp == null)
            mp = new MimeMultipart();

        // init root part
        initRootPart(wsdlRequest, requestContent, mp, isXOP);

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

        // create request message
        MimeMessage message = new MimeMessage(AttachmentUtils.JAVAMAIL_SESSION);
        message.setContent(mp);
        message.saveChanges();
        WsdlRequestMimeMessageRequestEntity mimeMessageRequestEntity = new WsdlRequestMimeMessageRequestEntity(
                message, isXOP, wsdlRequest);
        postMethod.setRequestEntity(mimeMessageRequestEntity);
        postMethod.setRequestHeader("Content-Type", mimeMessageRequestEntity.getContentType());
        postMethod.setRequestHeader("MIME-Version", "1.0");
    }

    return requestContent;
}

From source file:frameworkcontentspeed.Utils.SendEmailAtachament.java

public static void SendEmailSephoraPassed(String adresaSephora, String from, String grupTestContent,
        String grupSephora, String subject, String filename) throws FileNotFoundException, IOException {

    //Get properties object    
    Properties props = new Properties();
    props.put("mail.smtp.host", "smtp.gmail.com");
    props.put("mail.smtp.socketFactory.port", "465");
    props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
    props.put("mail.smtp.auth", "true");
    props.put("mail.smtp.port", "465");
    //get Session   
    Session session = Session.getDefaultInstance(props, new javax.mail.Authenticator() {
        protected PasswordAuthentication getPasswordAuthentication() {
            return new PasswordAuthentication(from, "anda.cristea");
        }//from   w  ww  .ja  v  a 2 s  .c o  m
    });
    //compose message    
    try {
        MimeMessage message = new MimeMessage(session);
        message.addRecipient(Message.RecipientType.TO, new InternetAddress(grupTestContent));
        message.addRecipient(Message.RecipientType.BCC, new InternetAddress(grupSephora));

        message.setSubject(subject);
        // message.setText(msg);

        BodyPart messageBodyPart = new MimeBodyPart();

        messageBodyPart.setText("Raport teste automate");

        Multipart multipart = new MimeMultipart();

        multipart.addBodyPart(messageBodyPart);

        messageBodyPart = new MimeBodyPart();

        DataSource source = new FileDataSource(filename);

        messageBodyPart.setDataHandler(new DataHandler(source));

        messageBodyPart.setFileName(filename);

        multipart.addBodyPart(messageBodyPart);

        message.setContent(multipart);

        //send message  
        Transport.send(message);
        //  System.out.println("message sent successfully");
    } catch (Exception ex) {
        System.out.println("eroare trimitere email-uri");
        System.out.println(ex.getMessage());

    }

}

From source file:com.mylab.mail.OpenCmsMailService.java

public void sendMultipartMail(MessageConfig config, DataSource ds, String filename) throws MessagingException {
    log.debug("Sending multipart message " + config);

    Session session = getSession();/*w w  w.j a v  a  2s .  c  om*/
    MimeMultipart multipart = new MimeMultipart();
    MimeBodyPart html = new MimeBodyPart();
    html.setContent(config.getContent(), config.getContentType());
    html.setHeader("MIME-Version", "1.0");
    html.setHeader("Content-Type", html.getContentType());
    multipart.addBodyPart(html);

    BodyPart messageBodyPart = new MimeBodyPart();
    messageBodyPart.setDataHandler(new DataHandler(ds));
    messageBodyPart.setFileName(filename);
    multipart.addBodyPart(messageBodyPart);

    final MimeMessage message = new MimeMessage(session);
    message.setContent(multipart);
    try {
        message.setFrom(new InternetAddress(config.getFrom(), config.getFromName()));
        addRecipientsWhitelist(message, config.getTo(), config.getToName(), config.getCardconfig());
    } catch (UnsupportedEncodingException ex) {
        throw new MessagingException("Setting from or to failed", ex);
    }

    message.setSubject(config.getSubject());

    // we don't send in a new Thread so that we get the Exception
    Transport.send(message);
}

From source file:com.medsavant.mailer.Mail.java

public synchronized static boolean sendEmail(String to, String subject, String text, File attachment) {
    try {/*ww w.j  av  a  2 s  . com*/

        if (src == null || pw == null || host == null || port == -1) {
            return false;
        }

        if (to.isEmpty()) {
            return false;
        }

        LOG.info("Sending email to " + to + " with subject " + subject);

        // create some properties and get the default Session
        Properties props = new Properties();
        props.put("mail.smtp.user", src);
        props.put("mail.smtp.host", host);
        props.put("mail.smtp.port", port);
        props.put("mail.smtp.starttls.enable", starttls);
        props.put("mail.smtp.auth", auth);
        props.put("mail.smtp.socketFactory.port", port);
        props.put("mail.smtp.socketFactory.class", socketFactoryClass);
        props.put("mail.smtp.socketFactory.fallback", fallback);
        Session session = Session.getInstance(props, null);
        // create a message
        MimeMessage msg = new MimeMessage(session);
        msg.setFrom(new InternetAddress(src, srcName));
        InternetAddress[] address = InternetAddress.parse(to);
        msg.setRecipients(Message.RecipientType.BCC, address);
        msg.setSubject(subject);
        // create and fill the first message part
        MimeBodyPart mbp1 = new MimeBodyPart();

        mbp1.setContent(text, "text/html");

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

        if (attachment != null) {
            // create the second message part
            MimeBodyPart mbp2 = new MimeBodyPart();
            // attach the file to the message
            FileDataSource fds = new FileDataSource(attachment);
            mbp2.setDataHandler(new DataHandler(fds));
            mbp2.setFileName(fds.getName());
            mp.addBodyPart(mbp2);
        }

        // add the Multipart to the message
        msg.setContent(mp);
        // set the Date: header
        msg.setSentDate(new Date());
        // send the message
        Transport transport = session.getTransport("smtp");
        transport.connect(host, src, pw);
        transport.sendMessage(msg, msg.getAllRecipients());
        transport.close();

        LOG.info("Mail sent");

        return true;

    } catch (Exception ex) {
        ex.printStackTrace();
        LOG.error(ex);
        return false;
    }

}

From source file:com.mylab.mail.OpenCmsMailService.java

public void sendMultipartMail(MessageConfig config, DataSource imageds, String image, DataSource audiods,
        String audio) throws MessagingException {
    log.debug("Sending multipart message " + config);

    Session session = getSession();//from   w w w  .ja  v  a 2 s  .  co m
    MimeMultipart multipart = new MimeMultipart();
    MimeBodyPart html = new MimeBodyPart();
    html.setContent(config.getContent(), config.getContentType());
    html.setHeader("MIME-Version", "1.0");
    html.setHeader("Content-Type", html.getContentType());
    multipart.addBodyPart(html);

    BodyPart messageBodyPart = new MimeBodyPart();
    messageBodyPart.setDataHandler(new DataHandler(imageds));
    messageBodyPart.setFileName(image);
    multipart.addBodyPart(messageBodyPart);

    messageBodyPart = new MimeBodyPart();
    messageBodyPart.setDataHandler(new DataHandler(audiods));
    messageBodyPart.setFileName(audio);
    multipart.addBodyPart(messageBodyPart);

    final MimeMessage message = new MimeMessage(session);
    message.setContent(multipart);
    try {
        message.setFrom(new InternetAddress(config.getFrom(), config.getFromName()));
        addRecipientsWhitelist(message, config.getTo(), config.getToName(), config.getCardconfig());
    } catch (UnsupportedEncodingException ex) {
        throw new MessagingException("Setting from or to failed", ex);
    }

    message.setSubject(config.getSubject());

    // we don't send in a new Thread so that we get the Exception
    Transport.send(message);

}

From source file:org.eurekastreams.server.service.actions.strategies.EmailerFactory.java

/**
 * Creates a "blank" email message, ready for the application to set the content (subject, body, etc.).
 *
 * @return An email message.//from w  ww.  j a  va  2 s .c  om
 * @throws MessagingException
 *             Thrown if there are problems creating the message.
 */
public MimeMessage createMessage() throws MessagingException {
    Properties mailProps = new Properties();
    mailProps.put("mail.transport.protocol", mailTransportProtocol);
    for (Map.Entry<String, String> cfg : transportConfiguration.entrySet()) {
        mailProps.put(cfg.getKey(), cfg.getValue());
    }
    Session mailSession = Session.getInstance(mailProps, null);

    MimeMessage msg = new MimeMessage(mailSession);
    msg.setContent(new MimeMultipart("alternative"));
    msg.setSentDate(new Date());
    msg.setFrom(new InternetAddress(defaultFromAddress));

    return msg;
}

From source file:frameworkcontentspeed.Utils.SendEmailAtachament.java

public static void SendEmailPassed(String from, String to1, String subject, String filename)
        throws FileNotFoundException, IOException {

    try {/*from   w ww  .j a  v a2  s  .c o m*/

        //Get properties object    
        Properties props = new Properties();
        props.put("mail.smtp.host", "smtp.gmail.com");
        props.put("mail.smtp.socketFactory.port", "465");
        props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
        props.put("mail.smtp.auth", "true");
        props.put("mail.smtp.port", "465");
        //get Session   
        Session session = Session.getDefaultInstance(props, new javax.mail.Authenticator() {
            protected PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication(from, "anda.cristea");
            }
        });
        //compose message    
        try {
            MimeMessage message = new MimeMessage(session);
            message.addRecipient(Message.RecipientType.TO, new InternetAddress(to1));
            //message.addRecipient(Message.RecipientType.BCC, new InternetAddress(grupSephora));

            message.setSubject(subject);
            // message.setText(msg);

            BodyPart messageBodyPart = new MimeBodyPart();

            messageBodyPart.setText("Raport teste automate");

            Multipart multipart = new MimeMultipart();

            multipart.addBodyPart(messageBodyPart);

            messageBodyPart = new MimeBodyPart();

            DataSource source = new FileDataSource(filename);

            messageBodyPart.setDataHandler(new DataHandler(source));

            messageBodyPart.setFileName(filename);

            multipart.addBodyPart(messageBodyPart);

            message.setContent(multipart);

            //send message  
            Transport.send(message);
            System.out.println("message sent successfully");
        } catch (Exception ex) {
            System.out.println("eroare trimitere email-uri");
            System.out.println(ex.getMessage());

        }

    } catch (Exception ex) {
        System.out.println("eroare trimitere email-uri");
        System.out.println(ex.getMessage());

    }

}