Search in sources :

Example 86 with DataSource

use of javax.activation.DataSource in project SpringStepByStep by JavaProgrammerLB.

the class SendHTMLEmailWithTemplate method main.

public static void main(String[] args) throws Exception {
    Properties props = new Properties();
    try {
        props.load(new FileInputStream(new File("settings.properties")));
    } catch (FileNotFoundException e1) {
        e1.printStackTrace();
    } catch (IOException e1) {
        e1.printStackTrace();
    }
    Session session = Session.getDefaultInstance(props, new Authenticator() {

        protected PasswordAuthentication getPasswordAuthentication() {
            return new PasswordAuthentication("username", "******");
        }
    });
    try {
        Message message = new MimeMessage(session);
        message.setFrom(new InternetAddress("from@gmail.com"));
        message.setRecipients(Message.RecipientType.TO, InternetAddress.parse("to@gmail.com"));
        message.setSubject("Testing Subject");
        BodyPart body = new MimeBodyPart();
        // freemarker stuff.
        Configuration cfg = new Configuration();
        Template template = cfg.getTemplate("html-mail-template.ftl");
        Map<String, String> rootMap = new HashMap<String, String>();
        rootMap.put("to", "liubei");
        rootMap.put("body", "Sample html email using freemarker");
        rootMap.put("from", "liubei");
        Writer out = new StringWriter();
        template.process(rootMap, out);
        // freemarker stuff ends.
        /* you can add html tags in your text to decorate it. */
        body.setContent(out.toString(), "text/html");
        Multipart multipart = new MimeMultipart();
        multipart.addBodyPart(body);
        body = new MimeBodyPart();
        String filename = "hello.txt";
        DataSource source = new FileDataSource(filename);
        body.setDataHandler(new DataHandler(source));
        body.setFileName(filename);
        multipart.addBodyPart(body);
        message.setContent(multipart, "text/html;charset=utf-8");
        Transport.send(message);
    } catch (MessagingException e) {
        e.printStackTrace();
    }
    System.out.println("Done....");
}
Also used : MimeBodyPart(javax.mail.internet.MimeBodyPart) BodyPart(javax.mail.BodyPart) InternetAddress(javax.mail.internet.InternetAddress) Multipart(javax.mail.Multipart) MimeMultipart(javax.mail.internet.MimeMultipart) Message(javax.mail.Message) MimeMessage(javax.mail.internet.MimeMessage) Configuration(freemarker.template.Configuration) HashMap(java.util.HashMap) FileNotFoundException(java.io.FileNotFoundException) DataHandler(javax.activation.DataHandler) Properties(java.util.Properties) Template(freemarker.template.Template) StringWriter(java.io.StringWriter) MimeMessage(javax.mail.internet.MimeMessage) MimeMultipart(javax.mail.internet.MimeMultipart) FileDataSource(javax.activation.FileDataSource) Authenticator(javax.mail.Authenticator) PasswordAuthentication(javax.mail.PasswordAuthentication) MessagingException(javax.mail.MessagingException) IOException(java.io.IOException) FileInputStream(java.io.FileInputStream) FileDataSource(javax.activation.FileDataSource) DataSource(javax.activation.DataSource) MimeBodyPart(javax.mail.internet.MimeBodyPart) File(java.io.File) StringWriter(java.io.StringWriter) Writer(java.io.Writer) Session(javax.mail.Session)

Example 87 with DataSource

use of javax.activation.DataSource in project wildfly by wildfly.

the class JaxrsMultipartProviderTestCase method testJaxRsWithNoApplication.

@Test
public void testJaxRsWithNoApplication() throws Exception {
    String result = performCall("myjaxrs/form");
    DataSource mimeData = new ByteArrayDataSource(result.getBytes(StandardCharsets.UTF_8), "multipart/related");
    MimeMultipart mime = new MimeMultipart(mimeData);
    String string = (String) mime.getBodyPart(0).getContent();
    Assert.assertEquals("Hello", string);
    string = (String) mime.getBodyPart(1).getContent();
    Assert.assertEquals("World", string);
}
Also used : MimeMultipart(javax.mail.internet.MimeMultipart) ByteArrayDataSource(javax.mail.util.ByteArrayDataSource) ByteArrayDataSource(javax.mail.util.ByteArrayDataSource) DataSource(javax.activation.DataSource) Test(org.junit.Test)

