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:com.gamesalutes.utils.email.DefaultEmailServiceImpl.java

public void send(EmailModel model) throws EmailException {

    if (LOGGER.isDebugEnabled())
        LOGGER.debug("Sending email: " + model);

    if (model == null)
        throw new NullPointerException("model");

    Properties emailProps;//  w w  w. j  av  a  2  s  .c om
    Session emailSession;

    // set the relay host as a property of the email session
    emailProps = new Properties();
    emailProps.setProperty("mail.transport.protocol", "smtp");
    emailProps.put("mail.smtp.host", host);
    emailProps.setProperty("mail.smtp.port", String.valueOf(port));
    // set the timeouts
    emailProps.setProperty("mail.smtp.connectiontimeout", String.valueOf(SOCKET_CONNECT_TIMEOUT_MS));
    emailProps.setProperty("mail.smtp.timeout", String.valueOf(SOCKET_IO_TIMEOUT_MS));

    if (LOGGER.isDebugEnabled())
        LOGGER.debug("Email properties: " + emailProps);

    // set up email session
    emailSession = Session.getInstance(emailProps, null);
    emailSession.setDebug(false);

    String from;
    String displayFrom;

    String body;
    String subject;
    List<EmailAttachment> attachments;

    if (model.getFrom() == null)
        throw new NullPointerException("from");
    if (MiscUtils.isEmpty(model.getTo()) && MiscUtils.isEmpty(model.getBcc())
            && MiscUtils.isEmpty(model.getCc()))
        throw new IllegalArgumentException("model has no addresses");

    from = model.getFrom();
    displayFrom = model.getDisplayFrom();
    body = model.getBody();
    subject = model.getSubject();
    attachments = model.getAttachments();

    MimeMessage emailMessage;
    InternetAddress emailAddressFrom;

    // create an email message from the current session
    emailMessage = new MimeMessage(emailSession);

    // set the from
    try {
        emailAddressFrom = new InternetAddress(from, displayFrom);
        emailMessage.setFrom(emailAddressFrom);
    } catch (Exception e) {
        throw new IllegalStateException(e);
    }

    if (!MiscUtils.isEmpty(model.getTo()))
        setEmailRecipients(emailMessage, model.getTo(), RecipientType.TO);
    if (!MiscUtils.isEmpty(model.getCc()))
        setEmailRecipients(emailMessage, model.getCc(), RecipientType.CC);
    if (!MiscUtils.isEmpty(model.getBcc()))
        setEmailRecipients(emailMessage, model.getBcc(), RecipientType.BCC);

    try {

        if (!MiscUtils.isEmpty(subject))
            emailMessage.setSubject(subject);

        Multipart multipart = new MimeMultipart();

        if (body != null) {
            // create the message part
            MimeBodyPart messageBodyPart = new MimeBodyPart();

            //fill message
            String bodyContentType;
            //        body = Utils.base64Encode(body);
            bodyContentType = "text/html; charset=UTF-8";

            messageBodyPart.setContent(body, bodyContentType);
            //Content-Transfer-Encoding : base64
            //        messageBodyPart.addHeader("Content-Transfer-Encoding", "base64");
            multipart.addBodyPart(messageBodyPart);
        }
        // Part two is attachment
        if (attachments != null && !attachments.isEmpty()) {
            try {
                for (EmailAttachment a : attachments) {
                    MimeBodyPart attachBodyPart = new MimeBodyPart();
                    // don't base 64 encode
                    DataSource source = new StreamDataSource(
                            new DefaultStreamFactory(a.getInputStream(), false), a.getName(),
                            a.getContentType());
                    attachBodyPart.setDataHandler(new DataHandler(source));
                    attachBodyPart.setFileName(a.getName());
                    attachBodyPart.setHeader("Content-Type", a.getContentType());
                    attachBodyPart.addHeader("Content-Transfer-Encoding", "base64");

                    // add the attachment to the message
                    multipart.addBodyPart(attachBodyPart);

                }
            }
            // close all the input streams
            finally {
                for (EmailAttachment a : attachments)
                    MiscUtils.closeStream(a.getInputStream());
            }
        }

        // set the content
        emailMessage.setContent(multipart);
        emailMessage.saveChanges();

        if (LOGGER.isDebugEnabled())
            LOGGER.debug("Sending email message: " + emailMessage);

        Transport.send(emailMessage);

        if (LOGGER.isDebugEnabled())
            LOGGER.debug("Sending email complete.");

    } catch (Exception e) {
        throw new EmailException(e);
    }

}

