Search in sources :

Example 56 with DataSource

use of javax.activation.DataSource in project mailim by zengsn.

the class EmailSender method addAttach.

/**
 * 在邮件内容中增加附件(邮件中添加需要在邮件中显示的图片时使用)
 * @param attach File 附件
 * @param header String Content-ID
 */
private static void addAttach(MimeMultipart multipart, File attach, String header) {
    try {
        BodyPart bodyPart = new MimeBodyPart();
        DataSource dataSource = new FileDataSource(attach);
        bodyPart.setDataHandler(new DataHandler(dataSource));
        bodyPart.setFileName(attach.getName());
        if (header != null) {
            bodyPart.setHeader("Content-ID", "<" + header + ">");
        }
        multipart.addBodyPart(bodyPart);
    } catch (MessagingException e) {
        e.printStackTrace();
    }
}
Also used : MimeBodyPart(javax.mail.internet.MimeBodyPart) BodyPart(javax.mail.BodyPart) MessagingException(javax.mail.MessagingException) FileDataSource(javax.activation.FileDataSource) DataHandler(javax.activation.DataHandler) MimeBodyPart(javax.mail.internet.MimeBodyPart) FileDataSource(javax.activation.FileDataSource) DataSource(javax.activation.DataSource)

Example 57 with DataSource

use of javax.activation.DataSource in project commons-utils-core by jiayongming.

the class EmailUtil method doSendHtmlEmail.

/**
 * 发送邮件
 *
 * @param subject     邮件主题
 * @param sendHtml    邮件内容
 * @param receiveUser 收件人地址
 * @param attachment  附件
 */
public void doSendHtmlEmail(String subject, String sendHtml, String receiveUser, File attachment) {
    try {
        // 发件人
        InternetAddress from = new InternetAddress(sender_username);
        message.setFrom(from);
        // 收件人
        InternetAddress to = new InternetAddress(receiveUser);
        message.setRecipient(Message.RecipientType.TO, to);
        // 邮件主题
        message.setSubject(subject);
        // 向multipart对象中添加邮件的各个部分内容,包括文本内容和附件
        Multipart multipart = new MimeMultipart();
        // 添加邮件正文
        BodyPart contentPart = new MimeBodyPart();
        contentPart.setContent(sendHtml, "text/html;charset=UTF-8");
        multipart.addBodyPart(contentPart);
        // 添加附件的内容
        if (attachment != null) {
            BodyPart attachmentBodyPart = new MimeBodyPart();
            DataSource source = new FileDataSource(attachment);
            attachmentBodyPart.setDataHandler(new DataHandler(source));
            // 网上流传的解决文件名乱码的方法,其实用MimeUtility.encodeWord就可以很方便的搞定
            // 这里很重要,通过下面的Base64编码的转换可以保证你的中文附件标题名在发送时不会变成乱码
            // sun.misc.BASE64Encoder enc = new sun.misc.BASE64Encoder();
            // messageBodyPart.setFileName("=?GBK?B?" + enc.encode(attachment.getName().getBytes()) + "?=");
            // MimeUtility.encodeWord可以避免文件名乱码
            attachmentBodyPart.setFileName(MimeUtility.encodeWord(attachment.getName()));
            multipart.addBodyPart(attachmentBodyPart);
        }
        // 将multipart对象放到message中
        message.setContent(multipart);
        // 保存邮件
        message.saveChanges();
        transport = session.getTransport("smtp");
        // smtp验证,就是你用来发邮件的邮箱用户名密码
        transport.connect(mailHost, port, sender_username, sender_password);
        // 发送
        transport.sendMessage(message, message.getAllRecipients());
        log.info("send success!");
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        if (transport != null) {
            try {
                transport.close();
            } catch (MessagingException e) {
                e.printStackTrace();
            }
        }
    }
}
Also used : FileDataSource(javax.activation.FileDataSource) DataHandler(javax.activation.DataHandler) FileDataSource(javax.activation.FileDataSource) DataSource(javax.activation.DataSource)

Example 58 with DataSource

use of javax.activation.DataSource in project light-4j by networknt.

the class EmailSender method sendMailWithAttachment.

