Example usage for javax.mail BodyPart setFileName

List of usage examples for javax.mail BodyPart setFileName

Introduction

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

Prototype

public void setFileName(String filename) throws MessagingException;

Source Link

Document

Set the filename associated with this part, if possible.

Usage

From source file:fr.paris.lutece.portal.service.mail.MailUtil.java

/**
 * Send a Multipart HTML message with the attachements associated to the
 * message and attached files. FIXME: use prepareMessage method
 *
 * @param strRecipientsTo/*  w  ww  .  java  2  s.c  om*/
 *            The list of the main recipients email.Every recipient must be
 *            separated by the mail separator defined in config.properties
 * @param strRecipientsCc
 *            The recipients list of the carbon copies .
 * @param strRecipientsBcc
 *            The recipients list of the blind carbon copies .
 * @param strSenderName
 *            The sender name.
 * @param strSenderEmail
 *            The sender email address.
 * @param strSubject
 *            The message subject.
 * @param strMessage
 *            The message.
 * @param urlAttachements
 *            The List of UrlAttachement Object, containing the URL of
 *            attachments associated with their content-location.
 * @param fileAttachements
 *            The list of files attached
 * @param transport
 *            the smtp transport object
 * @param session
 *            the smtp session object
 * @throws AddressException
 *             If invalid address
 * @throws SendFailedException
 *             If an error occured during sending
 * @throws MessagingException
 *             If a messaging error occurred
 */
protected static void sendMultipartMessageHtml(String strRecipientsTo, String strRecipientsCc,
        String strRecipientsBcc, String strSenderName, String strSenderEmail, String strSubject,
        String strMessage, List<UrlAttachment> urlAttachements, List<FileAttachment> fileAttachements,
        Transport transport, Session session) throws MessagingException, AddressException, SendFailedException {
    Message msg = prepareMessage(strRecipientsTo, strRecipientsCc, strRecipientsBcc, strSenderName,
            strSenderEmail, strSubject, session);
    msg.setHeader(HEADER_NAME, HEADER_VALUE);

    // Creation of the root part containing all the elements of the message
    MimeMultipart multipart = ((fileAttachements == null) || (fileAttachements.isEmpty()))
            ? new MimeMultipart(MULTIPART_RELATED)
            : new MimeMultipart();

    // Creation of the html part, the "core" of the message
    BodyPart msgBodyPart = new MimeBodyPart();
    // msgBodyPart.setContent( strMessage, BODY_PART_MIME_TYPE );
    msgBodyPart.setDataHandler(new DataHandler(
            new ByteArrayDataSource(strMessage, AppPropertiesService.getProperty(PROPERTY_MAIL_TYPE_HTML)
                    + AppPropertiesService.getProperty(PROPERTY_CHARSET))));
    multipart.addBodyPart(msgBodyPart);

    if (urlAttachements != null) {
        ByteArrayDataSource urlByteArrayDataSource;

        for (UrlAttachment urlAttachement : urlAttachements) {
            urlByteArrayDataSource = convertUrlAttachmentDataSourceToByteArrayDataSource(urlAttachement);

            if (urlByteArrayDataSource != null) {
                msgBodyPart = new MimeBodyPart();
                // Fill this part, then add it to the root part with the
                // good headers
                msgBodyPart.setDataHandler(new DataHandler(urlByteArrayDataSource));
                msgBodyPart.setHeader(HEADER_CONTENT_LOCATION, urlAttachement.getContentLocation());
                multipart.addBodyPart(msgBodyPart);
            }
        }
    }

    // add File Attachement
    if (fileAttachements != null) {
        for (FileAttachment fileAttachement : fileAttachements) {
            String strFileName = fileAttachement.getFileName();
            byte[] bContentFile = fileAttachement.getData();
            String strContentType = fileAttachement.getType();
            ByteArrayDataSource dataSource = new ByteArrayDataSource(bContentFile, strContentType);
            msgBodyPart = new MimeBodyPart();
            msgBodyPart.setDataHandler(new DataHandler(dataSource));
            msgBodyPart.setFileName(strFileName);
            msgBodyPart.setDisposition(CONSTANT_DISPOSITION_ATTACHMENT);
            multipart.addBodyPart(msgBodyPart);
        }
    }

    msg.setContent(multipart);

    sendMessage(msg, transport);
}

From source file:com.nridge.core.app.mail.MailManager.java

/**
 * If the property "delivery_enabled" is <i>true</i>, then this method
 * will generate an email message that includes subject, message and
 * attachments to the recipient list.  You can use the convenience
 * methods <i>lookupFromAddress()</i>, <i>createRecipientList()</i>
 * and <i>createAttachmentList()</i> for parameter building assistance.
 *
 * @param aFromAddress Source email address.
 * @param aRecipientList List of recipient email addresses.
 * @param aSubject Subject of the email message.
 * @param aMessage Messsage./*from  w w w . ja v  a  2 s.c om*/
 * @param anAttachmentFiles List of file attachments or <i>null</i> for none.
 *
 * @see <a href="https://www.tutorialspoint.com/javamail_api/javamail_api_send_email_with_attachment.htm">JavaMail API Attachments</a>
 * @see <a href="https://stackoverflow.com/questions/6756162/how-do-i-send-mail-with-both-plain-text-as-well-as-html-text-so-that-each-mail-r">JavaMail API MIME Types</a>
 *
 * @throws IOException I/O related error condition.
 * @throws NSException Missing configuration properties.
 * @throws MessagingException Message subsystem error condition.
 */
