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:org.fogbowcloud.manager.core.plugins.util.CloudInitUserDataBuilder.java

/**
 * Add given file <code>in</code> to the cloud-init mime message.
 * /* w ww.  j a v a  2 s . c o m*/
 * @param fileType
 * @param in
 *            file to add as readable
 * @return the builder
 * @throws IllegalArgumentException
 *             the given <code>fileType</code> was already added to this
 *             cloud-init mime message.
 */

public CloudInitUserDataBuilder addFile(FileType fileType, Readable in) throws IllegalArgumentException {
    Preconditions.checkNotNull(fileType, "'fileType' can NOT be null");
    Preconditions.checkNotNull(in, "'in' can NOT be null");
    //Preconditions.checkArgument(!alreadyAddedFileTypes.contains(fileType), "%s as already been added", fileType);
    alreadyAddedFileTypes.add(fileType);

    try {
        StringWriter sw = new StringWriter();
        CharStreams.copy(in, sw);
        MimeBodyPart mimeBodyPart = new MimeBodyPart();
        mimeBodyPart.setText(sw.toString(), charset.name(), fileType.getMimeTextSubType());
        mimeBodyPart.setFileName((userDataCounter++) + fileType.getFileName());
        userDataMultipart.addBodyPart(mimeBodyPart);

    } catch (IOException e) {
        throw Throwables.propagate(e);
    } catch (MessagingException e) {
        throw Throwables.propagate(e);
    }
    return this;
}

From source file:app.logica.gestores.GestorEmail.java

/**
 * Create a MimeMessage using the parameters provided.
 *
 * @param to//from ww w.  j  a v a2  s  .co m
 *            Email address of the receiver.
 * @param from
 *            Email address of the sender, the mailbox account.
 * @param subject
 *            Subject of the email.
 * @param bodyText
 *            Body text of the email.
 * @param file
 *            Path to the file to be attached.
 * @return MimeMessage to be used to send email.
 * @throws MessagingException
 */
private MimeMessage createEmailWithAttachment(String to, String from, String subject, String bodyText,
        File file) throws MessagingException, IOException {
    Properties props = new Properties();
    Session session = Session.getDefaultInstance(props, null);

    MimeMessage email = new MimeMessage(session);

    email.setFrom(new InternetAddress(from));
    email.addRecipient(javax.mail.Message.RecipientType.TO, new InternetAddress(to));
    email.setSubject(subject);

    MimeBodyPart mimeBodyPart = new MimeBodyPart();
    mimeBodyPart.setContent(bodyText, "text/plain");

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

    mimeBodyPart = new MimeBodyPart();
    DataSource source = new FileDataSource(file);

    mimeBodyPart.setDataHandler(new DataHandler(source));
    mimeBodyPart.setFileName(file.getName());

    multipart.addBodyPart(mimeBodyPart);
    email.setContent(multipart);

    return email;
}

From source file:fr.xebia.cloud.cloudinit.CloudInitUserDataBuilder.java

/**
 * Add given file <code>in</code> to the cloud-init mime message.
 * /*from   w  w  w  . ja  va2s.c  om*/
 * @param fileType
 * @param in
 *            file to add as readable
 * @return the builder
 * @throws IllegalArgumentException
 *             the given <code>fileType</code> was already added to this
 *             cloud-init mime message.
 */
@Nonnull
public CloudInitUserDataBuilder addFile(@Nonnull FileType fileType, @Nonnull Readable in)
        throws IllegalArgumentException {
    Preconditions.checkNotNull(fileType, "'fileType' can NOT be null");
    Preconditions.checkNotNull(in, "'in' can NOT be null");
    Preconditions.checkArgument(!alreadyAddedFileTypes.contains(fileType), "%s as already been added",
            fileType);
    alreadyAddedFileTypes.add(fileType);

    try {
        StringWriter sw = new StringWriter();
        CharStreams.copy(in, sw);
        MimeBodyPart mimeBodyPart = new MimeBodyPart();
        mimeBodyPart.setText(sw.toString(), charset.name(), fileType.getMimeTextSubType());
        mimeBodyPart.setFileName(fileType.getFileName());
        userDataMultipart.addBodyPart(mimeBodyPart);

    } catch (IOException e) {
        throw Throwables.propagate(e);
    } catch (MessagingException e) {
        throw Throwables.propagate(e);
    }
    return this;
}

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

