Search in sources :

Example 56 with DataHandler

use of javax.activation.DataHandler 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 57 with DataHandler

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

the class SendAttachmentInEmail method main.

public static void main(String[] args) {
    // Recipient's email ID needs to be mentioned.
    String to = "destinationemail@gmail.com";
    // Sender's email ID needs to be mentioned
    String from = "fromemail@gmail.com";
    //change accordingly
    final String username = "manishaspatil";
    //change accordingly
    final String password = "******";
    // Assuming you are sending email through relay.jangosmtp.net
    String host = "relay.jangosmtp.net";
    Properties props = new Properties();
    props.put("mail.smtp.auth", "true");
    props.put("mail.smtp.starttls.enable", "true");
    props.put("mail.smtp.host", host);
    props.put("mail.smtp.port", "25");
    // Get the Session object.
    Session session = Session.getInstance(props, new javax.mail.Authenticator() {

        protected PasswordAuthentication getPasswordAuthentication() {
            return new PasswordAuthentication(username, password);
        }
    });
    try {
        // Create a default MimeMessage object.
        Message message = new MimeMessage(session);
        // Set From: header field of the header.
        message.setFrom(new InternetAddress(from));
        // Set To: header field of the header.
        message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(to));
        // Set Subject: header field
        message.setSubject("Testing Subject");
        // Create the message part
        BodyPart messageBodyPart = new MimeBodyPart();
        // Now set the actual message
        messageBodyPart.setText("This is message body");
        // Create a multipar message
        Multipart multipart = new MimeMultipart();
        // Set text message part
        multipart.addBodyPart(messageBodyPart);
        // Part two is attachment
        messageBodyPart = new MimeBodyPart();
        String filename = "/home/manisha/file.txt";
        DataSource source = new FileDataSource(filename);
        messageBodyPart.setDataHandler(new DataHandler(source));
        messageBodyPart.setFileName(filename);
        multipart.addBodyPart(messageBodyPart);
        // Send the complete message parts
        message.setContent(multipart);
        // Send message
        Transport.send(message);
        System.out.println("Sent message successfully....");
    } catch (MessagingException e) {
        throw new RuntimeException(e);
    }
}
Also used : MimeBodyPart(javax.mail.internet.MimeBodyPart) BodyPart(javax.mail.BodyPart) InternetAddress(javax.mail.internet.InternetAddress) MimeMultipart(javax.mail.internet.MimeMultipart) Multipart(javax.mail.Multipart) Message(javax.mail.Message) MimeMessage(javax.mail.internet.MimeMessage) MessagingException(javax.mail.MessagingException) DataHandler(javax.activation.DataHandler) Properties(java.util.Properties) FileDataSource(javax.activation.FileDataSource) DataSource(javax.activation.DataSource) MimeMessage(javax.mail.internet.MimeMessage) MimeMultipart(javax.mail.internet.MimeMultipart) FileDataSource(javax.activation.FileDataSource) MimeBodyPart(javax.mail.internet.MimeBodyPart) Session(javax.mail.Session) PasswordAuthentication(javax.mail.PasswordAuthentication)

Example 58 with DataHandler

use of javax.activation.DataHandler in project nhin-d by DirectProject.

the class MDNFactory method create.

/**
     * Answers a MimeMultipartReport containing a
     * Message Delivery Notification as specified by RFC 2298.
     * 
     * @param humanText
     * @param reporting_UA_name
     * @param reporting_UA_product
     * @param original_recipient
     * @param final_recipient
     * @param original_message_id
     * @param disposition
     * @return MimeMultipartReport
     * @throws MessagingException
     */
