Example usage for javax.mail.internet MimeBodyPart setFileName

List of usage examples for javax.mail.internet MimeBodyPart setFileName

Introduction

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

Prototype

@Override
public void setFileName(String filename) throws MessagingException 

Source Link

Document

Set the filename associated with this body part, if possible.

Usage

From source file:rescustomerservices.GmailQuickstart.java

/**
 * Create a MimeMessage using the parameters provided.
 *
 * @param to Email address of the receiver.
 * @param from Email address of the sender, the mailbox account.
 * @param subject Subject of the email./*from ww w.  j ava  2 s  .  c  o  m*/
 * @param bodyText Body text of the email.
 * @param fileDir Path to the directory containing attachment.
 * @param filename Name of file to be attached.
 * @return MimeMessage to be used to send email.
 * @throws MessagingException
 */
public MimeMessage createEmailWithAttachment(String to, String from, String subject, String bodyText,
        String fileDir, String filename) throws MessagingException, IOException {
    Properties props = new Properties();
    Session session = Session.getDefaultInstance(props, null);

    MimeMessage email = new MimeMessage(session);
    InternetAddress tAddress = new InternetAddress(to);
    InternetAddress fAddress = new InternetAddress(from);

    email.setFrom(fAddress);
    email.addRecipient(javax.mail.Message.RecipientType.TO, tAddress);
    email.setSubject(subject);

    MimeBodyPart mimeBodyPart = new MimeBodyPart();
    mimeBodyPart.setContent(bodyText, "text/plain");
    mimeBodyPart.setHeader("Content-Type", "text/plain; charset=\"UTF-8\"");

    Multipart multipart = new MimeMultipart();
    multipart.addBodyPart(mimeBodyPart);

    mimeBodyPart = new MimeBodyPart();
    DataSource source = new FileDataSource(fileDir + filename);

    mimeBodyPart.setDataHandler(new DataHandler(source));
    mimeBodyPart.setFileName(filename);
    String contentType = Files.probeContentType(FileSystems.getDefault().getPath(fileDir, filename));
    mimeBodyPart.setHeader("Content-Type", contentType + "; name=\"" + filename + "\"");
    mimeBodyPart.setHeader("Content-Transfer-Encoding", "base64");

    multipart.addBodyPart(mimeBodyPart);

    email.setContent(multipart);

    return email;
}

From source file:org.igov.io.mail.Mail.java

public Mail _Attach(URL oURL, String sName) {
    try {//  ww  w. j  ava2s  .  c  o m
        MimeBodyPart oMimeBodyPart = new MimeBodyPart();//javax.activation
        oMimeBodyPart.setHeader("Content-Type", "multipart/mixed");
        DataSource oDataSource = new URLDataSource(oURL);
        oMimeBodyPart.setDataHandler(new DataHandler(oDataSource));
        //oPart.setFileName(MimeUtility.encodeText(source.getName()));
        oMimeBodyPart.setFileName(
                MimeUtility.encodeText(sName == null || "".equals(sName) ? oDataSource.getName() : sName));
        oMultiparts.addBodyPart(oMimeBodyPart);
        LOG.info("(sName={})", sName);
    } catch (Exception oException) {
        LOG.error("FAIL: {} (sName={})", oException.getMessage(), sName);
        LOG.trace("FAIL:", oException);
    }
    return this;
}

From source file:com.autentia.tnt.mail.DefaultMailService.java

public void sendOutputStreams(String to, String subject, String text, Map<InputStream, String> attachments)
        throws MessagingException {
    Transport t = null;//from w w w. j  a  va 2 s .  c om

    try {
        MimeMessage message = new MimeMessage(session);

        t = session.getTransport("smtp");

        message.setFrom(new InternetAddress(configurationUtil.getMailUsername()));
        message.addRecipient(Message.RecipientType.TO, new InternetAddress(to));
        message.setSubject(subject);
        message.setSentDate(new Date());
        if (attachments == null || attachments.size() < 1) {
            message.setText(text);
        } else {
            // create the message part 
            MimeBodyPart messageBodyPart = new MimeBodyPart();
            messageBodyPart.setText(text);
            Multipart multipart = new MimeMultipart();
            multipart.addBodyPart(messageBodyPart);
            try {
                for (InputStream attachment : attachments.keySet()) {
                    messageBodyPart = new MimeBodyPart();
                    DataSource source = new ByteArrayDataSource(attachment, "application/octet-stream");

                    messageBodyPart.setDataHandler(new DataHandler(source));
                    messageBodyPart.setFileName(attachments.get(attachment)); //NOSONAR 
                    multipart.addBodyPart(messageBodyPart); //Se emplea keyset y no valueset porque se emplea tanto la key como el val
                }
            } catch (IOException e) {
                throw new MessagingException("cannot add an attachment to mail", e);
            }
            message.setContent(multipart);
        }

        t.connect(configurationUtil.getMailUsername(), configurationUtil.getMailPassword());

        t.sendMessage(message, message.getAllRecipients());
    } finally {
        if (t != null) {
            t.close();
        }
    }

}

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