public void sendMessage(String aFromAddress, ArrayList<String> aRecipientList, String aSubject, String aMessage,
        ArrayList<String> anAttachmentFiles)

        throws IOException, NSException, MessagingException {
    InternetAddress internetAddressFrom, internetAddressTo;
    Logger appLogger = mAppMgr.getLogger(this, "sendMessage");

    appLogger.trace(mAppMgr.LOGMSG_TRACE_ENTER);

    if (isCfgStringTrue("delivery_enabled")) {
        if ((StringUtils.isNotEmpty(aFromAddress)) && (aRecipientList.size() > 0)
                && (StringUtils.isNotEmpty(aSubject)) && (StringUtils.isNotEmpty(aMessage))) {
            initialize();

            Message mimeMessage = new MimeMessage(mMailSession);
            internetAddressFrom = new InternetAddress(aFromAddress);
            mimeMessage.addFrom(new InternetAddress[] { internetAddressFrom });
            for (String mailAddressTo : aRecipientList) {
                internetAddressTo = new InternetAddress(mailAddressTo);
                mimeMessage.addRecipient(MimeMessage.RecipientType.TO, internetAddressTo);
            }
            mimeMessage.setSubject(aSubject);

            // The following logic create a multi-part message and adds the attachment to it.

            BodyPart messageBodyPart = new MimeBodyPart();
            messageBodyPart.setText(aMessage);
            //                messageBodyPart.setContent(aMessage, "text/html");
            Multipart multipart = new MimeMultipart();
            multipart.addBodyPart(messageBodyPart);

            if ((anAttachmentFiles != null) && (anAttachmentFiles.size() > 0)) {
                for (String pathFileName : anAttachmentFiles) {
                    File attachmentFile = new File(pathFileName);
                    if (attachmentFile.exists()) {
                        messageBodyPart = new MimeBodyPart();
                        DataSource fileDataSource = new FileDataSource(pathFileName);
                        messageBodyPart.setDataHandler(new DataHandler(fileDataSource));
                        messageBodyPart.setFileName(attachmentFile.getName());
                        multipart.addBodyPart(messageBodyPart);
                    }
                }
                appLogger.debug(String.format("Mail Message (%s): %s - with attachments", aSubject, aMessage));
            } else
                appLogger.debug(String.format("Mail Message (%s): %s", aSubject, aMessage));

            mimeMessage.setContent(multipart);
            Transport.send(mimeMessage);
        } else
            throw new NSException("Valid from, recipient, subject and message are required parameters.");
    } else
        appLogger.warn("Email delivery is not enabled - no message will be sent.");

    appLogger.trace(mAppMgr.LOGMSG_TRACE_DEPART);
}

From source file:nl.nn.adapterframework.senders.MailSenderOld.java

protected String sendEmail(String from, String subject, String threadTopic, String message, String messageType,
        String messageBase64, String charset, Collection<Recipient> recipients,
        Collection<Attachment> attachments) throws SenderException {

    StringBuffer sb = new StringBuffer();

    if (recipients == null || recipients.size() == 0) {
        throw new SenderException("MailSender [" + getName() + "] has no recipients for message");
    }/*from  ww w .ja  va2 s . co  m*/
    if (StringUtils.isEmpty(from)) {
        from = defaultFrom;
    }
    if (StringUtils.isEmpty(subject)) {
        subject = defaultSubject;
    }
    log.debug("MailSender [" + getName() + "] requested to send message from [" + from + "] subject [" + subject
            + "] to #recipients [" + recipients.size() + "]");

    if (StringUtils.isEmpty(messageType)) {
        messageType = defaultMessageType;
    }

    if (StringUtils.isEmpty(messageBase64)) {
        messageBase64 = defaultMessageBase64;
    }

    try {
        if (log.isDebugEnabled()) {
            sb.append("MailSender [" + getName() + "] sending message ");
            sb.append("[smtpHost=" + smtpHost);
            sb.append("[from=" + from + "]");
            sb.append("[subject=" + subject + "]");
            sb.append("[threadTopic=" + threadTopic + "]");
            sb.append("[text=" + message + "]");
            sb.append("[type=" + messageType + "]");
            sb.append("[base64=" + messageBase64 + "]");
        }

        if ("true".equalsIgnoreCase(messageBase64) && StringUtils.isNotEmpty(message)) {
            message = decodeBase64ToString(message);
        }

        // construct a message  
        MimeMessage msg = new MimeMessage(session);
        msg.setFrom(new InternetAddress(from));
        msg.setSubject(subject, charset);
        if (StringUtils.isNotEmpty(threadTopic)) {
            msg.setHeader("Thread-Topic", threadTopic);
        }
        Iterator iter = recipients.iterator();
        boolean recipientsFound = false;
        while (iter.hasNext()) {
            Recipient recipient = (Recipient) iter.next();
            String value = recipient.value;
            String type = recipient.type;
            Message.RecipientType recipientType;
            if ("cc".equalsIgnoreCase(type)) {
                recipientType = Message.RecipientType.CC;
            } else if ("bcc".equalsIgnoreCase(type)) {
                recipientType = Message.RecipientType.BCC;
            } else {
                recipientType = Message.RecipientType.TO;
            }
            msg.addRecipient(recipientType, new InternetAddress(value));
            recipientsFound = true;
            if (log.isDebugEnabled()) {
                sb.append("[recipient [" + recipient + "]]");
            }
        }
        if (!recipientsFound) {
            throw new SenderException("MailSender [" + getName() + "] did not find any valid recipients");
        }

        String messageTypeWithCharset;
        if (charset == null) {
            charset = System.getProperty("mail.mime.charset");
            if (charset == null) {
                charset = System.getProperty("file.encoding");
            }
        }
        if (charset != null) {
            messageTypeWithCharset = messageType + ";charset=" + charset;
        } else {
            messageTypeWithCharset = messageType;
        }
        log.debug("MailSender [" + getName() + "] uses encoding [" + messageTypeWithCharset + "]");

        if (attachments == null || attachments.size() == 0) {
            //msg.setContent(message, messageType);
            msg.setContent(message, messageTypeWithCharset);
        } else {
            Multipart multipart = new MimeMultipart();
            BodyPart messageBodyPart = new MimeBodyPart();
            //messageBodyPart.setContent(message, messageType);
            messageBodyPart.setContent(message, messageTypeWithCharset);
            multipart.addBodyPart(messageBodyPart);

            int counter = 0;
            iter = attachments.iterator();
            while (iter.hasNext()) {
                counter++;
                Attachment attachment = (Attachment) iter.next();
                Object value = attachment.getValue();
                String name = attachment.getName();
                if (StringUtils.isEmpty(name)) {
                    name = getDefaultAttachmentName() + counter;
                }
                log.debug("found attachment [" + attachment + "]");

                messageBodyPart = new MimeBodyPart();
                messageBodyPart.setFileName(name);

                if (value instanceof DataHandler) {
                    messageBodyPart.setDataHandler((DataHandler) value);
                } else {
                    messageBodyPart.setText((String) value);
                }

                multipart.addBodyPart(messageBodyPart);
            }
            msg.setContent(multipart);
        }

        log.debug(sb.toString());
        msg.setSentDate(new Date());
        msg.saveChanges();
        // send the message
        putOnTransport(msg);
        // return the mail in mail-safe from
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        msg.writeTo(out);
        byte[] byteArray = out.toByteArray();
        return Misc.byteArrayToString(byteArray, "\n", false);
    } catch (Exception e) {
        throw new SenderException("MailSender got error", e);
    }
}