/**
 * Send email with a string content and attachment
 *
 * @param to destination eamil address
 * @param subject email subject
 * @param content email content
 * @param filename attachment filename
 * @throws MessagingException messaging exception
 */
public void sendMailWithAttachment(String to, String subject, String content, String filename) throws MessagingException {
    Properties props = new Properties();
    props.put("mail.smtp.user", emailConfg.getUser());
    props.put("mail.smtp.host", emailConfg.getHost());
    props.put("mail.smtp.port", emailConfg.getPort());
    props.put("mail.smtp.starttls.enable", "true");
    props.put("mail.smtp.debug", emailConfg.getDebug());
    props.put("mail.smtp.auth", emailConfg.getAuth());
    SMTPAuthenticator auth = new SMTPAuthenticator(emailConfg.getUser(), (String) secret.get(SecretConstants.EMAIL_PASSWORD));
    Session session = Session.getInstance(props, auth);
    MimeMessage message = new MimeMessage(session);
    message.setFrom(new InternetAddress(emailConfg.getUser()));
    message.addRecipient(Message.RecipientType.TO, new InternetAddress(to));
    message.setSubject(subject);
    // Create the message part
    BodyPart messageBodyPart = new MimeBodyPart();
    // Now set the actual message
    messageBodyPart.setText(content);
    // Create a multipar message
    Multipart multipart = new MimeMultipart();
    // Set text message part
    multipart.addBodyPart(messageBodyPart);
    // Part two is attachment
    messageBodyPart = new MimeBodyPart();
    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);
}
Also used : MimeBodyPart(javax.mail.internet.MimeBodyPart) InternetAddress(javax.mail.internet.InternetAddress) MimeMultipart(javax.mail.internet.MimeMultipart) MimeMessage(javax.mail.internet.MimeMessage) MimeMultipart(javax.mail.internet.MimeMultipart) FileDataSource(javax.activation.FileDataSource) DataHandler(javax.activation.DataHandler) Properties(java.util.Properties) MimeBodyPart(javax.mail.internet.MimeBodyPart) FileDataSource(javax.activation.FileDataSource) DataSource(javax.activation.DataSource)

Example 59 with DataSource

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

the class TestODataUpdateExecution method helpExecute.

private String helpExecute(String query, final String resultXML, String expectedURL, int[] responseCode, TransformationMetadata metadata, int times) throws Exception {
    ODataExecutionFactory translator = new ODataExecutionFactory();
    translator.start();
    TranslationUtility utility = new TranslationUtility(metadata);
    Command cmd = utility.parseCommand(query);
    ExecutionContext context = Mockito.mock(ExecutionContext.class);
    WSConnection connection = Mockito.mock(WSConnection.class);
    Map<String, Object> headers = new HashMap<String, Object>();
    headers.put(MessageContext.HTTP_REQUEST_HEADERS, new HashMap<String, List<String>>());
    headers.put(WSConnection.STATUS_CODE, new Integer(responseCode[0]));
    Dispatch<DataSource> dispatch = Mockito.mock(Dispatch.class);
    Mockito.stub(dispatch.getRequestContext()).toReturn(headers);
    Mockito.stub(dispatch.getResponseContext()).toReturn(headers);
    Mockito.stub(connection.createDispatch(Mockito.eq(HTTPBinding.HTTP_BINDING), Mockito.anyString(), Mockito.eq(DataSource.class), Mockito.eq(Mode.MESSAGE))).toReturn(dispatch);
    DataSource ds = new DataSource() {

        @Override
        public OutputStream getOutputStream() throws IOException {
            return new ByteArrayOutputStream();
        }

        @Override
        public String getName() {
            return "result";
        }

        @Override
        public InputStream getInputStream() throws IOException {
            ByteArrayInputStream in = new ByteArrayInputStream(resultXML.getBytes());
            return in;
        }

        @Override
        public String getContentType() {
            return "application/xml";
        }
    };
    ArgumentCaptor<DataSource> payload = ArgumentCaptor.forClass(DataSource.class);
    Mockito.stub(dispatch.invoke(payload.capture())).toReturn(ds);
    UpdateExecution execution = translator.createUpdateExecution(cmd, context, utility.createRuntimeMetadata(), connection);
    execution.execute();
    ArgumentCaptor<String> endpoint = ArgumentCaptor.forClass(String.class);
    ArgumentCaptor<String> binding = ArgumentCaptor.forClass(String.class);
    Mockito.verify(connection, Mockito.times(times)).createDispatch(binding.capture(), endpoint.capture(), Mockito.eq(DataSource.class), Mockito.eq(Mode.MESSAGE));
    Mockito.verify(dispatch, Mockito.times(times)).invoke(payload.capture());
    assertEquals(expectedURL, URLDecoder.decode(endpoint.getValue(), "utf-8"));
    if (payload.getAllValues() != null) {
        List<DataSource> listDS = payload.getAllValues();
        InputStream in = null;
        if (times > 1) {
            in = listDS.get(1).getInputStream();
        } else {
            in = listDS.get(0).getInputStream();
        }
        return new String(ObjectConverterUtil.convertToByteArray(in));
    }
    return "";
}
Also used : WSConnection(org.teiid.translator.WSConnection) HashMap(java.util.HashMap) ByteArrayInputStream(java.io.ByteArrayInputStream) InputStream(java.io.InputStream) TranslationUtility(org.teiid.cdk.api.TranslationUtility) UpdateExecution(org.teiid.translator.UpdateExecution) ByteArrayOutputStream(java.io.ByteArrayOutputStream) DataSource(javax.activation.DataSource) ExecutionContext(org.teiid.translator.ExecutionContext) Command(org.teiid.language.Command) ByteArrayInputStream(java.io.ByteArrayInputStream) List(java.util.List)