From source file:de.betterform.connector.serializer.MultipartRelatedSerializer.java

public void serialize(Submission submission, Node node, SerializerRequestWrapper wrapper,
        String defaultEncoding) throws Exception {
    Map cache = new HashMap();
    MimeMultipart multipart = new MimeMultipart();

    MimeBodyPart part = new MimeBodyPart();
    multipart.addBodyPart(part);// w w  w  . j  ava  2  s  .c  o m

    String encoding = defaultEncoding;
    if (submission.getEncoding() != null) {
        encoding = submission.getEncoding();
    }

    if (node.getNodeType() == Node.ELEMENT_NODE || node.getNodeType() == Node.DOCUMENT_NODE) {
        part.setText(new String(serializeXML(multipart, cache, submission, node, encoding), encoding),
                encoding);
    } else {
        part.setText(node.getTextContent());
    }
    part.setContentID("<instance.xml@start>");
    part.addHeader("Content-Type", "application/xml");
    part.addHeader("Content-Transfer-Encoding", "base64");
    part.setDisposition("attachment");
    part.setFileName("instance.xml");

    multipart.setSubType("related; type=\"" + submission.getMediatype() + "\"; start=\"instance.xml@start\"");
    // FIXME: Is this a global http header or a local mime header?
    wrapper.getBodyStream()
            .write(("Content-Type: " + multipart.getContentType() + "\n\nThis is a MIME message.\n")
                    .getBytes(encoding));
    multipart.writeTo(wrapper.getBodyStream());
}

From source file:org.sakaiproject.tool.assessment.util.SamigoEmailService.java

public String send() {
    List attachmentList = null;/*from ww w. j a v  a  2s .c o  m*/
    AttachmentData a = null;
    try {
        Properties props = new Properties();

        // Server
        if (smtpServer == null || smtpServer.equals("")) {
            log.info("samigo.email.smtpServer is not set");
            smtpServer = ServerConfigurationService.getString("smtp@org.sakaiproject.email.api.EmailService");
            if (smtpServer == null || smtpServer.equals("")) {
                log.info("smtp@org.sakaiproject.email.api.EmailService is not set");
                log.error(
                        "Please set the value of samigo.email.smtpServer or smtp@org.sakaiproject.email.api.EmailService");
                return "error";
            }
        }
        props.setProperty("mail.smtp.host", smtpServer);

        // Port
        if (smtpPort == null || smtpPort.equals("")) {
            log.warn("samigo.email.smtpPort is not set. The default port 25 will be used.");
        } else {
            props.setProperty("mail.smtp.port", smtpPort);
        }

        Session session;
        session = Session.getInstance(props);
        session.setDebug(true);
        MimeMessage msg = new MimeMessage(session);

        InternetAddress fromIA = new InternetAddress(fromEmailAddress, fromName);
        msg.setFrom(fromIA);
        InternetAddress[] toIA = { new InternetAddress(toEmailAddress, toName) };
        msg.setRecipients(Message.RecipientType.TO, toIA);

        if ("yes".equals(ccMe)) {
            InternetAddress[] ccIA = { new InternetAddress(fromEmailAddress, fromName) };
            msg.setRecipients(Message.RecipientType.CC, ccIA);
        }
        msg.setSubject(subject);

        EmailBean emailBean = (EmailBean) ContextUtil.lookupBean("email");
        attachmentList = emailBean.getAttachmentList();
        StringBuilder content = new StringBuilder(message);
        ArrayList fileList = new ArrayList();
        ArrayList fileNameList = new ArrayList();
        if (attachmentList != null) {
            if (prefixedPath == null || prefixedPath.equals("")) {
                log.error("samigo.email.prefixedPath is not set");
                return "error";
            }
            Iterator iter = attachmentList.iterator();
            while (iter.hasNext()) {
                a = (AttachmentData) iter.next();
                if (a.getIsLink().booleanValue()) {
                    log.debug("send(): url");
                    content.append("<br/>\n\r");
                    content.append("<br/>"); // give a new line
                    content.append(a.getFilename());
                } else {
                    log.debug("send(): file");
                    File attachedFile = getAttachedFile(a.getResourceId());
                    fileList.add(attachedFile);
                    fileNameList.add(a.getFilename());
                }
            }
        }

        Multipart multipart = new MimeMultipart();
        MimeBodyPart messageBodyPart = new MimeBodyPart();
        messageBodyPart.setContent(content.toString(), "text/html");
        multipart.addBodyPart(messageBodyPart);
        msg.setContent(multipart);

        for (int i = 0; i < fileList.size(); i++) {
            messageBodyPart = new MimeBodyPart();
            FileDataSource source = new FileDataSource((File) fileList.get(i));
            messageBodyPart.setDataHandler(new DataHandler(source));
            messageBodyPart.setFileName((String) fileNameList.get(i));
            multipart.addBodyPart(messageBodyPart);
        }
        msg.setContent(multipart);

        Transport.send(msg);
    } catch (UnsupportedEncodingException e) {
        log.error("Exception throws from send()" + e.getMessage());
        return "error";
    } catch (MessagingException e) {
        log.error("Exception throws from send()" + e.getMessage());
        return "error";
    } catch (ServerOverloadException e) {
        log.error("Exception throws from send()" + e.getMessage());
        return "error";
    } catch (PermissionException e) {
        log.error("Exception throws from send()" + e.getMessage());
        return "error";
    } catch (IdUnusedException e) {
        log.error("Exception throws from send()" + e.getMessage());
        return "error";
    } catch (TypeException e) {
        log.error("Exception throws from send()" + e.getMessage());
        return "error";
    } catch (IOException e) {
        log.error("Exception throws from send()" + e.getMessage());
        return "error";
    } finally {
        if (attachmentList != null) {
            if (prefixedPath != null && !prefixedPath.equals("")) {
                StringBuilder sbPrefixedPath;
                Iterator iter = attachmentList.iterator();
                while (iter.hasNext()) {
                    sbPrefixedPath = new StringBuilder(prefixedPath);
                    sbPrefixedPath.append("/email_tmp/");
                    a = (AttachmentData) iter.next();
                    if (!a.getIsLink().booleanValue()) {
                        deleteAttachedFile(sbPrefixedPath.append(a.getResourceId()).toString());
                    }
                }
            }
        }
    }
    return "send";
}