From source file:com.enonic.esl.net.Mail.java

/**
 * <p/> Send the mail. The SMTP host is contacted and the mail is sent according to the parameters set. </p> <p/> If it fails, it is
 * considered a runtime exception. Note that this doesn't make it very failsafe, so care should be taken when one wants fault tolerance.
 * One solution could be to catch the exception thrown. Another solution could be to use the JavaMail API directly. </p>
 *///  ww w  . j  a v a  2s  . c  o m
public void send() throws ESLException {
    // smtp server
    Properties smtpProperties = new Properties();
    if (smtpHost != null) {
        smtpProperties.put("mail.smtp.host", smtpHost);
        System.setProperty("mail.smtp.host", smtpHost);
    } else {
        smtpProperties.put("mail.smtp.host", DEFAULT_SMTPHOST);
        System.setProperty("mail.smtp.host", DEFAULT_SMTPHOST);
    }
    Session session = Session.getDefaultInstance(smtpProperties, null);

    try {
        // create message
        Message msg = new MimeMessage(session);
        // set from address
        InternetAddress addressFrom = new InternetAddress();
        if (from_email != null) {
            addressFrom.setAddress(from_email);
        }
        if (from_name != null) {
            addressFrom.setPersonal(from_name, ENCODING);
        }
        ((MimeMessage) msg).setFrom(addressFrom);

        if ((to.size() == 0 && bcc.size() == 0) || subject == null
                || (message == null && htmlMessage == null)) {
            LOG.error("Missing data. Unable to send mail.");
            throw new ESLException("Missing data. Unable to send mail.");
        }

        // set to:
        for (int i = 0; i < to.size(); ++i) {
            String[] recipient = to.get(i);
            InternetAddress addressTo = new InternetAddress(recipient[1]);
            if (recipient[0] != null) {
                addressTo.setPersonal(recipient[0], ENCODING);
            }
            ((MimeMessage) msg).addRecipient(Message.RecipientType.TO, addressTo);
        }

        // set bcc:
        for (int i = 0; i < bcc.size(); ++i) {
            String[] recipient = bcc.get(i);
            InternetAddress addressTo = null;
            try {
                addressTo = new InternetAddress(recipient[1]);
            } catch (Exception e) {
                System.err.println("exception on address: " + recipient[1]);
                continue;
            }
            if (recipient[0] != null) {
                addressTo.setPersonal(recipient[0], ENCODING);
            }
            ((MimeMessage) msg).addRecipient(Message.RecipientType.BCC, addressTo);
        }

        // set cc:
        for (int i = 0; i < cc.size(); ++i) {
            String[] recipient = cc.get(i);
            InternetAddress addressTo = new InternetAddress(recipient[1]);
            if (recipient[0] != null) {
                addressTo.setPersonal(recipient[0], ENCODING);
            }
            ((MimeMessage) msg).addRecipient(Message.RecipientType.CC, addressTo);
        }

        // Setting subject and content type
        ((MimeMessage) msg).setSubject(subject, ENCODING);

        if (message != null) {
            message = RegexpUtil.substituteAll("\\\\n", "\n", message);
        }

        // if there are any attachments, treat this as a multipart message.
        if (attachments.size() > 0) {
            BodyPart messageBodyPart = new MimeBodyPart();
            if (message != null) {
                ((MimeBodyPart) messageBodyPart).setText(message, ENCODING);
            } else {
                DataHandler dataHandler = new DataHandler(
                        new ByteArrayDataSource(htmlMessage, "text/html", ENCODING));
                ((MimeBodyPart) messageBodyPart).setDataHandler(dataHandler);
            }
            Multipart multipart = new MimeMultipart();
            multipart.addBodyPart(messageBodyPart);

            // add all attachments
            for (int i = 0; i < attachments.size(); ++i) {
                Object obj = attachments.get(i);
                if (obj instanceof String) {
                    System.err.println("attachment is String");
                    messageBodyPart = new MimeBodyPart();
                    ((MimeBodyPart) messageBodyPart).setText((String) obj, ENCODING);
                    multipart.addBodyPart(messageBodyPart);
                } else if (obj instanceof File) {
                    messageBodyPart = new MimeBodyPart();
                    FileDataSource fds = new FileDataSource((File) obj);
                    messageBodyPart.setDataHandler(new DataHandler(fds));
                    messageBodyPart.setFileName(fds.getName());
                    multipart.addBodyPart(messageBodyPart);
                } else if (obj instanceof FileItem) {
                    FileItem fileItem = (FileItem) obj;
                    messageBodyPart = new MimeBodyPart();
                    FileItemDataSource fds = new FileItemDataSource(fileItem);
                    messageBodyPart.setDataHandler(new DataHandler(fds));
                    messageBodyPart.setFileName(fds.getName());
                    multipart.addBodyPart(messageBodyPart);
                } else {
                    // byte array
                    messageBodyPart = new MimeBodyPart();
                    ByteArrayDataSource bads = new ByteArrayDataSource((byte[]) obj, "text/html", ENCODING);
                    messageBodyPart.setDataHandler(new DataHandler(bads));
                    messageBodyPart.setFileName(bads.getName());
                    multipart.addBodyPart(messageBodyPart);
                }
            }

            msg.setContent(multipart);
        } else {
            if (message != null) {
                ((MimeMessage) msg).setText(message, ENCODING);
            } else {
                DataHandler dataHandler = new DataHandler(
                        new ByteArrayDataSource(htmlMessage, "text/html", ENCODING));
                ((MimeMessage) msg).setDataHandler(dataHandler);
            }
        }

        // send message
        Transport.send(msg);
    } catch (AddressException e) {
        String MESSAGE_30 = "Error in email address: " + e.getMessage();
        LOG.warn(MESSAGE_30);
        throw new ESLException(MESSAGE_30, e);
    } catch (UnsupportedEncodingException e) {
        String MESSAGE_40 = "Unsupported encoding: " + e.getMessage();
        LOG.error(MESSAGE_40, e);
        throw new ESLException(MESSAGE_40, e);
    } catch (SendFailedException sfe) {
        Throwable t = null;
        Exception e = sfe.getNextException();
        while (e != null) {
            t = e;
            if (t instanceof SendFailedException) {
                e = ((SendFailedException) e).getNextException();
            } else {
                e = null;
            }
        }
        if (t != null) {
            String MESSAGE_50 = "Error sending mail: " + t.getMessage();
            throw new ESLException(MESSAGE_50, t);
        } else {
            String MESSAGE_50 = "Error sending mail: " + sfe.getMessage();
            throw new ESLException(MESSAGE_50, sfe);
        }
    } catch (MessagingException e) {
        String MESSAGE_50 = "Error sending mail: " + e.getMessage();
        LOG.error(MESSAGE_50, e);
        throw new ESLException(MESSAGE_50, e);
    }
}