Example 60 with DataSource

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

the class ConnectorWorkItem method convertToRuntimeType.

static Object convertToRuntimeType(BufferManager bm, Object value, Class<?> desiredType, CommandContext context) throws TransformationException {
    if (desiredType != DataTypeManager.DefaultDataClasses.XML || !(value instanceof Source)) {
        if (value instanceof DataSource) {
            final DataSource ds = (DataSource) value;
            try {
                // Teiid uses the datasource interface in a degenerate way that
                // reuses the stream, so we test for that here
                InputStream initial = ds.getInputStream();
                InputStream other = null;
                try {
                    other = ds.getInputStream();
                } catch (IOException e) {
                // likely streaming
                }
                if (other != null && initial != other) {
                    initial.close();
                    other.close();
                    if (value instanceof InputStreamFactory) {
                        return asLob((InputStreamFactory) value, desiredType);
                    }
                    return asLob(new InputStreamFactory() {

                        @Override
                        public InputStream getInputStream() throws IOException {
                            return ds.getInputStream();
                        }
                    }, desiredType);
                }
                // $NON-NLS-1$
                FileStore fs = bm.createFileStore("bytes");
                // TODO: guess at the encoding from the content type
                FileStoreInputStreamFactory fsisf = new FileStoreInputStreamFactory(fs, Streamable.ENCODING);
                SaveOnReadInputStream is = new SaveOnReadInputStream(initial, fsisf);
                if (context != null) {
                    context.addCreatedLob(fsisf);
                }
                return asLob(is.getInputStreamFactory(), desiredType);
            } catch (IOException e) {
                throw new TransformationException(QueryPlugin.Event.TEIID30500, e, e.getMessage());
            }
        }
        if (value instanceof InputStreamFactory) {
            return asLob((InputStreamFactory) value, desiredType);
        }
        if (value instanceof GeometryInputSource) {
            GeometryInputSource gis = (GeometryInputSource) value;
            try {
                InputStream is = gis.getEwkb();
                if (is != null) {
                    return GeometryUtils.geometryFromEwkb(is, gis.getSrid());
                }
            } catch (Exception e) {
                throw new TransformationException(e);
            }
            try {
                Reader r = gis.getGml();
                if (r != null) {
                    return GeometryUtils.geometryFromGml(r, gis.getSrid());
                }
            } catch (Exception e) {
                throw new TransformationException(e);
            }
        }
    }
    if (value instanceof Source) {
        if (!(value instanceof InputStreamFactory)) {
            if (value instanceof StreamSource) {
                StreamSource ss = (StreamSource) value;
                InputStream is = ss.getInputStream();
                Reader r = ss.getReader();
                if (is == null && r != null) {
                    is = new ReaderInputStream(r, Streamable.CHARSET);
                }
                // $NON-NLS-1$
                final FileStore fs = bm.createFileStore("xml");
                final FileStoreInputStreamFactory fsisf = new FileStoreInputStreamFactory(fs, Streamable.ENCODING);
                value = new SaveOnReadInputStream(is, fsisf).getInputStreamFactory();
                if (context != null) {
                    context.addCreatedLob(fsisf);
                }
            } else if (value instanceof StAXSource) {
                // TODO: do this lazily.  if the first access to get the STaXSource, then
                // it's more efficient to let the processing happen against STaX
                StAXSource ss = (StAXSource) value;
                try {
                    // $NON-NLS-1$
                    final FileStore fs = bm.createFileStore("xml");
                    final FileStoreInputStreamFactory fsisf = new FileStoreInputStreamFactory(fs, Streamable.ENCODING);
                    value = new SaveOnReadInputStream(new XMLInputStream(ss, XMLSystemFunctions.getOutputFactory(true)), fsisf).getInputStreamFactory();
                    if (context != null) {
                        context.addCreatedLob(fsisf);
                    }
                } catch (XMLStreamException e) {
                    throw new TransformationException(e);
                }
            } else {
                // maybe dom or some other source we want to get out of memory
                StandardXMLTranslator sxt = new StandardXMLTranslator((Source) value);
                SQLXMLImpl sqlxml;
                try {
                    sqlxml = XMLSystemFunctions.saveToBufferManager(bm, sxt, context);
                } catch (TeiidComponentException e) {
                    throw new TransformationException(e);
                } catch (TeiidProcessingException e) {
                    throw new TransformationException(e);
                }
                return new XMLType(sqlxml);
            }
        }
        return new XMLType(new SQLXMLImpl((InputStreamFactory) value));
    }
    return DataTypeManager.convertToRuntimeType(value, desiredType != DataTypeManager.DefaultDataClasses.OBJECT);
}
Also used : SaveOnReadInputStream(org.teiid.dqp.internal.process.SaveOnReadInputStream) XMLInputStream(org.teiid.util.XMLInputStream) FileStoreInputStreamFactory(org.teiid.common.buffer.FileStoreInputStreamFactory) XMLInputStream(org.teiid.util.XMLInputStream) SaveOnReadInputStream(org.teiid.dqp.internal.process.SaveOnReadInputStream) ReaderInputStream(org.teiid.core.util.ReaderInputStream) InputStream(java.io.InputStream) StreamSource(javax.xml.transform.stream.StreamSource) GeometryInputSource(org.teiid.GeometryInputSource) Reader(java.io.Reader) IOException(java.io.IOException) StAXSource(javax.xml.transform.stax.StAXSource) FileStoreInputStreamFactory(org.teiid.common.buffer.FileStoreInputStreamFactory) GeometryInputSource(org.teiid.GeometryInputSource) StreamSource(javax.xml.transform.stream.StreamSource) Source(javax.xml.transform.Source) StAXSource(javax.xml.transform.stax.StAXSource) DataSource(javax.activation.DataSource) CollectionTupleSource(org.teiid.query.processor.CollectionTupleSource) ResourceException(javax.resource.ResourceException) TeiidComponentException(org.teiid.core.TeiidComponentException) XMLStreamException(javax.xml.stream.XMLStreamException) TeiidProcessingException(org.teiid.core.TeiidProcessingException) TeiidException(org.teiid.core.TeiidException) IOException(java.io.IOException) DataSource(javax.activation.DataSource) TeiidProcessingException(org.teiid.core.TeiidProcessingException) FileStore(org.teiid.common.buffer.FileStore) ReaderInputStream(org.teiid.core.util.ReaderInputStream) XMLStreamException(javax.xml.stream.XMLStreamException) TeiidComponentException(org.teiid.core.TeiidComponentException)

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