public static MimeMultipartReport create(String humanText, String reporting_UA_name, String reporting_UA_product, String original_recipient, String final_recipient, String original_message_id, String error, MdnGateway gateway, Disposition disposition) throws MessagingException {
    if (disposition == null)
        throw new IllegalArgumentException("Disposition can not be null.");
    // Create the message parts. According to RFC 2298, there are two
    // compulsory parts and one optional part...
    MimeMultipartReport multiPart = new MimeMultipartReport();
    multiPart.setReportType("disposition-notification");
    // Part 1: The 'human-readable' part
    MimeBodyPart humanPart = new MimeBodyPart();
    humanPart.setText(humanText);
    multiPart.addBodyPart(humanPart);
    // Part 2: MDN Report Part
    // 1) reporting-ua-field
    StringBuilder mdnReport = new StringBuilder(128);
    if (reporting_UA_name != null && !reporting_UA_name.isEmpty()) {
        mdnReport.append("Reporting-UA: ");
        mdnReport.append((reporting_UA_name == null ? "" : reporting_UA_name));
        mdnReport.append("; ");
        mdnReport.append((reporting_UA_product == null ? "" : reporting_UA_product));
        mdnReport.append("\r\n");
    }
    // 2) original-recipient-field
    if (original_recipient != null && !original_recipient.isEmpty()) {
        mdnReport.append("Original-Recipient: ");
        mdnReport.append("rfc822; ");
        mdnReport.append(original_recipient);
        mdnReport.append("\r\n");
    }
    // 3) final-recipient-field
    if (final_recipient != null && !final_recipient.isEmpty()) {
        mdnReport.append("Final-Recipient: ");
        mdnReport.append("rfc822; ");
        mdnReport.append(final_recipient);
        mdnReport.append("\r\n");
    }
    // 4) original-message-id-field
    if (original_message_id != null && !original_message_id.isEmpty()) {
        mdnReport.append("Original-Message-ID: ");
        mdnReport.append(original_message_id);
        mdnReport.append("\r\n");
    }
    // 5) mdn-gateway-field
    if (gateway != null) {
        mdnReport.append("MDN-Gateway: ");
        mdnReport.append(gateway.toString());
        mdnReport.append("\r\n");
    }
    // 6) error-field
    if (error != null && !error.isEmpty()) {
        mdnReport.append("Error: ");
        mdnReport.append(error);
        mdnReport.append("\r\n");
    }
    mdnReport.append(disposition.toString());
    mdnReport.append("\r\n");
    MimeBodyPart mdnPart = new MimeBodyPart();
    try {
        // using a DataSource gets around some of the issues with the JAF dynamically loading content handlers that may not work, speicifically
        // the java dsn library and the DispostionNotification class which doesn't know how to handle byte arrays
        ByteArrayDataSource dataSource = new ByteArrayDataSource(new ByteArrayInputStream(mdnReport.toString().getBytes()), "message/disposition-notification");
        mdnPart.setDataHandler(new DataHandler(dataSource));
        multiPart.addBodyPart(mdnPart);
    } catch (IOException e) {
    /*no-op*/
    }
    // described in RFC 1892. It would be a useful addition!        
    return multiPart;
}
Also used : MimeMultipartReport(org.apache.mailet.base.mail.MimeMultipartReport) ByteArrayInputStream(java.io.ByteArrayInputStream) DataHandler(javax.activation.DataHandler) IOException(java.io.IOException) MimeBodyPart(javax.mail.internet.MimeBodyPart) ByteArrayDataSource(javax.mail.util.ByteArrayDataSource)

Example 59 with DataHandler

use of javax.activation.DataHandler in project stanbol by apache.

the class SimpleMailExtractor method processContent.