From source file:org.olat.core.util.mail.manager.MailManagerImpl.java

@Override
public MimeMessage createMimeMessage(Address from, Address[] tos, Address[] ccs, Address[] bccs, String subject,
        String body, List<File> attachments, MailerResult result) {

    try {/* w  ww . ja v a  2  s. c o  m*/
        //   see FXOLAT-74: send all mails as <fromemail> (in config) to have a valid reverse lookup and therefore pass spam protection.
        // following doesn't work correctly, therefore add bounce-address in message already
        Address convertedFrom = getRawEmailFromAddress(from);
        MimeMessage msg = createMessage(convertedFrom);
        Address viewableFrom = createAddressWithName(WebappHelper.getMailConfig("mailFrom"),
                WebappHelper.getMailConfig("mailFromName"));
        msg.setFrom(viewableFrom);
        msg.setSubject(subject, "utf-8");
        // reply to can only be an address without name (at least for postfix!), see FXOLAT-312
        msg.setReplyTo(new Address[] { convertedFrom });

        if (tos != null && tos.length > 0) {
            msg.addRecipients(RecipientType.TO, tos);
        }

        if (ccs != null && ccs.length > 0) {
            msg.addRecipients(RecipientType.CC, ccs);
        }

        if (bccs != null && bccs.length > 0) {
            msg.addRecipients(RecipientType.BCC, bccs);
        }

        if (attachments != null && !attachments.isEmpty()) {
            // with attachment use multipart message
            Multipart multipart = new MimeMultipart("mixed");
            // 1) add body part
            if (StringHelper.isHtml(body)) {
                Multipart alternativePart = createMultipartAlternative(body);
                MimeBodyPart wrap = new MimeBodyPart();
                wrap.setContent(alternativePart);
                multipart.addBodyPart(wrap);
            } else {
                BodyPart messageBodyPart = new MimeBodyPart();
                messageBodyPart.setText(body);
                multipart.addBodyPart(messageBodyPart);
            }

            // 2) add attachments
            for (File attachmentFile : attachments) {
                // abort if attachment does not exist
                if (attachmentFile == null || !attachmentFile.exists()) {
                    result.setReturnCode(MailerResult.ATTACHMENT_INVALID);
                    logError("Tried to send mail wit attachment that does not exist::"
                            + (attachmentFile == null ? null : attachmentFile.getAbsolutePath()), null);
                    return msg;
                }
                BodyPart filePart = new MimeBodyPart();
                DataSource source = new FileDataSource(attachmentFile);
                filePart.setDataHandler(new DataHandler(source));
                filePart.setFileName(attachmentFile.getName());
                multipart.addBodyPart(filePart);
            }
            // Put parts in message
            msg.setContent(multipart);
        } else {
            // without attachment everything is easy, just set as text
            if (StringHelper.isHtml(body)) {
                msg.setContent(createMultipartAlternative(body));
            } else {
                msg.setText(body, "utf-8");
            }
        }
        msg.setSentDate(new Date());
        msg.saveChanges();
        return msg;
    } catch (AddressException e) {
        result.setReturnCode(MailerResult.SENDER_ADDRESS_ERROR);
        logError("", e);
        return null;
    } catch (MessagingException e) {
        result.setReturnCode(MailerResult.SEND_GENERAL_ERROR);
        logError("", e);
        return null;
    } catch (UnsupportedEncodingException e) {
        result.setReturnCode(MailerResult.SENDER_ADDRESS_ERROR);
        logError("", e);
        return null;
    }
}