@Test
public void testSimpleAttachment() throws MessagingException, IOException {
    Mailet mailet = initMailet();//from w  w  w  .  j a  v  a2 s .  co m

    MimeMessage message = new MimeMessage(Session.getDefaultInstance(new Properties()));

    MimeMultipart mm = new MimeMultipart();
    MimeBodyPart mp = new MimeBodyPart();
    mp.setText("simple text");
    mm.addBodyPart(mp);
    String body = "\u0023\u00A4\u00E3\u00E0\u00E9";
    MimeBodyPart mp2 = new MimeBodyPart(new ByteArrayInputStream(
            ("Content-Transfer-Encoding: 8bit\r\nContent-Type: application/octet-stream; charset=utf-8\r\n\r\n"
                    + body).getBytes("UTF-8")));
    mp2.setDisposition("attachment");
    mp2.setFileName("10.tmp");
    mm.addBodyPart(mp2);
    String body2 = "\u0014\u00A3\u00E1\u00E2\u00E4";
    MimeBodyPart mp3 = new MimeBodyPart(new ByteArrayInputStream(
            ("Content-Transfer-Encoding: 8bit\r\nContent-Type: application/octet-stream; charset=utf-8\r\n\r\n"
                    + body2).getBytes("UTF-8")));
    mp3.setDisposition("attachment");
    mp3.setFileName("temp.zip");
    mm.addBodyPart(mp3);
    message.setSubject("test");
    message.setContent(mm);
    message.saveChanges();

    Mail mail = FakeMail.builder().mimeMessage(message).build();

    mailet.service(mail);

    ByteArrayOutputStream rawMessage = new ByteArrayOutputStream();
    mail.getMessage().writeTo(rawMessage, new String[] { "Bcc", "Content-Length", "Message-ID" });

    @SuppressWarnings("unchecked")
    Collection<String> c = (Collection<String>) mail
            .getAttribute(StripAttachment.SAVED_ATTACHMENTS_ATTRIBUTE_KEY);
    Assert.assertNotNull(c);

    Assert.assertEquals(1, c.size());

    String name = c.iterator().next();

    File f = new File("./" + name);
    try {
        InputStream is = new FileInputStream(f);
        String savedFile = toString(is);
        is.close();
        Assert.assertEquals(body, savedFile);
    } finally {
        FileUtils.deleteQuietly(f);
    }
}

From source file:org.data2semantics.yasgui.selenium.FailNotification.java

private void sendMail(String subject, String content, String fileName) {
    Properties props = new Properties();
    props.put("mail.smtp.auth", "true");
    props.put("mail.smtp.starttls.enable", "true");
    props.put("mail.smtp.host", "smtp.gmail.com");
    props.put("mail.smtp.port", "587");

    Session session = Session.getInstance(props, new javax.mail.Authenticator() {
        protected PasswordAuthentication getPasswordAuthentication() {
            return new PasswordAuthentication(baseTest.props.getMailUserName(),
                    baseTest.props.getMailPassWord());
        }/*from   w  ww.ja va  2 s . c om*/
    });

    try {
        Message message = new MimeMessage(session);
        message.setFrom(new InternetAddress(baseTest.props.getMailUserName()));
        message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(baseTest.props.getMailSendTo()));
        message.setSubject(subject);
        message.setContent(content, "text/html; charset=utf-8");

        MimeBodyPart messageBodyPart = new MimeBodyPart();
        // message body
        messageBodyPart.setContent(content, "text/html; charset=utf-8");
        Multipart multipart = new MimeMultipart();
        multipart.addBodyPart(messageBodyPart);
        // attachment
        messageBodyPart = new MimeBodyPart();
        DataSource source = new FileDataSource(fileName);
        messageBodyPart.setDataHandler(new DataHandler(source));
        messageBodyPart.setFileName("screenshot.png");
        multipart.addBodyPart(messageBodyPart);
        message.setContent(multipart);

        Transport.send(message);

        System.out.println("Email send");

    } catch (MessagingException e) {
        throw new RuntimeException(e);
    }
}

From source file:com.szmslab.quickjavamail.send.MailSender.java

/**
 * MimeBodyPart????Content-Disposition: attachment
 *
 * @param file/* w  w  w  . jav a  2s .c o  m*/
 *            
 * @return MimeBodyPartContent-Disposition: attachment?
 * @throws MessagingException
 * @throws UnsupportedEncodingException
 */