From source file:org.apache.james.transport.mailets.DSNBounce.java

private MimeBodyPart createAttachedOriginal(Mail originalMail, TypeCode attachmentType)
        throws MessagingException {
    MimeBodyPart part = new MimeBodyPart();
    MimeMessage originalMessage = originalMail.getMessage();

    if (attachmentType.equals(TypeCode.HEADS)) {
        part.setContent(new MimeMessageUtils(originalMessage).getMessageHeaders(), "text/plain");
        part.setHeader("Content-Type", "text/rfc822-headers");
    } else {//from  www  .  j  a  v a2  s  . c  om
        part.setContent(originalMessage, "message/rfc822");
    }

    if ((originalMessage.getSubject() != null) && (originalMessage.getSubject().trim().length() > 0)) {
        part.setFileName(originalMessage.getSubject().trim());
    } else {
        part.setFileName("No Subject");
    }
    part.setDisposition("Attachment");
    return part;
}

From source file:com.xpn.xwiki.plugin.mailsender.MailSenderPlugin.java

/**
 * Add attachments to a multipart message
 * //from  w  ww.j  ava  2s  . co m
 * @param multipart Multipart message
 * @param attachments List of attachments
 */
public MimeBodyPart createAttachmentBodyPart(Attachment attachment, XWikiContext context)
        throws XWikiException, IOException, MessagingException {
    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;
}

From source file:org.apache.nifi.processors.standard.PutEmail.java