From source file:org.enlacerh.util.FileUploadController.java

/**
 * Mtodo que enva los recibos de pago a cada usuario
 * @throws IOException /*from  www .  j a  v  a2s.  c  o m*/
 * @throws NumberFormatException 
 * **/
public void enviarRP(String to, String laruta, String file) throws NumberFormatException, IOException {
    try {
        //System.out.println("Enviando recibo");
        //System.out.println(jndimail());
        Context initContext = new InitialContext();
        Session session = (Session) initContext.lookup(jndimail());
        // Crear el mensaje a enviar
        MimeMessage mm = new MimeMessage(session);

        // Establecer las direcciones a las que ser enviado
        // el mensaje (test2@gmail.com y test3@gmail.com en copia
        // oculta)
        // mm.setFrom(new
        // InternetAddress("opennomina@dvconsultores.com"));
        mm.addRecipient(Message.RecipientType.TO, new InternetAddress(to));

        // Establecer el contenido del mensaje
        mm.setSubject(getMessage("mailRP"));
        //mm.setText(getMessage("mailContent"));

        // Create the message part 
        BodyPart messageBodyPart = new MimeBodyPart();

        // Fill the message
        messageBodyPart.setContent(getMessage("mailRPcontent"), "text/html; charset=utf-8");

        // Create a multipar message
        Multipart multipart = new MimeMultipart();

        // Set text message part
        multipart.addBodyPart(messageBodyPart);

        // Part two is attachment
        messageBodyPart = new MimeBodyPart();
        String filename = laruta + File.separator + file + ".pdf";
        javax.activation.DataSource source = new FileDataSource(filename);
        messageBodyPart.setDataHandler(new DataHandler(source));
        messageBodyPart.setFileName(file + ".pdf");
        multipart.addBodyPart(messageBodyPart);

        // Send the complete message parts
        mm.setContent(multipart);

        // Enviar el correo electrnico
        Transport.send(mm);
        //System.out.println("Correo enviado exitosamente a :" + to);
        //System.out.println("Fin recibo");
    } catch (Exception e) {
        msj = new FacesMessage(FacesMessage.SEVERITY_FATAL, e.getMessage() + ": " + to, "");
        FacesContext.getCurrentInstance().addMessage(null, msj);
        e.printStackTrace();
    }
}

From source file:se.inera.axel.shs.processor.ShsMessageMarshaller.java

public void marshal(ShsMessage shsMessage, OutputStream outputStream) throws IllegalMessageStructureException {
    log.trace("marshal(ShsMessage, OutputStream)");

    MimeMultipart multipart = new MimeMultipart();
    BodyPart bodyPart = new MimeBodyPart();

    try {/* ww  w.  j a va 2  s  . c  o m*/

        ShsLabel label = shsMessage.getLabel();
        if (label == null) {
            throw new IllegalMessageStructureException("label not found in shs message");
        }

        Content content = label.getContent();
        if (content == null) {
            throw new IllegalMessageStructureException("label/content not found in shs label");
        } else {
            // we will update this according to our data parts below.
            content.getDataOrCompound().clear();

            String contentId = content.getContentId();
            content.setContentId(contentId.substring(0, Math.min(contentId.length(), MAX_LENGTH_CONTENT_ID)));
        }

        List<DataPart> dataParts = shsMessage.getDataParts();

        if (dataParts.isEmpty()) {
            throw new IllegalMessageStructureException("dataparts not found in message");
        }

        for (DataPart dp : dataParts) {
            Data data = new Data();

            data.setDatapartType(dp.getDataPartType());
            data.setFilename(dp.getFileName());
            if (dp.getContentLength() != null && dp.getContentLength() > 0)
                data.setNoOfBytes("" + dp.getContentLength());
            content.getDataOrCompound().add(data);
        }

        bodyPart.setContent(shsLabelMarshaller.marshal(label), "text/xml; charset=ISO-8859-1");
        bodyPart.setHeader("Content-Transfer-Encoding", "binary");

        multipart.addBodyPart(bodyPart);

        for (DataPart dataPart : dataParts) {

            bodyPart = new MimeBodyPart();

            bodyPart.setDisposition(Part.ATTACHMENT);
            if (StringUtils.isNotBlank(dataPart.getFileName())) {
                bodyPart.setFileName(dataPart.getFileName());
            }

            bodyPart.setDataHandler(dataPart.getDataHandler());

            if (dataPart.getTransferEncoding() != null) {
                bodyPart.addHeader("Content-Transfer-Encoding", dataPart.getTransferEncoding().toLowerCase());
            }
            multipart.addBodyPart(bodyPart);
        }

        MimeMessage mimeMessage = new MimeMessage(session);
        mimeMessage.setSubject("SHS Message");
        mimeMessage.addHeader("Content-Transfer-Encoding", "binary");

        mimeMessage.setContent(multipart);
        mimeMessage.saveChanges();

        String ignoreList[] = { "Message-ID" };

        mimeMessage.writeTo(outputStream, ignoreList);
        outputStream.flush();

    } catch (Exception e) {
        if (e instanceof IllegalMessageStructureException) {
            throw (IllegalMessageStructureException) e;
        }
        throw new IllegalMessageStructureException(e);
    }

}