public boolean dispatch(BIObject document, byte[] executionOutput) {

    String contentType;/*from w w  w . j  av  a  2 s .c  o  m*/
    String fileExtension;
    String nameSuffix;
    JobExecutionContext jobExecutionContext;

    logger.debug("IN");

    try {

        contentType = dispatchContext.getContentType();
        fileExtension = dispatchContext.getFileExtension();
        nameSuffix = dispatchContext.getNameSuffix();
        jobExecutionContext = dispatchContext.getJobExecutionContext();

        //Custom Trusted Store Certificate Options
        String trustedStorePath = SingletonConfig.getInstance()
                .getConfigValue("MAIL.PROFILES.trustedStore.file");
        String trustedStorePassword = SingletonConfig.getInstance()
                .getConfigValue("MAIL.PROFILES.trustedStore.password");

        String smtphost = SingletonConfig.getInstance().getConfigValue("MAIL.PROFILES.scheduler.smtphost");
        String smtpport = SingletonConfig.getInstance().getConfigValue("MAIL.PROFILES.scheduler.smtpport");
        String smtpssl = SingletonConfig.getInstance().getConfigValue("MAIL.PROFILES.scheduler.useSSL");
        logger.debug(smtphost + " " + smtpport + " use SSL: " + smtpssl);

        if ((smtphost == null) || smtphost.trim().equals(""))
            throw new Exception("Smtp host not configured");
        String from = SingletonConfig.getInstance().getConfigValue("MAIL.PROFILES.scheduler.from");
        if ((from == null) || from.trim().equals(""))
            from = "spagobi.scheduler@eng.it";

        int smptPort = 25;

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

        String user = SingletonConfig.getInstance().getConfigValue("MAIL.PROFILES.scheduler.user");
        String pass = SingletonConfig.getInstance().getConfigValue("MAIL.PROFILES.scheduler.password");

        /*
        if( (user==null) || user.trim().equals(""))
           throw new Exception("Smtp user not configured");
                
        if( (pass==null) || pass.trim().equals(""))
           throw new Exception("Smtp password not configured");
        */

        String mailTos = "";
        List dlIds = dispatchContext.getDlIds();
        Iterator it = dlIds.iterator();
        while (it.hasNext()) {

            Integer dlId = (Integer) it.next();
            DistributionList dl = DAOFactory.getDistributionListDAO().loadDistributionListById(dlId);

            List emails = new ArrayList();
            emails = dl.getEmails();
            Iterator j = emails.iterator();
            while (j.hasNext()) {
                Email e = (Email) j.next();
                String email = e.getEmail();
                String userTemp = e.getUserId();
                IEngUserProfile userProfile = GeneralUtilities.createNewUserProfile(userTemp);
                if (ObjectsAccessVerifier.canSee(document, userProfile)) {
                    if (j.hasNext()) {
                        mailTos = mailTos + email + ",";
                    } else {
                        mailTos = mailTos + email;
                    }
                }

            }
        }

        if ((mailTos == null) || mailTos.trim().equals("")) {
            throw new Exception("No recipient address found");
        }

        String[] recipients = mailTos.split(",");
        //Set the host smtp address
        Properties props = new Properties();
        props.put("mail.smtp.host", smtphost);
        props.put("mail.smtp.port", Integer.toString(smptPort));

        Session session = null;

        if (StringUtilities.isEmpty(user) || StringUtilities.isEmpty(pass)) {
            props.put("mail.smtp.auth", "false");
            session = Session.getInstance(props);
            logger.debug("Connecting to mail server without authentication");
        } else {
            props.put("mail.smtp.auth", "true");
            Authenticator auth = new SMTPAuthenticator(user, pass);
            //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(smptPort));
                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.getInstance(props, auth);
            logger.debug("Connecting to mail server with authentication");
        }

        // 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
        IMessageBuilder msgBuilder = MessageBuilderFactory.getMessageBuilder();
        String subject = document.getName() + nameSuffix;
        msg.setSubject(subject);
        // create and fill the first message part
        //MimeBodyPart mbp1 = new MimeBodyPart();
        //mbp1.setText(mailTxt);
        // create the second message part
        MimeBodyPart mbp2 = new MimeBodyPart();
        // attach the file to the message
        SchedulerDataSource sds = new SchedulerDataSource(executionOutput, contentType,
                document.getName() + nameSuffix + fileExtension);
        mbp2.setDataHandler(new DataHandler(sds));
        mbp2.setFileName(sds.getName());
        // create the Multipart and add its parts to it
        Multipart mp = new MimeMultipart();
        //mp.addBodyPart(mbp1);
        mp.addBodyPart(mbp2);
        // add the Multipart to the message
        msg.setContent(mp);
        // send message
        if ((smtpssl.equals("true")) && (!StringUtilities.isEmpty(user)) && (!StringUtilities.isEmpty(pass))) {
            //USE SSL Transport comunication with SMTPS
            Transport transport = session.getTransport("smtps");
            transport.connect(smtphost, smptPort, user, pass);
            transport.sendMessage(msg, msg.getAllRecipients());
            transport.close();
        } else {
            //Use normal SMTP
            Transport.send(msg);
        }

        if (jobExecutionContext.getNextFireTime() == null) {
            String triggername = jobExecutionContext.getTrigger().getName();
            dlIds = dispatchContext.getDlIds();
            it = dlIds.iterator();
            while (it.hasNext()) {
                Integer dlId = (Integer) it.next();
                DistributionList dl = DAOFactory.getDistributionListDAO().loadDistributionListById(dlId);
                DAOFactory.getDistributionListDAO().eraseDistributionListObjects(dl,
                        (document.getId()).intValue(), triggername);
            }
        }
    } catch (Exception e) {
        logger.error("Error while sending schedule result mail", e);
        return false;
    } finally {
        logger.debug("OUT");
    }

    return true;
}

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;//  w w w . j ava2s.c  om
    }

    /*
     * 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.xwiki.commons.internal.DefaultMailSender.java

private MimeBodyPart createAttachmentPart(Attachment attachment) {
    try {/*from w  w w.  j  a  v a  2s . co  m*/
        String name = attachment.getFilename();
        byte[] stream = attachment.getContent();
        File temp = File.createTempFile("tmpfile", ".tmp");
        FileOutputStream fos = new FileOutputStream(temp);
        fos.write(stream);
        fos.close();
        DataSource source = new FileDataSource(temp);
        MimeBodyPart part = new MimeBodyPart();
        String mimeType = MimeTypesUtil.getMimeTypeFromFilename(name);

        part.setDataHandler(new DataHandler(source));
        part.setHeader("Content-Type", mimeType);
        part.setFileName(name);
        part.setContentID("<" + name + ">");
        part.setDisposition("inline");

        temp.deleteOnExit();
        return part;
    } catch (Exception e) {
        return new MimeBodyPart();
    }
}