private MimeBodyPart createAttachmentPart(AttachmentFile file)
        throws MessagingException, UnsupportedEncodingException {
    MimeBodyPart attachmentPart = new MimeBodyPart();
    attachmentPart.setFileName(MimeUtility.encodeText(file.getFileName(), charset, null));
    attachmentPart.setDataHandler(new DataHandler(file.getDataSource()));
    attachmentPart.setDisposition(MimeBodyPart.ATTACHMENT);
    return attachmentPart;
}

From source file:net.ymate.module.mailsender.impl.DefaultMailSendProvider.java

@Override
public IMailSendBuilder create(final MailSendServerCfgMeta serverCfgMeta) {
    return new AbstractMailSendBuilder() {
        @Override/* ww  w.  j a  v a2 s.  co  m*/
        public void send(final String content) throws Exception {
            __sendExecPool.execute(new Runnable() {
                @Override
                public void run() {
                    try {
                        MimeMessage _message = new MimeMessage(serverCfgMeta.createIfNeed());
                        //
                        for (String _to : getTo()) {
                            _message.addRecipient(Message.RecipientType.TO, new InternetAddress(_to));
                        }
                        for (String _cc : getCc()) {
                            _message.addRecipient(Message.RecipientType.CC, new InternetAddress(_cc));
                        }
                        for (String _bcc : getBcc()) {
                            _message.addRecipient(Message.RecipientType.BCC, new InternetAddress(_bcc));
                        }
                        //
                        if (getLevel() != null) {
                            switch (getLevel()) {
                            case LEVEL_HIGH:
                                _message.setHeader("X-MSMail-Priority", "High");
                                _message.setHeader("X-Priority", "1");
                                break;
                            case LEVEL_NORMAL:
                                _message.setHeader("X-MSMail-Priority", "Normal");
                                _message.setHeader("X-Priority", "3");
                                break;
                            case LEVEL_LOW:
                                _message.setHeader("X-MSMail-Priority", "Low");
                                _message.setHeader("X-Priority", "5");
                                break;
                            default:
                            }
                        }
                        //
                        String _charset = StringUtils.defaultIfEmpty(getCharset(), "UTF-8");
                        _message.setFrom(new InternetAddress(serverCfgMeta.getFromAddr(),
                                serverCfgMeta.getDisplayName(), _charset));
                        _message.setSubject(getSubject(), _charset);
                        // 
                        Multipart _container = new MimeMultipart();
                        // 
                        MimeBodyPart _textBodyPart = new MimeBodyPart();
                        if (getMimeType() == null) {
                            mimeType(IMailSender.MimeType.TEXT_PLAIN);
                        }
                        _textBodyPart.setContent(content, getMimeType().getMimeType() + ";charset=" + _charset);
                        _container.addBodyPart(_textBodyPart);
                        // ??<img src="cid:<CID_NAME>">
                        for (PairObject<String, File> _file : getAttachments()) {
                            if (_file.getValue() != null) {
                                MimeBodyPart _fileBodyPart = new MimeBodyPart();
                                FileDataSource _fileDS = new FileDataSource(_file.getValue());
                                _fileBodyPart.setDataHandler(new DataHandler(_fileDS));
                                if (_file.getKey() != null) {
                                    _fileBodyPart.setHeader("Content-ID", _file.getKey());
                                }
                                _fileBodyPart.setFileName(_fileDS.getName());
                                _container.addBodyPart(_fileBodyPart);
                            }
                        }
                        // ??
                        _message.setContent(_container);
                        Transport.send(_message);
                    } catch (Exception e) {
                        throw new RuntimeException(RuntimeUtils.unwrapThrow(e));
                    }
                }
            });
        }
    };
}

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

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

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

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

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

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

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

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

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

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

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

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

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

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