From source file:nl.nn.adapterframework.senders.MailSender.java

protected String sendEmail(String from, String subject, String threadTopic, String message, String messageType,
        String messageBase64, String charset, Collection recipients, Collection attachments)
        throws SenderException {

    StringBuffer sb = new StringBuffer();

    if (recipients == null || recipients.size() == 0) {
        throw new SenderException("MailSender [" + getName() + "] has no recipients for message");
    }//from   ww w.j  a v a2  s. com
    if (StringUtils.isEmpty(from)) {
        from = defaultFrom;
    }
    if (StringUtils.isEmpty(subject)) {
        subject = defaultSubject;
    }
    log.debug("MailSender [" + getName() + "] requested to send message from [" + from + "] subject [" + subject
            + "] to #recipients [" + recipients.size() + "]");

    if (StringUtils.isEmpty(messageType)) {
        messageType = defaultMessageType;
    }

    if (StringUtils.isEmpty(messageBase64)) {
        messageBase64 = defaultMessageBase64;
    }

    try {
        if (log.isDebugEnabled()) {
            sb.append("MailSender [" + getName() + "] sending message ");
            sb.append("[smtpHost=" + smtpHost);
            sb.append("[from=" + from + "]");
            sb.append("[subject=" + subject + "]");
            sb.append("[threadTopic=" + threadTopic + "]");
            sb.append("[text=" + message + "]");
            sb.append("[type=" + messageType + "]");
            sb.append("[base64=" + messageBase64 + "]");
        }

        if ("true".equalsIgnoreCase(messageBase64) && StringUtils.isNotEmpty(message)) {
            message = decodeBase64ToString(message);
        }

        // construct a message  
        MimeMessage msg = new MimeMessage(session);
        msg.setFrom(new InternetAddress(from));
        msg.setSubject(subject, charset);
        if (StringUtils.isNotEmpty(threadTopic)) {
            msg.setHeader("Thread-Topic", threadTopic);
        }
        Iterator iter = recipients.iterator();
        boolean recipientsFound = false;
        while (iter.hasNext()) {
            Element recipientElement = (Element) iter.next();
            String recipient = XmlUtils.getStringValue(recipientElement);
            if (StringUtils.isNotEmpty(recipient)) {
                String typeAttr = recipientElement.getAttribute("type");
                Message.RecipientType recipientType = Message.RecipientType.TO;
                if ("cc".equalsIgnoreCase(typeAttr)) {
                    recipientType = Message.RecipientType.CC;
                }
                if ("bcc".equalsIgnoreCase(typeAttr)) {
                    recipientType = Message.RecipientType.BCC;
                }
                msg.addRecipient(recipientType, new InternetAddress(recipient));
                recipientsFound = true;
                if (log.isDebugEnabled()) {
                    sb.append("[recipient(" + typeAttr + ")=" + recipient + "]");
                }
            } else {
                log.debug("empty recipient found, ignoring");
            }
        }
        if (!recipientsFound) {
            throw new SenderException("MailSender [" + getName() + "] did not find any valid recipients");
        }

        String messageTypeWithCharset;
        if (charset == null) {
            charset = System.getProperty("mail.mime.charset");
            if (charset == null) {
                charset = System.getProperty("file.encoding");
            }
        }
        if (charset != null) {
            messageTypeWithCharset = messageType + ";charset=" + charset;
        } else {
            messageTypeWithCharset = messageType;
        }
        log.debug("MailSender [" + getName() + "] uses encoding [" + messageTypeWithCharset + "]");

        if (attachments == null || attachments.size() == 0) {
            //msg.setContent(message, messageType);
            msg.setContent(message, messageTypeWithCharset);
        } else {
            Multipart multipart = new MimeMultipart();
            BodyPart messageBodyPart = new MimeBodyPart();
            //messageBodyPart.setContent(message, messageType);
            messageBodyPart.setContent(message, messageTypeWithCharset);
            multipart.addBodyPart(messageBodyPart);

            iter = attachments.iterator();
            while (iter.hasNext()) {
                Element attachmentElement = (Element) iter.next();
                String attachmentText = XmlUtils.getStringValue(attachmentElement);
                String attachmentName = attachmentElement.getAttribute("name");
                String attachmentUrl = attachmentElement.getAttribute("url");
                String attachmentType = attachmentElement.getAttribute("type");
                String attachmentBase64 = attachmentElement.getAttribute("base64");
                if (StringUtils.isEmpty(attachmentType)) {
                    attachmentType = getDefaultAttachmentType();
                }
                if (StringUtils.isEmpty(attachmentName)) {
                    attachmentName = getDefaultAttachmentName();
                }
                log.debug("found attachment [" + attachmentName + "] type [" + attachmentType + "] url ["
                        + attachmentUrl + "]contents [" + attachmentText + "]");

                messageBodyPart = new MimeBodyPart();

                DataSource attachmentDataSource;
                if (!StringUtils.isEmpty(attachmentUrl)) {
                    attachmentDataSource = new URLDataSource(new URL(attachmentUrl));
                    messageBodyPart.setDataHandler(new DataHandler(attachmentDataSource));
                }

                messageBodyPart.setFileName(attachmentName);

                if ("true".equalsIgnoreCase(attachmentBase64)) {
                    messageBodyPart.setDataHandler(decodeBase64(attachmentText));
                } else {
                    messageBodyPart.setText(attachmentText);
                }

                multipart.addBodyPart(messageBodyPart);
            }
            msg.setContent(multipart);
        }

        log.debug(sb.toString());
        msg.setSentDate(new Date());
        msg.saveChanges();
        // send the message
        putOnTransport(msg);
        // return the mail in mail-safe from
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        msg.writeTo(out);
        byte[] byteArray = out.toByteArray();
        return Misc.byteArrayToString(byteArray, "\n", false);
    } catch (Exception e) {
        throw new SenderException("MailSender got error", e);
    }
}