From source file:org.ktunaxa.referral.server.command.email.SendEmailCommand.java

public void execute(final SendEmailRequest request, final SendEmailResponse response) throws Exception {
    final String from = request.getFrom();
    if (null == from) {
        throw new GeomajasException(ExceptionCode.PARAMETER_MISSING, "from");
    }//from  w  w  w .  j  a  v a 2  s. c om
    final String to = request.getTo();
    if (null == to) {
        throw new GeomajasException(ExceptionCode.PARAMETER_MISSING, "to");
    }

    response.setSuccess(false);
    final List<HttpGet> attachmentConnections = new ArrayList<HttpGet>();
    MimeMessagePreparator preparator = new MimeMessagePreparator() {

        public void prepare(MimeMessage mimeMessage) throws Exception {
            log.debug("Build mime message");

            addRecipients(mimeMessage, Message.RecipientType.TO, to);
            addRecipients(mimeMessage, Message.RecipientType.CC, request.getCc());
            addRecipients(mimeMessage, Message.RecipientType.BCC, request.getBcc());
            addReplyTo(mimeMessage, request.getReplyTo());
            mimeMessage.setFrom(new InternetAddress(from));
            mimeMessage.setSubject(request.getSubject());
            // mimeMessage.setText(request.getText());

            List<String> attachments = request.getAttachmentUrls();
            MimeMultipart mp = new MimeMultipart();
            MimeBodyPart mailBody = new MimeBodyPart();
            mailBody.setText(request.getText());
            mp.addBodyPart(mailBody);
            if (null != attachments && !attachments.isEmpty()) {
                for (String url : attachments) {
                    log.debug("add mime part for {}", url);
                    MimeBodyPart part = new MimeBodyPart();
                    String filename = url;
                    int pos = filename.lastIndexOf('/');
                    if (pos >= 0) {
                        filename = filename.substring(pos + 1);
                    }
                    pos = filename.indexOf('?');
                    if (pos >= 0) {
                        filename = filename.substring(0, pos);
                    }
                    part.setFileName(filename);
                    String fixedUrl = url;
                    if (fixedUrl.startsWith("../")) {
                        fixedUrl = "http://localhost:8080/" + fixedUrl.substring(3);
                    }
                    fixedUrl = fixedUrl.replace(" ", "%20");
                    part.setDataHandler(new DataHandler(new URL(fixedUrl)));
                    mp.addBodyPart(part);
                }
            }
            mimeMessage.setContent(mp);
            log.debug("message {}", mimeMessage);
        }
    };
    try {
        if (request.isSendMail()) {
            mailSender.send(preparator);
            cleanAttachmentConnection(attachmentConnections);
            log.debug("mail sent");
        }
        if (request.isSaveMail()) {
            MimeMessage mimeMessage = new MimeMessage((Session) null);
            preparator.prepare(mimeMessage);
            // overwrite multipart body as we don't need the attachments
            mimeMessage.setText(request.getText());
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            mimeMessage.writeTo(baos);
            // add document in referral
            Crs crs = geoService.getCrs2(KtunaxaConstant.LAYER_CRS);
            List<InternalFeature> features = vectorLayerService.getFeatures(
                    KtunaxaConstant.LAYER_REFERRAL_SERVER_ID, crs,
                    filterService.parseFilter(ReferralUtil.createFilter(request.getReferralId())), null,
                    VectorLayerService.FEATURE_INCLUDE_ATTRIBUTES);
            InternalFeature orgReferral = features.get(0);
            log.debug("Got referral {}", request.getReferralId());
            InternalFeature referral = orgReferral.clone();
            List<InternalFeature> newFeatures = new ArrayList<InternalFeature>();
            newFeatures.add(referral);
            Map<String, Attribute> attributes = referral.getAttributes();
            OneToManyAttribute orgComments = (OneToManyAttribute) attributes
                    .get(KtunaxaConstant.ATTRIBUTE_COMMENTS);
            List<AssociationValue> comments = new ArrayList<AssociationValue>(orgComments.getValue());
            AssociationValue emailAsComment = new AssociationValue();
            emailAsComment.setStringAttribute(KtunaxaConstant.ATTRIBUTE_COMMENT_TITLE,
                    "Mail: " + request.getSubject());
            emailAsComment.setStringAttribute(KtunaxaConstant.ATTRIBUTE_COMMENT_CONTENT,
                    new String(baos.toByteArray()));
            emailAsComment.setStringAttribute(KtunaxaConstant.ATTRIBUTE_COMMENT_CREATED_BY,
                    securitycontext.getUserName());
            emailAsComment.setDateAttribute(KtunaxaConstant.ATTRIBUTE_COMMENT_CREATION_DATE, new Date());
            emailAsComment.setStringAttribute(KtunaxaConstant.ATTRIBUTE_COMMENT_CONTENT,
                    new String(baos.toByteArray()));
            emailAsComment.setStringAttribute(KtunaxaConstant.ATTRIBUTE_COMMENT_CONTENT,
                    new String(baos.toByteArray()));
            emailAsComment.setBooleanAttribute(KtunaxaConstant.ATTRIBUTE_COMMENT_INCLUDE_IN_REPORT, false);
            comments.add(emailAsComment);
            OneToManyAttribute newComments = new OneToManyAttribute(comments);
            attributes.put(KtunaxaConstant.ATTRIBUTE_COMMENTS, newComments);
            log.debug("Going to add mail as comment to referral");
            vectorLayerService.saveOrUpdate(KtunaxaConstant.LAYER_REFERRAL_SERVER_ID, crs, features,
                    newFeatures);
        }
        response.setSuccess(true);
    } catch (MailException me) {
        log.error("Could not send e-mail", me);
        throw new KtunaxaException(KtunaxaException.CODE_MAIL_ERROR, "Could not send e-mail");
    }
}