// the recursive part
protected void processContent(Object content, StringBuilder buffer, RDFContainer rdf) throws MessagingException, IOException, ExtractorException {
    if (content instanceof String) {
        buffer.append(content);
        buffer.append(' ');
    } else if (content instanceof BodyPart) {
        BodyPart bodyPart = (BodyPart) content;
        DataHandler handler = bodyPart.getDataHandler();
        String encoding = null;
        if (handler != null) {
            encoding = MimeUtility.getEncoding(handler);
        }
        String fileName = bodyPart.getFileName();
        String contentType = bodyPart.getContentType();
        if (fileName != null) {
            try {
                fileName = MimeUtility.decodeWord(fileName);
            } catch (MessagingException e) {
            // happens on unencoded file names! so just ignore it and leave the file name as it is
            }
            URI attachURI = URIGenerator.createNewRandomUniqueURI();
            rdf.add(NMO.hasAttachment, attachURI);
            Model m = rdf.getModel();
            m.addStatement(attachURI, RDF.type, NFO.Attachment);
            m.addStatement(attachURI, NFO.fileName, fileName);
            if (handler != null) {
                if (encoding != null) {
                    m.addStatement(attachURI, NFO.encoding, encoding);
                }
            }
            if (contentType != null) {
                contentType = (new ContentType(contentType)).getBaseType();
                m.addStatement(attachURI, NIE.mimeType, contentType.trim());
            }
        // TODO: encoding?
        }
        // append the content, if any
        content = bodyPart.getContent();
        // remove any html markup if necessary
        if (contentType != null && content instanceof String) {
            contentType = contentType.toLowerCase();
            if (contentType.indexOf("text/html") >= 0) {
                if (encoding != null) {
                    encoding = MimeUtility.javaCharset(encoding);
                }
                content = extractTextFromHtml((String) content, encoding, rdf);
            }
        }
        processContent(content, buffer, rdf);
    } else if (content instanceof Multipart) {
        Multipart multipart = (Multipart) content;
        String subType = null;
        String contentType = multipart.getContentType();
        if (contentType != null) {
            ContentType ct = new ContentType(contentType);
            subType = ct.getSubType();
            if (subType != null) {
                subType = subType.trim().toLowerCase();
            }
        }
        if ("alternative".equals(subType)) {
            handleAlternativePart(multipart, buffer, rdf);
        } else if ("signed".equals(subType)) {
            handleProtectedPart(multipart, 0, buffer, rdf);
        } else if ("encrypted".equals(subType)) {
            handleProtectedPart(multipart, 1, buffer, rdf);
        } else {
            // handles multipart/mixed, /digest, /related, /parallel, /report and unknown subtypes
            handleMixedPart(multipart, buffer, rdf);
        }
    }
}
Also used : BodyPart(javax.mail.BodyPart) Multipart(javax.mail.Multipart) ContentType(javax.mail.internet.ContentType) MessagingException(javax.mail.MessagingException) Model(org.ontoware.rdf2go.model.Model) DataHandler(javax.activation.DataHandler) URI(org.ontoware.rdf2go.model.node.URI)

Example 60 with DataHandler

use of javax.activation.DataHandler in project webservices-axiom by apache.

the class DataHandlerUtils method getDataHandlerFromText.

public static Object getDataHandlerFromText(String value, String mimeType) {
    ByteArrayDataSource dataSource;
    byte[] data = Base64Utils.decode(value);
    if (mimeType != null) {
        dataSource = new ByteArrayDataSource(data, mimeType);
    } else {
        // Assumes type as application/octet-stream
        dataSource = new ByteArrayDataSource(data);
    }
    return new DataHandler(dataSource);
}
Also used : DataHandler(javax.activation.DataHandler) ByteArrayDataSource(org.apache.axiom.attachments.ByteArrayDataSource)

Aggregations

DataHandler (javax.activation.DataHandler)180 Exchange (org.apache.camel.Exchange)39 MimeBodyPart (javax.mail.internet.MimeBodyPart)38 FileDataSource (javax.activation.FileDataSource)33 Test (org.junit.Test)33 DataSource (javax.activation.DataSource)32 ByteArrayDataSource (javax.mail.util.ByteArrayDataSource)29 IOException (java.io.IOException)27 ByteArrayOutputStream (java.io.ByteArrayOutputStream)25 InputStream (java.io.InputStream)25 MessagingException (javax.mail.MessagingException)25 MimeMultipart (javax.mail.internet.MimeMultipart)25 MimeMessage (javax.mail.internet.MimeMessage)23 ByteArrayInputStream (java.io.ByteArrayInputStream)22 Message (org.apache.camel.Message)21 OMElement (org.apache.axiom.om.OMElement)17 Processor (org.apache.camel.Processor)15 MockEndpoint (org.apache.camel.component.mock.MockEndpoint)14 File (java.io.File)13 PipedInputStream (java.io.PipedInputStream)13