From source file:org.olat.core.util.mail.manager.MailManagerImpl.java

private MimeMessage createForwardMimeMessage(Address from, Address to, String subject, String body,
        List<DBMailAttachment> attachments, MailerResult result) {

    try {//from   w ww  . j  ava 2 s.  com
        Address convertedFrom = getRawEmailFromAddress(from);
        MimeMessage msg = createMessage(convertedFrom);
        msg.setFrom(from);
        msg.setSubject(subject, "utf-8");

        if (to != null) {
            msg.addRecipient(RecipientType.TO, to);
        }

        if (attachments != null && !attachments.isEmpty()) {
            // with attachment use multipart message
            Multipart multipart = new MimeMultipart();
            // 1) add body part
            BodyPart messageBodyPart = new MimeBodyPart();
            messageBodyPart.setText(body);
            multipart.addBodyPart(messageBodyPart);
            // 2) add attachments
            for (DBMailAttachment attachment : attachments) {
                // abort if attachment does not exist
                if (attachment == null || attachment.getSize() <= 0) {
                    result.setReturnCode(MailerResult.ATTACHMENT_INVALID);
                    logError("Tried to send mail wit attachment that does not exist::"
                            + (attachment == null ? null : attachment.getName()), null);
                    return msg;
                }
                messageBodyPart = new MimeBodyPart();

                VFSLeaf data = getAttachmentDatas(attachment);
                DataSource source = new VFSDataSource(attachment.getName(), attachment.getMimetype(), data);
                messageBodyPart.setDataHandler(new DataHandler(source));
                messageBodyPart.setFileName(attachment.getName());
                multipart.addBodyPart(messageBodyPart);
            }
            // Put parts in message
            msg.setContent(multipart);
        } else {
            // without attachment everything is easy, just set as text
            msg.setText(body, "utf-8");
        }
        msg.setSentDate(new Date());
        msg.saveChanges();
        return msg;
    } catch (MessagingException e) {
        logError("", e);
        return null;
    }
}

From source file:org.sakaiproject.tool.mailtool.Mailtool.java