@Test
public void testToAndFromAttributes() throws MessagingException, IOException {
    Mailet strip = new StripAttachment();
    FakeMailetConfig mci = new FakeMailetConfig("Test", FakeMailContext.defaultContext());
    mci.setProperty("attribute", "my.attribute");
    mci.setProperty("remove", "all");
    mci.setProperty("notpattern", ".*\\.tmp.*");
    strip.init(mci);/*from www . ja v  a  2  s .  c om*/

    Mailet recover = new RecoverAttachment();
    FakeMailetConfig mci2 = new FakeMailetConfig("Test", FakeMailContext.defaultContext());
    mci2.setProperty("attribute", "my.attribute");
    recover.init(mci2);

    Mailet onlyText = new OnlyText();
    onlyText.init(new FakeMailetConfig("Test", FakeMailContext.defaultContext()));

    MimeMessage message = new MimeMessage(Session.getDefaultInstance(new Properties()));

    MimeMultipart mm = new MimeMultipart();
    MimeBodyPart mp = new MimeBodyPart();
    mp.setText("simple text");
    mm.addBodyPart(mp);
    String body = "\u0023\u00A4\u00E3\u00E0\u00E9";
    MimeBodyPart mp2 = new MimeBodyPart(new ByteArrayInputStream(
            ("Content-Transfer-Encoding: 8bit\r\nContent-Type: application/octet-stream; charset=utf-8\r\n\r\n"
                    + body).getBytes("UTF-8")));
    mp2.setDisposition("attachment");
    mp2.setFileName("=?iso-8859-15?Q?=E9_++++Pubblicit=E0_=E9_vietata____Milano9052.tmp?=");
    mm.addBodyPart(mp2);
    String body2 = "\u0014\u00A3\u00E1\u00E2\u00E4";
    MimeBodyPart mp3 = new MimeBodyPart(new ByteArrayInputStream(
            ("Content-Transfer-Encoding: 8bit\r\nContent-Type: application/octet-stream; charset=utf-8\r\n\r\n"
                    + body2).getBytes("UTF-8")));
    mp3.setDisposition("attachment");
    mp3.setFileName("temp.zip");
    mm.addBodyPart(mp3);
    message.setSubject("test");
    message.setContent(mm);
    message.saveChanges();
    Mail mail = FakeMail.builder().mimeMessage(message).build();

    Assert.assertTrue(mail.getMessage().getContent() instanceof MimeMultipart);
    Assert.assertEquals(3, ((MimeMultipart) mail.getMessage().getContent()).getCount());

    strip.service(mail);

    Assert.assertTrue(mail.getMessage().getContent() instanceof MimeMultipart);
    Assert.assertEquals(1, ((MimeMultipart) mail.getMessage().getContent()).getCount());

    onlyText.service(mail);

    Assert.assertFalse(mail.getMessage().getContent() instanceof MimeMultipart);

    Assert.assertEquals("simple text", mail.getMessage().getContent());

    // prova per caricare il mime message da input stream che altrimenti
    // javamail si comporta differentemente.
    String mimeSource = "Message-ID: <26194423.21197328775426.JavaMail.bago@bagovista>\r\nSubject: test\r\nMIME-Version: 1.0\r\nContent-Type: text/plain; charset=us-ascii\r\nContent-Transfer-Encoding: 7bit\r\n\r\nsimple text";

    MimeMessage mmNew = new MimeMessage(Session.getDefaultInstance(new Properties()),
            new ByteArrayInputStream(mimeSource.getBytes("UTF-8")));

    mmNew.writeTo(System.out);
    mail.setMessage(mmNew);

    recover.service(mail);

    Assert.assertTrue(mail.getMessage().getContent() instanceof MimeMultipart);
    Assert.assertEquals(2, ((MimeMultipart) mail.getMessage().getContent()).getCount());

    Object actual = ((MimeMultipart) mail.getMessage().getContent()).getBodyPart(1).getContent();
    if (actual instanceof ByteArrayInputStream) {
        Assert.assertEquals(body2, toString((ByteArrayInputStream) actual));
    } else {
        Assert.assertEquals(body2, actual);
    }

}

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

private MimeBodyPart createDSN(Mail originalMail) throws MessagingException {
    StringBuffer buffer = new StringBuffer();

    appendReportingMTA(buffer);/*from  w w  w  .j  a  v a2  s . c o m*/
    buffer.append("Received-From-MTA: dns; " + originalMail.getRemoteHost()).append(LINE_BREAK);

    for (MailAddress rec : originalMail.getRecipients()) {
        appendRecipient(buffer, rec, getDeliveryError(originalMail), originalMail.getLastUpdated());
    }

    MimeBodyPart bodyPart = new MimeBodyPart();
    bodyPart.setContent(buffer.toString(), "text/plain");
    bodyPart.setHeader("Content-Type", "message/delivery-status");
    bodyPart.setDescription("Delivery Status Notification");
    bodyPart.setFileName("status.dat");
    return bodyPart;
}