@Override
public void onTrigger(final ProcessContext context, final ProcessSession session) {
    final FlowFile flowFile = session.get();
    if (flowFile == null) {
        return;/*from w w w . j  av  a 2  s. co  m*/
    }

    final Properties properties = this.getMailPropertiesFromFlowFile(context, flowFile);

    final Session mailSession = this.createMailSession(properties);

    final Message message = new MimeMessage(mailSession);
    final ComponentLog logger = getLogger();

    try {
        message.addFrom(toInetAddresses(context, flowFile, FROM));
        message.setRecipients(RecipientType.TO, toInetAddresses(context, flowFile, TO));
        message.setRecipients(RecipientType.CC, toInetAddresses(context, flowFile, CC));
        message.setRecipients(RecipientType.BCC, toInetAddresses(context, flowFile, BCC));

        message.setHeader("X-Mailer",
                context.getProperty(HEADER_XMAILER).evaluateAttributeExpressions(flowFile).getValue());
        message.setSubject(context.getProperty(SUBJECT).evaluateAttributeExpressions(flowFile).getValue());
        String messageText = context.getProperty(MESSAGE).evaluateAttributeExpressions(flowFile).getValue();

        if (context.getProperty(INCLUDE_ALL_ATTRIBUTES).asBoolean()) {
            messageText = formatAttributes(flowFile, messageText);
        }

        String contentType = context.getProperty(CONTENT_TYPE).evaluateAttributeExpressions(flowFile)
                .getValue();
        message.setContent(messageText, contentType);
        message.setSentDate(new Date());

        if (context.getProperty(ATTACH_FILE).asBoolean()) {
            final MimeBodyPart mimeText = new PreencodedMimeBodyPart("base64");
            mimeText.setDataHandler(new DataHandler(new ByteArrayDataSource(
                    Base64.encodeBase64(messageText.getBytes("UTF-8")), contentType + "; charset=\"utf-8\"")));
            final MimeBodyPart mimeFile = new MimeBodyPart();
            session.read(flowFile, new InputStreamCallback() {
                @Override
                public void process(final InputStream stream) throws IOException {
                    try {
                        mimeFile.setDataHandler(
                                new DataHandler(new ByteArrayDataSource(stream, "application/octet-stream")));
                    } catch (final Exception e) {
                        throw new IOException(e);
                    }
                }
            });

            mimeFile.setFileName(flowFile.getAttribute(CoreAttributes.FILENAME.key()));
            MimeMultipart multipart = new MimeMultipart();
            multipart.addBodyPart(mimeText);
            multipart.addBodyPart(mimeFile);
            message.setContent(multipart);
        }

        send(message);

        session.getProvenanceReporter().send(flowFile, "mailto:" + message.getAllRecipients()[0].toString());
        session.transfer(flowFile, REL_SUCCESS);
        logger.info("Sent email as a result of receiving {}", new Object[] { flowFile });
    } catch (final ProcessException | MessagingException | IOException e) {
        context.yield();
        logger.error("Failed to send email for {}: {}; routing to failure",
                new Object[] { flowFile, e.getMessage() }, e);
        session.transfer(flowFile, REL_FAILURE);
    }
}

From source file:com.panet.imeta.trans.steps.mail.Mail.java

private void addAttachedFilePart(FileObject file) throws Exception {
    // create a data source

    MimeBodyPart files = new MimeBodyPart();
    // create a data source
    URLDataSource fds = new URLDataSource(file.getURL());
    // get a data Handler to manipulate this file type;
    files.setDataHandler(new DataHandler(fds));
    // include the file in the data source
    files.setFileName(file.getName().getBaseName());
    // add the part with the file in the BodyPart();
    data.parts.addBodyPart(files);/* w  ww.  j  ava 2  s  .co m*/
    if (log.isDetailed())
        log.logDetailed(toString(), Messages.getString("Mail.Log.AttachedFile", fds.getName()));

}

From source file:org.apache.james.transport.mailets.managesieve.ManageSieveMailetTestCase.java

private MimeMessage prepareMessageWithAttachment(String scriptContent, String subject)
        throws MessagingException, IOException {
    MimeMessage message = prepareMimeMessage(subject);
    MimeMultipart multipart = new MimeMultipart();
    MimeBodyPart scriptPart = new MimeBodyPart();
    scriptPart.setDataHandler(//from ww w.  java2  s .  c  om
            new DataHandler(new ByteArrayDataSource(scriptContent, "application/sieve; charset=UTF-8")));
    scriptPart.setDisposition(MimeBodyPart.ATTACHMENT);
    // setting a DataHandler with no mailcap definition is not
    // supported by the specs. Javamail activation still work,
    // but Geronimo activation translate it to text/plain.
    // Let's manually force the header.
    scriptPart.setHeader("Content-Type", "application/sieve; charset=UTF-8");
    scriptPart.setFileName(SCRIPT_NAME);
    multipart.addBodyPart(scriptPart);
    message.setContent(multipart);
    message.saveChanges();
    return message;
}

From source file:com.youxifan.utils.EMail.java

/**
 *   Set the message content//from   w ww .j  av a  2  s  .  c o m
 *    @throws MessagingException
 *    @throws IOException
 */