public String processSendEmail() {
    /* EmailUser */ selected = m_recipientSelector.getSelectedUsers();
    if (m_selectByTree) {
        selectedGroupAwareRoleUsers = m_recipientSelector1.getSelectedUsers();
        selectedGroupUsers = m_recipientSelector2.getSelectedUsers();
        selectedSectionUsers = m_recipientSelector3.getSelectedUsers();

        selected.addAll(selectedGroupAwareRoleUsers);
        selected.addAll(selectedGroupUsers);
        selected.addAll(selectedSectionUsers);
    }/*from   w w w  .ja v a 2s .c  om*/
    // Put everyone in a set so the same person doesn't get multiple emails.
    Set emailusers = new TreeSet();
    if (isAllUsersSelected()) { // the button for this is inactivated ... leave for future 
        for (Iterator i = getEmailGroups().iterator(); i.hasNext();) {
            EmailGroup group = (EmailGroup) i.next();
            emailusers.addAll(group.getEmailusers());
        }
    }
    if (isAllGroupSelected()) {
        for (Iterator i = getEmailGroupsByType("section").iterator(); i.hasNext();) {
            EmailGroup group = (EmailGroup) i.next();
            if (group.getEmailrole().roletype.equals("section")) {
                selected.addAll(group.getEmailusers());
            }
        }
    }
    if (isAllSectionSelected()) {
        for (Iterator i = getEmailGroupsByType("group").iterator(); i.hasNext();) {
            EmailGroup group = (EmailGroup) i.next();
            if (group.getEmailrole().roletype.equals("group")) {
                selected.addAll(group.getEmailusers());
            }
        }
    }
    if (isAllGroupAwareRoleSelected()) {
        for (Iterator i = getEmailGroupsByType("role_groupaware").iterator(); i.hasNext();) {
            EmailGroup group = (EmailGroup) i.next();
            if (group.getEmailrole().roletype.equals("role_groupaware")) {
                selected.addAll(group.getEmailusers());
            }
        }
    }
    emailusers = new TreeSet(selected); // convert List to Set (remove duplicates)

    m_subjectprefix = getSubjectPrefixFromConfig();

    EmailUser curUser = getCurrentUser();

    String fromEmail = "";
    String fromDisplay = "";
    if (curUser != null) {
        fromEmail = curUser.getEmail();
        fromDisplay = curUser.getDisplayname();
    }
    String fromString = fromDisplay + " <" + fromEmail + ">";

    m_results = "Message sent to: <br>";

    String subject = m_subject;

    //Should we append this to the archive?
    String emailarchive = "/mailarchive/channel/" + m_siteid + "/main";
    if (m_archiveMessage && isEmailArchiveInSite()) {
        String attachment_info = "<br/>";
        Attachment a = null;
        Iterator iter = attachedFiles.iterator();
        int i = 0;
        while (iter.hasNext()) {
            a = (Attachment) iter.next();
            attachment_info += "<br/>";
            attachment_info += "Attachment #" + (i + 1) + ": " + a.getFilename() + "(" + a.getSize()
                    + " Bytes)";
            i++;
        }
        this.appendToArchive(emailarchive, fromString, subject, m_body + attachment_info);
    }
    List headers = new ArrayList();
    if (getTextFormat().equals("htmltext"))
        headers.add("content-type: text/html");
    else
        headers.add("content-type: text/plain");

    String smtp_server = ServerConfigurationService.getString("smtp@org.sakaiproject.email.api.EmailService");
    //String smtp_port = ServerConfigurationService.getString("smtp.port");
    try {
        Properties props = new Properties();
        props.put("mail.smtp.host", smtp_server);
        //props.put("mail.smtp.port", smtp_port);
        Session s = Session.getInstance(props, null);

        MimeMessage message = new MimeMessage(s);

        InternetAddress from = new InternetAddress(fromString);
        message.setFrom(from);
        String reply = getReplyToSelected().trim().toLowerCase();
        if (reply.equals("yes")) {
            // "reply to sender" is default. So do nothing
        } else if (reply.equals("no")) {
            String noreply = getSiteTitle() + " <noreply@" + smtp_server + ">";
            InternetAddress noreplyemail = new InternetAddress(noreply);
            message.setFrom(noreplyemail);
        } else if (reply.equals("otheremail") && getReplyToOtherEmail().equals("") != true) {
            // need input(email) validation
            InternetAddress replytoList[] = { new InternetAddress(getConfigParam("replyto").trim()) };
            message.setReplyTo(replytoList);
        }
        message.setSubject(subject);
        String text = m_body;
        String attachmentdirectory = getUploadDirectory();

        // Create the message part
        BodyPart messageBodyPart = new MimeBodyPart();

        // Fill the message
        String messagetype = "";

        if (getTextFormat().equals("htmltext")) {
            messagetype = "text/html";
        } else {
            messagetype = "text/plain";
        }
        messageBodyPart.setContent(text, messagetype);
        Multipart multipart = new MimeMultipart();
        multipart.addBodyPart(messageBodyPart);

        // Part two is attachment
        Attachment a = null;
        Iterator iter = attachedFiles.iterator();
        while (iter.hasNext()) {
            a = (Attachment) iter.next();
            messageBodyPart = new MimeBodyPart();
            DataSource source = new FileDataSource(
                    attachmentdirectory + this.getCurrentUser().getUserid() + "-" + a.getFilename());
            messageBodyPart.setDataHandler(new DataHandler(source));
            messageBodyPart.setFileName(a.getFilename());
            multipart.addBodyPart(messageBodyPart);
        }
        message.setContent(multipart);

        //Send the emails
        String recipientsString = "";
        for (Iterator i = emailusers.iterator(); i.hasNext(); recipientsString += ",") {
            EmailUser euser = (EmailUser) i.next();
            String toEmail = euser.getEmail(); // u.getEmail();
            String toDisplay = euser.getDisplayname(); // u.getDisplayName();
            // if AllUsers are selected, do not add current user's email to recipients
            if (isAllUsersSelected() && getCurrentUser().getEmail().equals(toEmail)) {
                // don't add sender to recipients
            } else {
                recipientsString += toEmail;
                m_results += toDisplay + (i.hasNext() ? "<br/>" : "");
            }
            //               InternetAddress to[] = {new InternetAddress(toEmail) };
            //               Transport.send(message,to);
        }
        if (m_otheremails.trim().equals("") != true) {
            //
            // multiple email validation is needed here
            //
            String refinedOtherEmailAddresses = m_otheremails.trim().replace(';', ',');
            recipientsString += refinedOtherEmailAddresses;
            m_results += "<br/>" + refinedOtherEmailAddresses;
            //               InternetAddress to[] = {new InternetAddress(refinedOtherEmailAddresses) };
            //               Transport.send(message, to);
        }
        if (m_sendmecopy) {
            message.addRecipients(Message.RecipientType.CC, fromEmail);
            // trying to solve SAK-7410
            // recipientsString+=fromEmail;
            //               InternetAddress to[] = {new InternetAddress(fromEmail) };
            //               Transport.send(message, to);
        }
        //            message.addRecipients(Message.RecipientType.TO, recipientsString);
        message.addRecipients(Message.RecipientType.BCC, recipientsString);

        Transport.send(message);
    } catch (Exception e) {
        log.debug("Mailtool Exception while trying to send the email: " + e.getMessage());
    }

    //   Clear the Subject and Body of the Message
    m_subject = getSubjectPrefix().equals("") ? getSubjectPrefixFromConfig() : getSubjectPrefix();
    m_otheremails = "";
    m_body = "";
    num_files = 0;
    attachedFiles.clear();
    m_recipientSelector = null;
    m_recipientSelector1 = null;
    m_recipientSelector2 = null;
    m_recipientSelector3 = null;
    setAllUsersSelected(false);
    setAllGroupSelected(false);
    setAllSectionSelected(false);

    //  Display Users with Bad Emails if the option is turned on.
    boolean showBadEmails = getDisplayInvalidEmailAddr();
    if (showBadEmails == true) {
        m_results += "<br/><br/>";

        List /* String */ badnames = new ArrayList();

        for (Iterator i = selected.iterator(); i.hasNext();) {
            EmailUser user = (EmailUser) i.next();
            /* This check should maybe be some sort of regular expression */
            if (user.getEmail().equals("")) {
                badnames.add(user.getDisplayname());
            }
        }
        if (badnames.size() > 0) {
            m_results += "The following users do not have valid email addresses:<br/>";
            for (Iterator i = badnames.iterator(); i.hasNext();) {
                String name = (String) i.next();
                if (i.hasNext() == true)
                    m_results += name + "/ ";
                else
                    m_results += name;
            }
        }
    }
    return "results";
}