Example 88 with DataSource

use of javax.activation.DataSource in project tomee by apache.

the class AttachmentUtil method createAttachment.

public static Attachment createAttachment(InputStream stream, Map<String, List<String>> headers) throws IOException {
    String id = cleanContentId(getHeader(headers, "Content-ID"));
    AttachmentImpl att = new AttachmentImpl(id);
    final String ct = getHeader(headers, "Content-Type");
    String cd = getHeader(headers, "Content-Disposition");
    String fileName = getContentDispositionFileName(cd);
    String encoding = null;
    for (Map.Entry<String, List<String>> e : headers.entrySet()) {
        String name = e.getKey();
        if ("Content-Transfer-Encoding".equalsIgnoreCase(name)) {
            encoding = getHeader(headers, name);
            if (BINARY.equalsIgnoreCase(encoding)) {
                att.setXOP(true);
            }
        }
        att.setHeader(name, getHeaderValue(e.getValue()));
    }
    if (encoding == null) {
        encoding = BINARY;
    }
    InputStream ins = decode(stream, encoding);
    if (ins != stream) {
        headers.remove("Content-Transfer-Encoding");
    }
    DataSource source = new AttachmentDataSource(ct, ins);
    if (!StringUtils.isEmpty(fileName)) {
        ((AttachmentDataSource) source).setName(FileUtils.stripPath(fileName));
    }
    att.setDataHandler(new DataHandler(source));
    return att;
}
Also used : InputStream(java.io.InputStream) ArrayList(java.util.ArrayList) List(java.util.List) DataHandler(javax.activation.DataHandler) LinkedHashMap(java.util.LinkedHashMap) CommandMap(javax.activation.CommandMap) Map(java.util.Map) MailcapCommandMap(javax.activation.MailcapCommandMap) AbstractMap(java.util.AbstractMap) FileDataSource(javax.activation.FileDataSource) URLDataSource(javax.activation.URLDataSource) DataSource(javax.activation.DataSource)

Example 89 with DataSource

use of javax.activation.DataSource in project tomee by apache.

the class MultipartProvider method createDataHandler.

private <T> Attachment createDataHandler(T obj, Class<T> cls, Type genericType, Annotation[] anns, String mimeType, String mainMediaType, int id) throws IOException {
    final DataHandler dh;
    if (InputStream.class.isAssignableFrom(obj.getClass())) {
        dh = createInputStreamDH((InputStream) obj, mimeType);
    } else if (DataHandler.class.isAssignableFrom(obj.getClass())) {
        dh = (DataHandler) obj;
    } else if (DataSource.class.isAssignableFrom(obj.getClass())) {
        dh = new DataHandler((DataSource) obj);
    } else if (File.class.isAssignableFrom(obj.getClass())) {
        File f = (File) obj;
        ContentDisposition cd = mainMediaType.startsWith(MediaType.MULTIPART_FORM_DATA) ? new ContentDisposition("form-data;name=file;filename=" + f.getName()) : null;
        return new Attachment(AttachmentUtil.BODY_ATTACHMENT_ID, Files.newInputStream(f.toPath()), cd);
    } else if (Attachment.class.isAssignableFrom(obj.getClass())) {
        Attachment att = (Attachment) obj;
        if (att.getObject() == null) {
            return att;
        }
        dh = getHandlerForObject(att.getObject(), att.getObject().getClass(), new Annotation[] {}, att.getContentType().toString(), id);
        return new Attachment(att.getContentId(), dh, att.getHeaders());
    } else if (byte[].class.isAssignableFrom(obj.getClass())) {
        ByteDataSource source = new ByteDataSource((byte[]) obj);
        source.setContentType(mimeType);
        dh = new DataHandler(source);
    } else {
        dh = getHandlerForObject(obj, cls, genericType, anns, mimeType);
    }
    String contentId = getContentId(anns, id);
    MultivaluedMap<String, String> headers = new MetadataMap<>();
    headers.putSingle("Content-Type", mimeType);
    return new Attachment(contentId, dh, headers);
}
Also used : MetadataMap(org.apache.cxf.jaxrs.impl.MetadataMap) ByteDataSource(org.apache.cxf.attachment.ByteDataSource) ContentDisposition(org.apache.cxf.jaxrs.ext.multipart.ContentDisposition) InputStream(java.io.InputStream) Attachment(org.apache.cxf.jaxrs.ext.multipart.Attachment) DataHandler(javax.activation.DataHandler) File(java.io.File) Annotation(java.lang.annotation.Annotation) InputStreamDataSource(org.apache.cxf.jaxrs.ext.multipart.InputStreamDataSource) ByteDataSource(org.apache.cxf.attachment.ByteDataSource) DataSource(javax.activation.DataSource)