From source file:immf.MyHtmlEmail.java

/**
 * Embeds the specified <code>DataSource</code> in the HTML using the
 * specified Content-ID. Returns the specified Content-ID string.
 *
 * @param dataSource the <code>DataSource</code> to embed
 * @param name the name that will be set in the filename header field
 * @param cid the Content-ID to use for this <code>DataSource</code>
 * @return the supplied Content-ID for this <code>DataSource</code>
 * @throws EmailException if the embedding fails or if <code>name</code> is
 * null or empty/*from   w w w .j  av  a2s .c o  m*/
 * @since 1.1
 */
public String embed(DataSource dataSource, String name, String cid) throws EmailException {
    if (StringUtils.isEmpty(name)) {
        throw new EmailException("name cannot be null or empty");
    }

    MimeBodyPart mbp = new MimeBodyPart();

    try {
        mbp.setDataHandler(new DataHandler(dataSource));
        mbp.setFileName(name);
        mbp.setDisposition("inline");
        mbp.setContentID("<" + cid + ">");

        InlineImage ii = new InlineImage(cid, dataSource, mbp);
        this.inlineEmbeds.put(name, ii);

        return cid;
    } catch (MessagingException me) {
        throw new EmailException(me);
    }
}

From source file:org.xwiki.mail.internal.AttachmentMimeBodyPartFactory.java