private void setContent() throws MessagingException, IOException {
    //   Local Character Set
    String charSetName;
    if (m_encoding == null) {
        charSetName = System.getProperty("file.encoding"); //   Cp1252
        if (charSetName == null || charSetName.length() == 0)
            charSetName = "UTF-8"; // WebEnv.ENCODING - alternative iso-8859-1
    } else {
        charSetName = m_encoding;
    }
    m_msg.setSubject(getSubject(), charSetName);

    //   Simple Message
    if (m_attachments == null || m_attachments.size() == 0) {
        if (m_messageHTML == null || m_messageHTML.length() == 0)
            m_msg.setText(getMessageCRLF(), charSetName);
        else
            m_msg.setDataHandler(
                    new DataHandler(new ByteArrayDataSource(m_messageHTML, charSetName, "text/html")));
        //
        log.info("(simple) " + getSubject());
    } else //   Multi part message   ***************************************
    {
        //   First Part - Message
        MimeBodyPart mbp_1 = new MimeBodyPart();
        mbp_1.setText("");
        if (m_messageHTML == null || m_messageHTML.length() == 0)
            mbp_1.setText(getMessageCRLF(), charSetName);
        else
            mbp_1.setDataHandler(
                    new DataHandler(new ByteArrayDataSource(m_messageHTML, charSetName, "text/html")));

        // Create Multipart and its parts to it
        Multipart mp = new MimeMultipart();
        mp.addBodyPart(mbp_1);
        log.info("(multi) " + getSubject() + " - " + mbp_1);

        //   for all attachments
        for (int i = 0; i < m_attachments.size(); i++) {
            Object attachment = m_attachments.get(i);
            DataSource ds = null;
            if (attachment instanceof File) {
                File file = (File) attachment;
                if (file.exists())
                    ds = new FileDataSource(file);
                else {
                    log.warn("File does not exist: " + file);
                    continue;
                }
            } else if (attachment instanceof URL) {
                URL url = (URL) attachment;
                ds = new URLDataSource(url);
            } else if (attachment instanceof DataSource)
                ds = (DataSource) attachment;
            else {
                log.warn("Attachement type unknown: " + attachment);
                continue;
            }
            //   Attachment Part
            MimeBodyPart mbp_2 = new MimeBodyPart();
            mbp_2.setDataHandler(new DataHandler(ds));
            mbp_2.setFileName(ds.getName());
            log.info("Added Attachment " + ds.getName() + " - " + mbp_2);
            mp.addBodyPart(mbp_2);
        }

        //   Add to Message
        m_msg.setContent(mp);
    } //   multi=part
}

From source file:userInterface.EnergySourceBoardSupervisor.ManageEnergyConsumptionsJPanel.java

public void sendMailToCommunityMember(String to, String subject, String message, String from, String password) {
    String host = "smtp.gmail.com";
    message = "Some of the appliances in your house are running inefficient." + "\n"
            + "Kindly check or replace your appliance " + "\n"
            + "Check the attachment for details or visit your account";
    Properties props = System.getProperties();
    props.put("mail.smtp.auth", "true");
    props.put("mail.smtp.starttls.enable", "true");
    props.put("mail.smtp.host", host);
    props.put("mail.smtp.port", 587);
    props.put("mail.smtp.user", from);

    Session session = Session.getDefaultInstance(props);
    MimeMessage mimeMessage = new MimeMessage(session);
    try {/* w ww.  j  a  va 2  s.  c o m*/
        mimeMessage.setFrom(new InternetAddress(from));
        mimeMessage.setRecipients(Message.RecipientType.TO, InternetAddress.parse(to));
        mimeMessage.setSubject("Alert from Energy Board");

        MimeBodyPart messageBodyPart = new MimeBodyPart();
        messageBodyPart.setText(message);
        Multipart multipart = new MimeMultipart();
        multipart.addBodyPart(messageBodyPart);

        messageBodyPart = new MimeBodyPart();
        DataSource source = new FileDataSource(path);
        messageBodyPart.setDataHandler(new DataHandler(source));
        messageBodyPart.setFileName(name_attach.getText() + ".png");
        multipart.addBodyPart(messageBodyPart);
        mimeMessage.setContent(multipart);

        SMTPTransport transport = (SMTPTransport) session.getTransport("smtps");
        transport.connect(host, from, password);
        transport.sendMessage(mimeMessage, mimeMessage.getAllRecipients());
        System.out.println("sent");
        transport.close();
    } catch (MessagingException me) {

    }
}