Example 90 with DataSource

use of javax.activation.DataSource in project openolat by klemens.

the class MailManagerImpl method createForwardMimeMessage.

private MimeMessage createForwardMimeMessage(Address from, Address to, String subject, String body, List<DBMailAttachment> attachments, MailerResult result) {
    try {
        MimeMessage msg = createMessage(subject, from);
        if (to != null) {
            msg.addRecipient(RecipientType.TO, to);
        }
        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 (DBMailAttachment attachment : attachments) {
                // abort if attachment does not exist
                if (attachment == null || attachment.getSize() <= 0) {
                    result.setReturnCode(MailerResult.ATTACHMENT_INVALID);
                    log.error("Tried to send mail wit attachment that does not exist::" + (attachment == null ? null : attachment.getName()), null);
                    return msg;
                }
                BodyPart 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
            if (StringHelper.isHtml(body)) {
                msg.setContent(createMultipartAlternative(body));
            } else {
                msg.setText(body, "utf-8");
            }
        }
        msg.setSentDate(new Date());
        msg.saveChanges();
        return msg;
    } catch (MessagingException | UnsupportedEncodingException e) {
        log.error("", e);
        return null;
    }
}
Also used : BodyPart(javax.mail.BodyPart) MimeBodyPart(javax.mail.internet.MimeBodyPart) VFSLeaf(org.olat.core.util.vfs.VFSLeaf) MimeMultipart(javax.mail.internet.MimeMultipart) Multipart(javax.mail.Multipart) MessagingException(javax.mail.MessagingException) UnsupportedEncodingException(java.io.UnsupportedEncodingException) DataHandler(javax.activation.DataHandler) Date(java.util.Date) FileDataSource(javax.activation.FileDataSource) DataSource(javax.activation.DataSource) DBMailAttachment(org.olat.core.util.mail.model.DBMailAttachment) MimeMessage(javax.mail.internet.MimeMessage) MimeMultipart(javax.mail.internet.MimeMultipart) MimeBodyPart(javax.mail.internet.MimeBodyPart)

Aggregations

DataSource (javax.activation.DataSource)196 DataHandler (javax.activation.DataHandler)114 FileDataSource (javax.activation.FileDataSource)60 MimeBodyPart (javax.mail.internet.MimeBodyPart)53 MimeMultipart (javax.mail.internet.MimeMultipart)48 MimeMessage (javax.mail.internet.MimeMessage)39 InputStream (java.io.InputStream)37 IOException (java.io.IOException)36 ByteArrayDataSource (javax.mail.util.ByteArrayDataSource)35 ByteArrayInputStream (java.io.ByteArrayInputStream)33 File (java.io.File)33 ByteArrayOutputStream (java.io.ByteArrayOutputStream)30 Test (org.junit.Test)30 InternetAddress (javax.mail.internet.InternetAddress)27 Properties (java.util.Properties)26 MessagingException (javax.mail.MessagingException)25 Multipart (javax.mail.Multipart)24 Session (javax.mail.Session)21 BodyPart (javax.mail.BodyPart)19 ArrayList (java.util.ArrayList)16