@Override
public MimeBodyPart create(Attachment attachment, Map<String, Object> parameters) throws MessagingException {
    // Create the attachment part of the email
    MimeBodyPart attachmentPart = new MimeBodyPart();

    // Save the attachment to a temporary file on the file system and wrap it in a Java Mail Data Source.
    DataSource source = createTemporaryAttachmentDataSource(attachment);
    attachmentPart.setDataHandler(new DataHandler(source));

    attachmentPart.setHeader("Content-Type", attachment.getMimeType());

    // Add a content-id so that we can uniquely reference this attachment. This is used for example to
    // display the attachment inline in some mail HTML content.
    // Note: According to http://tools.ietf.org/html/rfc2392 the id must be enclosed in angle brackets.
    attachmentPart.setHeader("Content-ID", "<" + attachment.getFilename() + ">");

    attachmentPart.setFileName(source.getName());

    // Handle headers passed as parameter
    addHeaders(attachmentPart, parameters);

    return attachmentPart;
}

From source file:org.xwiki.mail.internal.factory.attachment.AttachmentMimeBodyPartFactory.java

@Override
public MimeBodyPart create(Attachment attachment, Map<String, Object> parameters) throws MessagingException {
    // Create the attachment part of the email
    MimeBodyPart attachmentPart = new MimeBodyPart();

    // Save the attachment to a temporary file on the file system and wrap it in a Java Mail Data Source.
    DataSource source = createTemporaryAttachmentDataSource(attachment);
    attachmentPart.setDataHandler(new DataHandler(source));

    attachmentPart.setHeader("Content-Type", attachment.getMimeType());

    // Add a content-id so that we can uniquely reference this attachment. This is used for example to
    // display the attachment inline in some mail HTML content.
    // Note: According to http://tools.ietf.org/html/rfc2392 the id must be enclosed in angle brackets.
    attachmentPart.setHeader("Content-ID", "<" + attachment.getFilename() + ">");

    attachmentPart.setFileName(attachment.getFilename());

    // Handle headers passed as parameter
    addHeaders(attachmentPart, parameters);

    return attachmentPart;
}