Java Code Examples for javax.mail.util.ByteArrayDataSource

The following are top voted examples for showing how to use javax.mail.util.ByteArrayDataSource. These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to generate more good examples.
Example 1
Project: simple-java-mail   File: MailTestDemoApp.java   Source Code and License 8 votes vote down vote up
public static void main(final String[] args)
		throws Exception {
	final EmailPopulatingBuilder emailPopulatingBuilderNormal = EmailBuilder.startingBlank();
	emailPopulatingBuilderNormal.from("lollypop", "[email protected]");
	// don't forget to add your own address here ->
	emailPopulatingBuilderNormal.to("C.Cane", YOUR_GMAIL_ADDRESS);
	emailPopulatingBuilderNormal.withPlainText("We should meet up!");
	emailPopulatingBuilderNormal.withHTMLText("<b>We should meet up!</b><img src='cid:thumbsup'>");
	emailPopulatingBuilderNormal.withSubject("hey");
	
	// add two text files in different ways and a black thumbs up embedded image ->
	emailPopulatingBuilderNormal.withAttachment("dresscode.txt", new ByteArrayDataSource("Black Tie Optional", "text/plain"));
	emailPopulatingBuilderNormal.withAttachment("location.txt", "On the moon!".getBytes(Charset.defaultCharset()), "text/plain");
	String base64String = "iVBORw0KGgoAAAANSUhEUgAAACAAAAAgCAYAAABzenr0AAABeElEQVRYw2NgoAAYGxu3GxkZ7TY1NZVloDcAWq4MxH+B+D8Qv3FwcOCgtwM6oJaDMTAUXOhmuYqKCjvQ0pdoDrCnmwNMTEwakC0H4u8GBgYC9Ap6DSD+iewAoIPm0ctyLqBlp9F8/x+YE4zpYT8T0LL16JYD8U26+B7oyz4sloPwenpYno3DchCeROsUbwa05A8eB3wB4kqgIxOAuArIng7EW4H4EhC/B+JXQLwDaI4ryZaDSjeg5mt4LCcFXyIn1fdSyXJQVt1OtMWGhoai0OD8T0W8GohZifE1PxD/o7LlsPLiFNAKRrwOABWptLAcqc6QGDAHQEOAYaAc8BNotsJAOgAUAosG1AFA/AtUoY3YEFhKMAvS2AE7iC1+WaG1H6gY3gzE36hUFJ8mqzbU1dUVBBqQBzTgIDQRkWo5qCZdpaenJ0Zx1aytrc0DDB0foIG1oAYKqC0IZK8D4n1AfA6IzwPxXpCFoGoZVEUDaRGGUTAKRgEeAAA2eGJC+ETCiAAAAABJRU5ErkJggg==";
	emailPopulatingBuilderNormal.withEmbeddedImage("thumbsup", parseBase64Binary(base64String), "image/png");
	
	// let's try producing and then consuming a MimeMessage ->
	Email emailNormal = emailPopulatingBuilderNormal.buildEmail();
	final MimeMessage mimeMessage = EmailConverter.emailToMimeMessage(emailNormal);
	final Email emailFromMimeMessage = EmailConverter.mimeMessageToEmail(mimeMessage);
	
	// note: the following statements will produce 6 new emails!
	sendMail(emailNormal);
	sendMail(emailFromMimeMessage); // should produce the exact same result as emailPopulatingBuilderNormal!
}
 
Example 2
Project: Camel   File: MailBinding.java   Source Code and License 7 votes vote down vote up
protected String populateContentOnBodyPart(BodyPart part, MailConfiguration configuration, Exchange exchange)
    throws MessagingException, IOException {

    String contentType = determineContentType(configuration, exchange);

    if (contentType != null) {
        LOG.trace("Using Content-Type {} for BodyPart: {}", contentType, part);

        // always store content in a byte array data store to avoid various content type and charset issues
        String data = exchange.getContext().getTypeConverter().tryConvertTo(String.class, exchange.getIn().getBody());
        // use empty data if the body was null for some reason (otherwise there is a NPE)
        data = data != null ? data : "";

        DataSource ds = new ByteArrayDataSource(data, contentType);
        part.setDataHandler(new DataHandler(ds));

        // set the content type header afterwards
        part.setHeader("Content-Type", contentType);
    }

    return contentType;
}
 
Example 3
Project: jersey-smime   File: SignedReader.java   Source Code and License 7 votes vote down vote up
@Override
public SignedInput readFrom(Class<SignedInput> type, Type genericType, Annotation[] annotations, MediaType mediaType, MultivaluedMap<String, String> headers, InputStream entityStream) throws IOException, WebApplicationException {
    Class<?> baseType = null;
    Type baseGenericType = null;

    if (genericType instanceof ParameterizedType) {
        ParameterizedType param = (ParameterizedType) genericType;
        baseGenericType = param.getActualTypeArguments()[0];
        baseType = Types.getRawType(baseGenericType);
    }
    try {
        ByteArrayDataSource ds = new ByteArrayDataSource(entityStream, mediaType.toString());
        MimeMultipart mm = new MimeMultipart(ds);
        SignedInputImpl input = new SignedInputImpl();
        input.setType(baseType);
        input.setGenericType(baseGenericType);
        input.setAnnotations(annotations);
        input.setBody(mm);
        input.setProviders(providers);
        return input;
    } catch (MessagingException e) {
        throw new RuntimeException(e);
    }

}
 
Example 4
Project: carrier   File: SMTPMessageFactory.java   Source Code and License 6 votes vote down vote up
/**
 * Creates a list of {@link MimeMessage} attachments using the given incoming e-mail.
 *
 * @param email The parsed e-mail.
 * @return A list containing the attachments, if any.
 * @throws Exception If there is an error while constructing the list of attachments.
 */
private List<BodyPart> createMimeMessageAttachments(Email email) throws Exception {

    List<BodyPart> attachments = new LinkedList<>();

    for (Attachment attachment : email.getAttachments()) {
        BodyPart attachmentBodyPart = new MimeBodyPart();
        attachmentBodyPart.setFileName(attachment.getAttachmentName());

        byte[] data = ByteStreams.toByteArray(attachment.getIs());
        DataSource source = new ByteArrayDataSource(data, "application/octet-stream");
        attachmentBodyPart.setDataHandler(new DataHandler(source));

        attachments.add(attachmentBodyPart);
    }

    return attachments;
}
 
Example 5
Project: dungeonstory-java   File: MailTestApp.java   Source Code and License 6 votes vote down vote up
public static void main(final String[] args) throws Exception {
    clearConfigProperties();

    final Email emailNormal = new Email();
    emailNormal.setFromAddress("lollypop", "[email protected]");
    // don't forget to add your own address here ->
    emailNormal.addRecipient("C.Cane", YOUR_GMAIL_ADDRESS, RecipientType.TO);
    emailNormal.setText("We should meet up!");
    emailNormal.setTextHTML("<b>We should meet up!</b><img src='cid:thumbsup'>");
    emailNormal.setSubject("hey");

    // add two text files in different ways and a black thumbs up embedded image ->
    emailNormal.addAttachment("dresscode.txt", new ByteArrayDataSource("Black Tie Optional", "text/plain"));
    emailNormal.addAttachment("location.txt", "On the moon!".getBytes(Charset.defaultCharset()), "text/plain");
    String base64String = "iVBORw0KGgoAAAANSUhEUgAAACAAAAAgCAYAAABzenr0AAABeElEQVRYw2NgoAAYGxu3GxkZ7TY1NZVloDcAWq4MxH+B+D8Qv3FwcOCgtwM6oJaDMTAUXOhmuYqKCjvQ0pdoDrCnmwNMTEwakC0H4u8GBgYC9Ap6DSD+iewAoIPm0ctyLqBlp9F8/x+YE4zpYT8T0LL16JYD8U26+B7oyz4sloPwenpYno3DchCeROsUbwa05A8eB3wB4kqgIxOAuArIng7EW4H4EhC/B+JXQLwDaI4ryZaDSjeg5mt4LCcFXyIn1fdSyXJQVt1OtMWGhoai0OD8T0W8GohZifE1PxD/o7LlsPLiFNAKRrwOABWptLAcqc6QGDAHQEOAYaAc8BNotsJAOgAUAosG1AFA/AtUoY3YEFhKMAvS2AE7iC1+WaG1H6gY3gzE36hUFJ8mqzbU1dUVBBqQBzTgIDQRkWo5qCZdpaenJ0Zx1aytrc0DDB0foIG1oAYKqC0IZK8D4n1AfA6IzwPxXpCFoGoZVEUDaRGGUTAKRgEeAAA2eGJC+ETCiAAAAABJRU5ErkJggg==";
    emailNormal.addEmbeddedImage("thumbsup", parseBase64Binary(base64String), "image/png");

    // let's try producing and then consuming a MimeMessage ->
    final MimeMessage mimeMessage = Mailer.produceMimeMessage(emailNormal);
    final Email emailFromMimeMessage = new Email(mimeMessage);

    // note: the following statements will produce 6 new emails!
    sendMail(emailNormal);
    sendMail(emailFromMimeMessage); // should produce the exact same result as emailNormal!
}
 
Example 6
Project: IdentityRegistry   File: EmailUtil.java   Source Code and License 6 votes vote down vote up
public void sendBugReport(BugReport report) throws MailException, MessagingException {
    MimeMessage message = this.mailSender.createMimeMessage();
    MimeMessageHelper helper = new MimeMessageHelper(message, true);
    helper.setTo(bugReportEmail);
    helper.setFrom(from);
    helper.setSubject(report.getSubject());
    helper.setText(report.getDescription());
    if (report.getAttachments() != null) {
        for (BugReportAttachment attachment : report.getAttachments()) {
            // Decode base64 encoded data
            byte[] data =  Base64.getDecoder().decode(attachment.getData());
            ByteArrayDataSource dataSource = new ByteArrayDataSource(data, attachment.getMimetype());
            helper.addAttachment(attachment.getName(), dataSource);
        }
    }
    this.mailSender.send(message);
}
 
Example 7
Project: Camel   File: CxfMtomConsumerPayloadModeTest.java   Source Code and License 6 votes vote down vote up
@Test
public void testConsumer() throws Exception {
    if (MtomTestHelper.isAwtHeadless(logger, null)) {
        return;
    }

    context.createProducerTemplate().send("cxf:bean:consumerEndpoint", new Processor() {

        public void process(Exchange exchange) throws Exception {
            exchange.setPattern(ExchangePattern.InOut);
            assertEquals("Get a wrong Content-Type header", "application/xop+xml", exchange.getIn().getHeader("Content-Type"));
            List<Source> elements = new ArrayList<Source>();
            elements.add(new DOMSource(StaxUtils.read(new StringReader(getRequestMessage())).getDocumentElement()));
            CxfPayload<SoapHeader> body = new CxfPayload<SoapHeader>(new ArrayList<SoapHeader>(),
                elements, null);
            exchange.getIn().setBody(body);
            exchange.getIn().addAttachment(MtomTestHelper.REQ_PHOTO_CID, 
                new DataHandler(new ByteArrayDataSource(MtomTestHelper.REQ_PHOTO_DATA, "application/octet-stream")));

            exchange.getIn().addAttachment(MtomTestHelper.REQ_IMAGE_CID, 
                new DataHandler(new ByteArrayDataSource(MtomTestHelper.requestJpeg, "image/jpeg")));
        }
    });
}
 
Example 8
Project: Camel   File: CxfMtomDisabledConsumerPayloadModeTest.java   Source Code and License 6 votes vote down vote up
@SuppressWarnings("unchecked")
public void process(Exchange exchange) throws Exception {
    CxfPayload<SoapHeader> in = exchange.getIn().getBody(CxfPayload.class);
    
    // verify request
    Assert.assertEquals(1, in.getBody().size());
    
    DataHandler dr = exchange.getIn().getAttachment(MtomTestHelper.REQ_PHOTO_CID);
    Assert.assertEquals("application/octet-stream", dr.getContentType());
    MtomTestHelper.assertEquals(MtomTestHelper.REQ_PHOTO_DATA, IOUtils.readBytesFromStream(dr.getInputStream()));
       
    dr = exchange.getIn().getAttachment(MtomTestHelper.REQ_IMAGE_CID);
    Assert.assertEquals("image/jpeg", dr.getContentType());
    MtomTestHelper.assertEquals(MtomTestHelper.requestJpeg, IOUtils.readBytesFromStream(dr.getInputStream()));

    // create response
    List<Source> elements = new ArrayList<Source>();
    elements.add(new DOMSource(StaxUtils.read(new StringReader(MtomTestHelper.MTOM_DISABLED_RESP_MESSAGE)).getDocumentElement()));
    CxfPayload<SoapHeader> body = new CxfPayload<SoapHeader>(new ArrayList<SoapHeader>(),
        elements, null);
    exchange.getOut().setBody(body);
    exchange.getOut().addAttachment(MtomTestHelper.RESP_PHOTO_CID, 
        new DataHandler(new ByteArrayDataSource(MtomTestHelper.RESP_PHOTO_DATA, "application/octet-stream")));

    exchange.getOut().addAttachment(MtomTestHelper.RESP_IMAGE_CID, 
        new DataHandler(new ByteArrayDataSource(MtomTestHelper.responseJpeg, "image/jpeg")));

}
 
Example 9
Project: Camel   File: MailBinding.java   Source Code and License 6 votes vote down vote up
protected String populateContentOnMimeMessage(MimeMessage part, MailConfiguration configuration, Exchange exchange)
    throws MessagingException, IOException {

    String contentType = determineContentType(configuration, exchange);

    LOG.trace("Using Content-Type {} for MimeMessage: {}", contentType, part);

    String body = exchange.getIn().getBody(String.class);
    if (body == null) {
        body = "";
    }

    // always store content in a byte array data store to avoid various content type and charset issues
    DataSource ds = new ByteArrayDataSource(body, contentType);
    part.setDataHandler(new DataHandler(ds));

    // set the content type header afterwards
    part.setHeader("Content-Type", contentType);

    return contentType;
}
 
Example 10
Project: Camel   File: MimeMultipartDataFormatTest.java   Source Code and License 6 votes vote down vote up
@Test
public void roundtripWithBinaryAttachments() throws IOException {
    String attContentType = "application/binary";
    byte[] attText = {0, 1, 2, 3, 4, 5, 6, 7};
    String attFileName = "Attachment File Name";
    in.setBody("Body text");
    DataSource ds = new ByteArrayDataSource(attText, attContentType);
    in.addAttachment(attFileName, new DataHandler(ds));
    Exchange result = template.send("direct:roundtrip", exchange);
    Message out = result.getOut();
    assertEquals("Body text", out.getBody(String.class));
    assertTrue(out.hasAttachments());
    assertEquals(1, out.getAttachmentNames().size());
    assertThat(out.getAttachmentNames(), hasItem(attFileName));
    DataHandler dh = out.getAttachment(attFileName);
    assertNotNull(dh);
    assertEquals(attContentType, dh.getContentType());
    InputStream is = dh.getInputStream();
    ByteArrayOutputStream os = new ByteArrayOutputStream();
    IOHelper.copyAndCloseInput(is, os);
    assertArrayEquals(attText, os.toByteArray());
}
 
Example 11
Project: Camel   File: MimeMultipartDataFormatTest.java   Source Code and License 6 votes vote down vote up
@Test
public void roundtripWithBinaryAttachmentsAndBinaryContent() throws IOException {
    String attContentType = "application/binary";
    byte[] attText = {0, 1, 2, 3, 4, 5, 6, 7};
    String attFileName = "Attachment File Name";
    in.setBody("Body text");
    DataSource ds = new ByteArrayDataSource(attText, attContentType);
    in.addAttachment(attFileName, new DataHandler(ds));
    Exchange result = template.send("direct:roundtripbinarycontent", exchange);
    Message out = result.getOut();
    assertEquals("Body text", out.getBody(String.class));
    assertTrue(out.hasAttachments());
    assertEquals(1, out.getAttachmentNames().size());
    assertThat(out.getAttachmentNames(), hasItem(attFileName));
    DataHandler dh = out.getAttachment(attFileName);
    assertNotNull(dh);
    assertEquals(attContentType, dh.getContentType());
    InputStream is = dh.getInputStream();
    ByteArrayOutputStream os = new ByteArrayOutputStream();
    IOHelper.copyAndCloseInput(is, os);
    assertArrayEquals(attText, os.toByteArray());
}
 
Example 12
Project: openxds   File: XdsTest.java   Source Code and License 6 votes vote down vote up
protected OMElement addOneDocument(OMElement request, String document, String documentId) throws IOException {
	OMFactory fac = OMAbstractFactory.getOMFactory();
	OMNamespace ns = fac.createOMNamespace("urn:ihe:iti:xds-b:2007" , null);
	OMElement docElem = fac.createOMElement("Document", ns);
	docElem.addAttribute("id", documentId, null);

       // A string, turn it into an StreamSource
    DataSource ds = new ByteArrayDataSource(document, "text/xml"); 
	DataHandler handler = new DataHandler(ds);
	 
       OMText binaryData = fac.createOMText(handler, true);
       docElem.addChild(binaryData);

       Iterator iter = request.getChildrenWithLocalName("SubmitObjectsRequest");
       OMElement submitObjectsRequest = null;
       for (;iter.hasNext();) {
       	submitObjectsRequest = (OMElement)iter.next();
       	if (submitObjectsRequest != null)
       		break;
       }
       submitObjectsRequest.insertSiblingAfter(docElem);
       return request;
}
 
Example 13
Project: simple-java-mail   File: EmailPopulatingBuilderUsingDefaultsFromPropertyFileTest.java   Source Code and License 6 votes vote down vote up
@Test
public void testBuilderSimpleBuildWithStandardEmail()
		throws IOException {
	ByteArrayDataSource namedAttachment = new ByteArrayDataSource("Black Tie Optional", "text/plain");
	namedAttachment.setName("dresscode.txt"); // normally not needed, but otherwise the equals will fail
	String base64String = "iVBORw0KGgoAAAANSUhEUgAAACAAAAAgCAYAAABzenr0AAABeElEQVRYw2NgoAAYGxu3GxkZ7TY1NZVloDcAWq4MxH+B+D8Qv3FwcOCgtwM6oJaDMTAUXOhmuYqKCjvQ0pdoDrCnmwNMTEwakC0H4u8GBgYC9Ap6DSD+iewAoIPm0ctyLqBlp9F8/x+YE4zpYT8T0LL16JYD8U26+B7oyz4sloPwenpYno3DchCeROsUbwa05A8eB3wB4kqgIxOAuArIng7EW4H4EhC/B+JXQLwDaI4ryZaDSjeg5mt4LCcFXyIn1fdSyXJQVt1OtMWGhoai0OD8T0W8GohZifE1PxD/o7LlsPLiFNAKRrwOABWptLAcqc6QGDAHQEOAYaAc8BNotsJAOgAUAosG1AFA/AtUoY3YEFhKMAvS2AE7iC1+WaG1H6gY3gzE36hUFJ8mqzbU1dUVBBqQBzTgIDQRkWo5qCZdpaenJ0Zx1aytrc0DDB0foIG1oAYKqC0IZK8D4n1AfA6IzwPxXpCFoGoZVEUDaRGGUTAKRgEeAAA2eGJC+ETCiAAAAABJRU5ErkJggg==";
	
	final Email email = EmailBuilder.startingBlank()
			.from("lollypop", "[email protected]")
			.to("C.Cane", "[email protected]")
			.withPlainText("We should meet up!")
			.withHTMLText("<b>We should meet up!</b><img src='cid:thumbsup'>")
			.withSubject("hey")
			.withAttachment("dresscode.txt", namedAttachment)
			.withAttachment("location.txt", "On the moon!".getBytes(Charset.defaultCharset()), "text/plain")
			.withEmbeddedImage("thumbsup", parseBase64Binary(base64String), "image/png")
			.buildEmail();
	
	assertThat(EmailHelper.createDummyEmailBuilder(true, true, false).buildEmail()).isEqualTo(email);
}
 
Example 14
Project: simple-java-mail   File: EmailPopulatingBuilderUsingDefaultsFromPropertyFileTest.java   Source Code and License 6 votes vote down vote up
@Test
public void testBuilderSimpleBuildWithStandardEmail_PlusOptionals()
		throws IOException {
	ByteArrayDataSource namedAttachment = new ByteArrayDataSource("Black Tie Optional", "text/plain");
	namedAttachment.setName("dresscode.txt"); // normally not needed, but otherwise the equals will fail
	String base64String = "iVBORw0KGgoAAAANSUhEUgAAACAAAAAgCAYAAABzenr0AAABeElEQVRYw2NgoAAYGxu3GxkZ7TY1NZVloDcAWq4MxH+B+D8Qv3FwcOCgtwM6oJaDMTAUXOhmuYqKCjvQ0pdoDrCnmwNMTEwakC0H4u8GBgYC9Ap6DSD+iewAoIPm0ctyLqBlp9F8/x+YE4zpYT8T0LL16JYD8U26+B7oyz4sloPwenpYno3DchCeROsUbwa05A8eB3wB4kqgIxOAuArIng7EW4H4EhC/B+JXQLwDaI4ryZaDSjeg5mt4LCcFXyIn1fdSyXJQVt1OtMWGhoai0OD8T0W8GohZifE1PxD/o7LlsPLiFNAKRrwOABWptLAcqc6QGDAHQEOAYaAc8BNotsJAOgAUAosG1AFA/AtUoY3YEFhKMAvS2AE7iC1+WaG1H6gY3gzE36hUFJ8mqzbU1dUVBBqQBzTgIDQRkWo5qCZdpaenJ0Zx1aytrc0DDB0foIG1oAYKqC0IZK8D4n1AfA6IzwPxXpCFoGoZVEUDaRGGUTAKRgEeAAA2eGJC+ETCiAAAAABJRU5ErkJggg==";
	
	final Email email = EmailBuilder.startingBlank()
			.from("lollypop", "[email protected]")
			.withReplyTo("lollypop-reply", "[email protected]")
			.withBounceTo("lollypop-bounce", "[email protected]")
			.to("C.Cane", "[email protected]")
			.withPlainText("We should meet up!")
			.withHTMLText("<b>We should meet up!</b><img src='cid:thumbsup'>")
			.withSubject("hey")
			.withAttachment("dresscode.txt", namedAttachment)
			.withAttachment("location.txt", "On the moon!".getBytes(Charset.defaultCharset()), "text/plain")
			.withEmbeddedImage("thumbsup", parseBase64Binary(base64String), "image/png")
			.withDispositionNotificationTo("[email protected]")
			.withReturnReceiptTo("Complex Email", "[email protected]")
			.withHeader("dummyHeader", "dummyHeaderValue")
			.buildEmail();
	
	assertThat(EmailHelper.createDummyEmailBuilder(true, false, true).buildEmail()).isEqualTo(email);
}
 
Example 15
Project: openmeetings   File: MailHandler.java   Source Code and License 6 votes vote down vote up
protected MimeMessage appendIcsBody(MimeMessage msg, MailMessage m) throws Exception {
	log.debug("setMessageBody for iCal message");
	// -- Create a new message --
	Multipart multipart = new MimeMultipart();

	Multipart multiBody = new MimeMultipart("alternative");
	BodyPart html = new MimeBodyPart();
	html.setDataHandler(new DataHandler(new ByteArrayDataSource(m.getBody(), "text/html; charset=UTF-8")));
	multiBody.addBodyPart(html);

	BodyPart iCalContent = new MimeBodyPart();
	iCalContent.addHeader("content-class", "urn:content-classes:calendarmessage");
	iCalContent.setDataHandler(new DataHandler(new ByteArrayDataSource(new ByteArrayInputStream(m.getIcs()),
			"text/calendar; charset=UTF-8; method=REQUEST")));
	multiBody.addBodyPart(iCalContent);
	BodyPart body = new MimeBodyPart();
	body.setContent(multiBody);
	multipart.addBodyPart(body);

	BodyPart iCalAttachment = new MimeBodyPart();
	iCalAttachment.setDataHandler(new DataHandler(new ByteArrayDataSource(new ByteArrayInputStream(m.getIcs()),
			"application/ics")));
	iCalAttachment.removeHeader("Content-Transfer-Encoding");
	iCalAttachment.addHeader("Content-Transfer-Encoding", "base64");
	iCalAttachment.removeHeader("Content-Type");
	iCalAttachment.addHeader("Content-Type", "application/ics");
	iCalAttachment.setFileName("invite.ics");
	multipart.addBodyPart(iCalAttachment);

	msg.setContent(multipart);
	return msg;
}
 
Example 16
Project: muleebmsadapter   File: AbstractEbMSDAO.java   Source Code and License 6 votes vote down vote up
private List<DataSource> getAttachments(long messageId) throws DAOException
{
	try
	{
		return simpleJdbcTemplate.query(
			"select name, content_type, content" + 
			" from ebms_attachment" + 
			" where ebms_message_id = ?",
			new ParameterizedRowMapper<DataSource>()
			{
				@Override
				public DataSource mapRow(ResultSet rs, int rowNum) throws SQLException
				{
					ByteArrayDataSource result = new ByteArrayDataSource(rs.getBytes("content"),rs.getString("content_type"));
					result.setName(rs.getString("name"));
					return result;
				}
			},
			messageId
		);
	}
	catch (DataAccessException e)
	{
		throw new DAOException(e);
	}
}
 
Example 17
Project: muleebmsadapter   File: EbMSMessageUtils.java   Source Code and License 6 votes vote down vote up
public static EbMSMessage ebMSMessageContentToEbMSMessage(CollaborationProtocolAgreement cpa, EbMSMessageContent content, String hostname) throws DatatypeConfigurationException
{
	MessageHeader messageHeader = createMessageHeader(cpa,content.getContext(),hostname);

	AckRequested ackRequested = createAckRequested(cpa,content.getContext());
	
	Manifest manifest = createManifest();
	for (int i = 0; i < content.getAttachments().size(); i++)
		manifest.getReference().add(createReference(i + 1));
	
	List<DataSource> attachments = new ArrayList<DataSource>();
	for (EbMSAttachment attachment : content.getAttachments())
	{
		ByteArrayDataSource ds = new ByteArrayDataSource(attachment.getContent(),attachment.getContentType());
		ds.setName(attachment.getName());
		attachments.add(ds);
	}

	return new EbMSMessage(messageHeader,ackRequested,manifest,attachments);
}
 
Example 18
Project: Tournament   File: SmtpMailService.java   Source Code and License 6 votes vote down vote up
/**
 * Add file attachments to multi part document
 *
 * @param multipart
 * @param attachments
 * @throws MessagingException
 */
private static void addFileAttachments(MimeMultipart multipart, List<MailAttachmentPO> attachments)
                throws MessagingException
{
    for (MailAttachmentPO attachment : attachments)
    {
        if (null == attachment.getCid() || attachment.getCid().isEmpty())
        {
            DataSource byteDataSource = new ByteArrayDataSource(attachment.getContent(), attachment.getMimeType());

            DataHandler attachementDataHandler = new DataHandler(byteDataSource);

            BodyPart memoryBodyPart = new MimeBodyPart();

            memoryBodyPart.setDataHandler(attachementDataHandler);

            memoryBodyPart.setFileName(attachment.getName());

            // Add part to multi-part
            multipart.addBodyPart(memoryBodyPart);
        }
    }
}
 
Example 19
Project: blynk-server   File: GMailClient.java   Source Code and License 6 votes vote down vote up
private void attachCSV(Multipart multipart, QrHolder[] attachmentData) throws Exception {
    StringBuilder sb = new StringBuilder();
    for (QrHolder qrHolder : attachmentData) {
        sb.append(qrHolder.token)
        .append(",")
        .append(qrHolder.deviceId)
        .append(",")
        .append(qrHolder.dashId)
        .append("\n");
    }
    MimeBodyPart attachmentsPart = new MimeBodyPart();
    ByteArrayDataSource source = new ByteArrayDataSource(sb.toString(), "text/csv");
    attachmentsPart.setDataHandler(new DataHandler(source));
    attachmentsPart.setFileName("tokens.csv");

    multipart.addBodyPart(attachmentsPart);
}
 
Example 20
Project: Lapwing   File: ITSProcessorImpl.java   Source Code and License 6 votes vote down vote up
@Override
public SOAPResponse check(SOAPRequest input) throws ServerException {

	Pipeline pipeline = new Pipeline();
	byte[] annotatedFile;
	try {
		Input ltinput = new Input();
		ltinput.setData(input.getData().getInputStream());
		ltinput.setEncoding(input.getEncoding());
		ltinput.setSrcLocale(input.getSource());
		ltinput.setTgtLocale(input.getTarget());
		Output output = pipeline.check(ltinput);
		SOAPResponse response = new SOAPResponse();
		annotatedFile = IOUtils.readBytesFromStream(output.getData());
		DataSource responseFile = new ByteArrayDataSource(annotatedFile,
				ITSProcessorImpl.OUTPUT_MIME_TYPE);
		DataHandler handler = new DataHandler(responseFile);
		response.setData(handler);
		response.setEncoding(output.getEncoding());
		return response;
	} catch (Exception e) {
		throw new ServerException(e);
	}

}
 
Example 21
Project: openhim-mediator-xds   File: XDSbMimeProcessorActor.java   Source Code and License 6 votes vote down vote up
private void parseMimeMessage(String msg, String contentType) throws IOException, MessagingException, SOAPPartNotFound, UnprocessableContentFound {
    mimeMessage = new MimeMultipart(new ByteArrayDataSource(msg, contentType));
    for (int i=0; i<mimeMessage.getCount(); i++) {
        BodyPart part = mimeMessage.getBodyPart(i);

        if (part.getContentType().contains("application/soap+xml")) {
            _soapPart = getValue(part);
        } else {
            _documents.add(getValue(part));
        }
    }

    if (_soapPart==null) {
        throw new SOAPPartNotFound();
    }
}
 
Example 22
Project: xltestview-plugin   File: XLTestServerImplTest.java   Source Code and License 6 votes vote down vote up
private void verifyUploadRequest(final RecordedRequest request) throws IOException, MessagingException {
    assertEquals(request.getRequestLine(), "POST /api/internal/import/testspecid HTTP/1.1");
    assertEquals(request.getHeader("accept"), "application/json; charset=utf-8");
    assertEquals(request.getHeader("authorization"), "Basic YWRtaW46YWRtaW4=");
    assertThat(request.getHeader("Content-Length"), is(nullValue()));
    assertThat(request.getHeader("Transfer-Encoding"), is("chunked"));
    assertThat(request.getChunkSizes().get(0), greaterThan(0));
    assertThat(request.getChunkSizes().size(), greaterThan(0));

    assertTrue(request.getBodySize() > 0);

    ByteArrayDataSource bads = new ByteArrayDataSource(request.getBody().inputStream(), "multipart/mixed");
    MimeMultipart mp = new MimeMultipart(bads);
    assertTrue(request.getBodySize() > 0);

    assertEquals(mp.getCount(), 2);
    assertEquals(mp.getContentType(), "multipart/mixed");

    // TODO could do additional checks on metadata content
    BodyPart bodyPart1 = mp.getBodyPart(0);
    assertEquals(bodyPart1.getContentType(), "application/json; charset=utf-8");

    BodyPart bodyPart2 = mp.getBodyPart(1);
    assertEquals(bodyPart2.getContentType(), "application/zip");
}
 
Example 23
Project: wso2-axis2   File: SOAPMessageFormatterTest.java   Source Code and License 6 votes vote down vote up
public void testMM7() throws Exception {
    SOAPMessageFormatter formatter = new SOAPMessageFormatter();
    MessageContext mc = new MessageContext();
    SOAPFactory factory = OMAbstractFactory.getSOAP11Factory();
    mc.setEnvelope(factory.getDefaultEnvelope());
    mc.setDoingSwA(true);
    Attachments attachments = mc.getAttachmentMap();
    attachments.addDataHandler("[email protected]", new DataHandler("test1", "text/plain"));
    attachments.addDataHandler("[email protected]", new DataHandler("test2", "text/plain"));
    mc.setProperty(Constants.Configuration.MM7_COMPATIBLE, true);
    OMOutputFormat format = new OMOutputFormat();
    format.setDoingSWA(true);
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    formatter.writeTo(mc, format, baos, true);
    
    MimeMultipart mp = new MimeMultipart(new ByteArrayDataSource(baos.toByteArray(), format.getContentType()));
    assertEquals(2, mp.getCount());
    BodyPart bp = mp.getBodyPart(0);
    assertEquals("<" + format.getRootContentId() + ">", bp.getHeader("Content-ID")[0]);
    bp = mp.getBodyPart(1);
    Object content = bp.getContent();
    assertTrue(content instanceof MimeMultipart);
    MimeMultipart inner = (MimeMultipart)content;
    assertEquals(2, inner.getCount());
    bp = inner.getBodyPart(0);
    assertEquals("<[email protected]>", bp.getHeader("Content-ID")[0]);
    assertEquals("test1", bp.getContent());
    bp = inner.getBodyPart(1);
    assertEquals("<[email protected]>", bp.getHeader("Content-ID")[0]);
    assertEquals("test2", bp.getContent());
}
 
Example 24
Project: cleverbus   File: EmailServiceCamelSmtpImpl.java   Source Code and License 6 votes vote down vote up
@Override
public void sendEmail(final Email email) {
    Assert.notNull(email, "email can not be null");
    Assert.notEmpty(email.getRecipients(), "email must have at least one recipients");
    Assert.hasText(email.getSubject(), "subject in email can not be empty");
    Assert.hasText(email.getBody(), "body in email can not be empty");

    producerTemplate.send("smtp://" + smtp, new Processor() {
        @Override
        public void process(final Exchange exchange) throws Exception {
            Message in = exchange.getIn();
            in.setHeader("To", StringUtils.join(email.getRecipients(), ","));
            in.setHeader("From", StringUtils.isBlank(email.getFrom()) ? from : email.getFrom());
            in.setHeader("Subject", email.getSubject());
            in.setHeader("contentType", email.getContentType().getContentType());
            in.setBody(email.getBody());
            if (email.getAllAtachments() != null && !email.getAllAtachments().isEmpty()) {
                for (EmailAttachment attachment : email.getAllAtachments()) {
                    in.addAttachment(attachment.getFileName(), new DataHandler(new ByteArrayDataSource(
                            attachment.getContent(), "*/*")));
                }
            }
        }
    });
}
 
Example 25
Project: elasticsearch-imap   File: AttachmentMapperTest.java   Source Code and License 6 votes vote down vote up
@Test
public void testAttachments() throws Exception{

        Map<String, Object> settings = settings("/river-imap-attachments.json");

	final Properties props = new Properties();
	final String user = XContentMapValues.nodeStringValue(settings.get("user"), null);
	final String password = XContentMapValues.nodeStringValue(settings.get("password"), null);

	for (final Map.Entry<String, Object> entry : settings.entrySet()) {

		if (entry != null && entry.getKey().startsWith("mail.")) {
			props.setProperty(entry.getKey(), String.valueOf(entry.getValue()));
		}
	}

	registerRiver("imap_river", "river-imap-attachments.json");

	final Session session = Session.getInstance(props);
	final Store store = session.getStore();
	store.connect(user, password);
	checkStoreForTestConnection(store);
	final Folder inbox = store.getFolder("INBOX");
	inbox.open(Folder.READ_WRITE);



	final MimeMessage message = new MimeMessage(session);
	message.setFrom(new InternetAddress(EMAIL_TO));
	message.addRecipient(Message.RecipientType.TO, new InternetAddress(EMAIL_USER_ADDRESS));
	message.setSubject(EMAIL_SUBJECT + "::attachment test");
	message.setSentDate(new Date());

	BodyPart bp = new MimeBodyPart();
	bp.setText("Text");
	Multipart mp = new MimeMultipart();
	mp.addBodyPart(bp);

	bp = new MimeBodyPart();
	DataSource ds = new ByteArrayDataSource(this.getClass().getResourceAsStream("/httpclient-tutorial.pdf"), AttachmentMapperTest.APPLICATION_PDF);
	bp.setDataHandler(new DataHandler(ds));
	bp.setFileName("httpclient-tutorial.pdf");
	mp.addBodyPart(bp);
	message.setContent(mp);

	inbox.appendMessages(new Message[]{message});
	IMAPUtils.close(inbox);
	IMAPUtils.close(store);

	//let the river index
	Thread.sleep(20*1000);

	esSetup.client().admin().indices().refresh(new RefreshRequest()).actionGet();

	SearchResponse searchResponse =  esSetup.client().prepareSearch("imapriverdata").setTypes("mail").execute().actionGet();
	Assert.assertEquals(1, searchResponse.getHits().totalHits());
               
	//BASE64 content httpclient-tutorial.pdf
	Assert.assertTrue(searchResponse.getHits().hits()[0].getSourceAsString().contains(AttachmentMapperTest.PDF_BASE64_DETECTION));

	searchResponse =  esSetup.client().prepareSearch("imapriverdata").addFields("*").setTypes("mail").setQuery(QueryBuilders.matchPhraseQuery("attachments.content.content", PDF_CONTENT_TO_SEARCH)).execute().actionGet();
	Assert.assertEquals(1, searchResponse.getHits().totalHits());

	Assert.assertEquals(1, searchResponse.getHits().hits()[0].field("attachments.content.content").getValues().size());
	Assert.assertEquals("HttpClient Tutorial", searchResponse.getHits().hits()[0].field("attachments.content.title").getValue().toString());
	Assert.assertEquals("application/pdf", searchResponse.getHits().hits()[0].field("attachments.content.content_type").getValue().toString());
	Assert.assertTrue(searchResponse.getHits().hits()[0].field("attachments.content.content").getValue().toString().contains(PDF_CONTENT_TO_SEARCH));

}
 
Example 26
Project: camel-agent   File: MailBinding.java   Source Code and License 6 votes vote down vote up
protected String populateContentOnMimeMessage(MimeMessage part, MailConfiguration configuration, Exchange exchange)
    throws MessagingException, IOException {

    String contentType = determineContentType(configuration, exchange);

    LOG.trace("Using Content-Type {} for MimeMessage: {}", contentType, part);

    String body = exchange.getIn().getBody(String.class);
    if (body == null) {
        body = "";
    }

    // always store content in a byte array data store to avoid various content type and charset issues
    DataSource ds = new ByteArrayDataSource(body, contentType);
    part.setDataHandler(new DataHandler(ds));

    // set the content type header afterwards
    part.setHeader("Content-Type", contentType);

    return contentType;
}
 
Example 27
Project: camel-agent   File: MailBinding.java   Source Code and License 6 votes vote down vote up
protected String populateContentOnBodyPart(BodyPart part, MailConfiguration configuration, Exchange exchange)
    throws MessagingException, IOException {

    String contentType = determineContentType(configuration, exchange);

    if (contentType != null) {
        LOG.trace("Using Content-Type {} for BodyPart: {}", contentType, part);

        // always store content in a byte array data store to avoid various content type and charset issues
        String data = exchange.getContext().getTypeConverter().tryConvertTo(String.class, exchange.getIn().getBody());
        // use empty data if the body was null for some reason (otherwise there is a NPE)
        data = data != null ? data : "";

        DataSource ds = new ByteArrayDataSource(data, contentType);
        part.setDataHandler(new DataHandler(ds));

        // set the content type header afterwards
        part.setHeader("Content-Type", contentType);
    }

    return contentType;
}
 
Example 28
Project: PortlandStateJava   File: Survey.java   Source Code and License 6 votes vote down vote up
private static MimeBodyPart createXmlAttachment(Student student) {
  byte[] xmlBytes = getXmlBytes(student);

  if (saveStudentXmlFile) {
    writeStudentXmlToFile(xmlBytes, student);
  }

  DataSource ds = new ByteArrayDataSource(xmlBytes, "text/xml");
  DataHandler dh = new DataHandler(ds);
  MimeBodyPart filePart = new MimeBodyPart();
  try {
    String xmlFileTitle = student.getId() + ".xml";

    filePart.setDataHandler(dh);
    filePart.setFileName(xmlFileTitle);
    filePart.setDescription("XML file for " + student.getFullName());

  } catch (MessagingException ex) {
    printErrorMessageAndExit("** Exception with file part", ex);
  }
  return filePart;
}
 
Example 29
Project: extemporal   File: EmailTestPlatform.java   Source Code and License 6 votes vote down vote up
protected boolean transmitEmail(String to, ByteBuffer msgContent, Message emailSkeleton)
{
	try {
		if (emailSkeleton == null) {
			emailSkeleton = new MimeMessage(mSession);
			emailSkeleton.setFrom(new InternetAddress(mEndpoint));
			emailSkeleton.setRecipients(Message.RecipientType.TO, InternetAddress.parse(to));
		}

		byte[] mc = new byte[msgContent.remaining()];
		msgContent.get(mc);
		ByteArrayDataSource dSrc = new ByteArrayDataSource(mc, "application/octet-stream");
		emailSkeleton.setDataHandler(new DataHandler(dSrc));

		final Transport channel = mSession.getTransport(mSmtpAccountURN);
		channel.connect();	// throws if can't connect
		channel.sendMessage(emailSkeleton, emailSkeleton.getRecipients(Message.RecipientType.TO));
		channel.close();
	}
	catch (MessagingException e) {
		e.printStackTrace();
		return false;
	}
	return true;
}
 
Example 30
Project: dropwizard-jaxws   File: JAXWSEnvironmentTest.java   Source Code and License 6 votes vote down vote up
@Test
public void publishEndpointWithMtom() throws Exception {

    jaxwsEnvironment.publishEndpoint(
            new EndpointBuilder("local://path", service)
                    .enableMtom());

    verify(mockInvokerBuilder).create(any(), any(Invoker.class));

    byte[] response = testutils.invokeBytes("local://path", LocalTransportFactory.TRANSPORT_ID, soapRequest.getBytes());

    verify(mockInvoker).invoke(any(Exchange.class), any());

    MimeMultipart mimeMultipart = new MimeMultipart(new ByteArrayDataSource(response,
            "application/xop+xml; charset=UTF-8; type=\"text/xml\""));
    assertThat(mimeMultipart.getCount(), equalTo(1));
    testutils.assertValid("/soap:Envelope/soap:Body/a:fooResponse",
            StaxUtils.read(mimeMultipart.getBodyPart(0).getInputStream()));
}
 
Example 31
Project: dropwizard-jaxws   File: AccessMtomServiceResource.java   Source Code and License 6 votes vote down vote up
@GET
@Timed
public String getFoo() {

    ObjectFactory of = new ObjectFactory();
    Hello h = of.createHello();
    h.setTitle("Hello");
    h.setBinary(new DataHandler(new ByteArrayDataSource("test".getBytes(), "text/plain")));

    HelloResponse hr = mtomServiceClient.hello(h);

    try {
        return "Hello response: " + hr.getTitle() + ", " +
                IOUtils.readStringFromStream(hr.getBinary().getInputStream());
    }
    catch (IOException e) {
        throw new RuntimeException(e);
    }
}
 
Example 32
Project: jersey-smime   File: SignedTest.java   Source Code and License 6 votes vote down vote up
@Test
public void testOutput2() throws Exception {
    SMIMESignedGenerator gen = new SMIMESignedGenerator();
    SignerInfoGenerator signer = new JcaSimpleSignerInfoGeneratorBuilder().setProvider("BC").build("SHA1WITHRSA", privateKey, cert);
    gen.addSignerInfoGenerator(signer);

    MimeMultipart mp = gen.generate(createMsg());

    ByteArrayOutputStream os = new ByteArrayOutputStream();
    mp.writeTo(os);

    ByteArrayInputStream is = new ByteArrayInputStream(os.toByteArray());
    String contentType = mp.getContentType();
    contentType = contentType.replace("\r\n", "").replace("\t", " ");

    ByteArrayDataSource ds = new ByteArrayDataSource(is, contentType);
    MimeMultipart mm = new MimeMultipart(ds);
    MimeBodyPart part = (MimeBodyPart) mm.getBodyPart(0);


}
 
Example 33
Project: logistimo-web-service   File: EmailService.java   Source Code and License 5 votes vote down vote up
private void addAttachment(Multipart mp, byte[] attachmentData, String mimeType, String filename)
    throws MessagingException {
  if (mp == null) {
    return;
  }
  ByteArrayDataSource dataSrc = new ByteArrayDataSource(attachmentData, mimeType);
  MimeBodyPart attachment = new MimeBodyPart();
  attachment.setFileName(filename);
  attachment.setDataHandler(new DataHandler(dataSrc));
  ///attachment.setContent( attachmentData, mimeType );
  mp.addBodyPart(attachment);
}
 
Example 34
Project: logistimo-web-service   File: EmailService.java   Source Code and License 5 votes vote down vote up
private void addAttachmentStream(Multipart mp, InputStream attachmentStream, String mimeType,
                                 String filename, BodyPart message)
    throws MessagingException, IOException {
  if (mp == null) {
    return;
  }
  ByteArrayDataSource dataSrc = new ByteArrayDataSource(attachmentStream, mimeType);
  MimeBodyPart attachment = new MimeBodyPart();
  attachment.setFileName(filename);
  attachment.setDataHandler(new DataHandler(dataSrc));
  ///attachment.setContent( attachmentData, mimeType );
  mp.addBodyPart(message);
  mp.addBodyPart(attachment);
}
 
Example 35
Project: chronos   File: CallableQuery.java   Source Code and License 5 votes vote down vote up
@CoverageIgnore
private static DataSource createAttachment(PersistentResultSet results) {
  try {
    String text = makeAttachmentText(results);
    DataSource source = new ByteArrayDataSource(text, TSV);
    return source;
  } catch (IOException e) {
    throw new RuntimeException(e);
  }
}
 
Example 36
Project: openex-worker   File: EmailAttacher.java   Source Code and License 5 votes vote down vote up
@SuppressWarnings({"unused", "unchecked"})
public void process(Exchange exchange) {
    List<EmailAttachment> filesContent = (List) exchange.getProperty(ATTACHMENTS_CONTENT, new ArrayList<>());
    for (EmailAttachment attachment : filesContent) {
        ByteArrayDataSource bds = new ByteArrayDataSource(attachment.getData(), attachment.getContentType());
        exchange.getIn().addAttachmentObject(attachment.getName(), new DefaultAttachment(bds));
    }
}
 
Example 37
Project: SoapUI-Cookbook   File: InvoicePortImpl.java   Source Code and License 5 votes vote down vote up
public void getInvoice(javax.xml.ws.Holder<java.lang.String> invoiceNo,
		javax.xml.ws.Holder<java.lang.String> company,
		javax.xml.ws.Holder<java.lang.Double> amount,
		javax.xml.ws.Holder<javax.activation.DataHandler> file) {
	
	LOG.info("Executing operation getInvoice");
	System.out.println("Invoice no: "+invoiceNo.value);
	
	try {
		company.value = "company";
		System.out.println("Company: "+company.value);
		amount.value = 100d;
		System.out.println("Amount: "+amount);

		String attachmentFileName = "/temp/invoice1.pdf";
		System.out.println("Attachment: "+attachmentFileName);
		File attachment = new File(attachmentFileName);
		InputStream attachmentInputStream = new FileInputStream(attachment);
		ByteArrayOutputStream responseOutputStream = new ByteArrayOutputStream();
		copyInputStreamToOutputStream(attachmentInputStream,
				responseOutputStream);
		System.out.println("Attachment size: "
				+ responseOutputStream.size());
		attachmentInputStream.close();
		file.value = new DataHandler(new ByteArrayDataSource(
				responseOutputStream.toByteArray(), "application/pdf"));

	} catch (Exception ex) {
		ex.printStackTrace();
		throw new RuntimeException(ex);
	}
}
 
Example 38
Project: qianworks-meican   File: MimeMessageParser.java   Source Code and License 5 votes vote down vote up
/**
 * Parses the MimePart to create a DataSource.
 *
 * @param part   the current part to be processed
 * @return the DataSource
 * @throws MessagingException creating the DataSource failed
 * @throws IOException        creating the DataSource failed
 */
private static DataSource createDataSource(final MimePart part)
        throws MessagingException, IOException {
    final DataHandler dataHandler = part.getDataHandler();
    final DataSource dataSource = dataHandler.getDataSource();
    final String contentType = getBaseMimeType(dataSource.getContentType());
    final byte[] content = MimeMessageParser.getContent(dataSource.getInputStream());
    final ByteArrayDataSource result = new ByteArrayDataSource(content, contentType);
    final String dataSourceName = getDataSourceName(part, dataSource);

    result.setName(dataSourceName);
    return result;
}
 
Example 39
Project: Camel   File: MimeMultipartDataFormat.java   Source Code and License 5 votes vote down vote up
private void writeBodyPart(byte[] bodyContent, Part part, ContentType contentType) throws MessagingException {
    DataSource ds = new ByteArrayDataSource(bodyContent, contentType.toString());
    part.setDataHandler(new DataHandler(ds));
    part.setHeader(CONTENT_TYPE, contentType.toString());
    if (contentType.match("text/*")) {
        part.setHeader(CONTENT_TRANSFER_ENCODING, "8bit");
    } else if (binaryContent) {
        part.setHeader(CONTENT_TRANSFER_ENCODING, "binary");
    } else {
        part.setHeader(CONTENT_TRANSFER_ENCODING, "base64");
    }
}
 
Example 40
Project: metaworks_framework   File: MessageCreator.java   Source Code and License 5 votes vote down vote up
public MimeMessagePreparator buildMimeMessagePreparator(final Map<String, Object> props) {
    MimeMessagePreparator preparator = new MimeMessagePreparator() {

        @Override
        public void prepare(MimeMessage mimeMessage) throws Exception {
            EmailTarget emailUser = (EmailTarget) props.get(EmailPropertyType.USER.getType());
            EmailInfo info = (EmailInfo) props.get(EmailPropertyType.INFO.getType());
            boolean isMultipart = CollectionUtils.isNotEmpty(info.getAttachments());
            MimeMessageHelper message = new MimeMessageHelper(mimeMessage, isMultipart, info.getEncoding());
            message.setTo(emailUser.getEmailAddress());
            message.setFrom(info.getFromAddress());
            message.setSubject(info.getSubject());
            if (emailUser.getBCCAddresses() != null && emailUser.getBCCAddresses().length > 0) {
                message.setBcc(emailUser.getBCCAddresses());
            }
            if (emailUser.getCCAddresses() != null && emailUser.getCCAddresses().length > 0) {
                message.setCc(emailUser.getCCAddresses());
            }
            String messageBody = info.getMessageBody();
            if (messageBody == null) {
                messageBody = buildMessageBody(info, props);
            }
            message.setText(messageBody, true);
            for (Attachment attachment : info.getAttachments()) {
                ByteArrayDataSource dataSource = new ByteArrayDataSource(attachment.getData(), attachment.getMimeType());
                message.addAttachment(attachment.getFilename(), dataSource);
            }
        }
    };
    return preparator;

}
 
Example 41
Project: openxds   File: ProvideAndRegisterDocumentSetTest.java   Source Code and License 5 votes vote down vote up
protected OMElement addOneDocument(OMElement request, String document, String documentId, boolean includeWhitespace) throws IOException {
	OMFactory fac = OMAbstractFactory.getOMFactory();
	OMNamespace ns = fac.createOMNamespace("urn:ihe:iti:xds-b:2007" , null);
	OMElement docElem = fac.createOMElement("Document", ns);
	docElem.addAttribute("id", documentId, null);

       // A string, turn it into an StreamSource
    DataSource ds = new ByteArrayDataSource(document, "text/xml"); 
	DataHandler handler = new DataHandler(ds);
	 
       OMText binaryData = fac.createOMText(handler, true);
       if (includeWhitespace)
       {
        /** The whitespace */
        docElem.addChild(fac.createOMText("\n"));
       }
       docElem.addChild(binaryData);

       Iterator iter = request.getChildrenWithLocalName("SubmitObjectsRequest");
       OMElement submitObjectsRequest = null;
       for (;iter.hasNext();) {
       	submitObjectsRequest = (OMElement)iter.next();
       	if (submitObjectsRequest != null)
       		break;
       }
       submitObjectsRequest.insertSiblingAfter(docElem);
       return request;
}
 
Example 42
Project: kc-rice   File: MailerImpl.java   Source Code and License 5 votes vote down vote up
protected void prepareHtmlMessage(String messageText, Message message) throws MessagingException {
      try {
	message.setDataHandler(new DataHandler(new ByteArrayDataSource(messageText, "text/html")));
} catch (IOException e) {
	LOG.warn(e.getMessage());
	throw new RuntimeException(e);
}
  }
 
Example 43
Project: SparkCommerce   File: MessageCreator.java   Source Code and License 5 votes vote down vote up
public MimeMessagePreparator buildMimeMessagePreparator(final Map<String, Object> props) {
    MimeMessagePreparator preparator = new MimeMessagePreparator() {

        @Override
        public void prepare(MimeMessage mimeMessage) throws Exception {
            EmailTarget emailUser = (EmailTarget) props.get(EmailPropertyType.USER.getType());
            EmailInfo info = (EmailInfo) props.get(EmailPropertyType.INFO.getType());
            boolean isMultipart = CollectionUtils.isNotEmpty(info.getAttachments());
            MimeMessageHelper message = new MimeMessageHelper(mimeMessage, isMultipart, info.getEncoding());
            message.setTo(emailUser.getEmailAddress());
            message.setFrom(info.getFromAddress());
            message.setSubject(info.getSubject());
            if (emailUser.getBCCAddresses() != null && emailUser.getBCCAddresses().length > 0) {
                message.setBcc(emailUser.getBCCAddresses());
            }
            if (emailUser.getCCAddresses() != null && emailUser.getCCAddresses().length > 0) {
                message.setCc(emailUser.getCCAddresses());
            }
            String messageBody = info.getMessageBody();
            if (messageBody == null) {
                messageBody = buildMessageBody(info, props);
            }
            message.setText(messageBody, true);
            for (Attachment attachment : info.getAttachments()) {
                ByteArrayDataSource dataSource = new ByteArrayDataSource(attachment.getData(), attachment.getMimeType());
                message.addAttachment(attachment.getFilename(), dataSource);
            }
        }
    };
    return preparator;

}
 
Example 44
Project: simple-java-mail   File: MimeMessageParser.java   Source Code and License 5 votes vote down vote up
/**
 * Parses the MimePart to create a DataSource.
 *
 * @param part the current part to be processed
 * @return the DataSource
 */
@Nonnull
private static DataSource createDataSource(@Nonnull final MimePart part) {
	final DataHandler dataHandler = retrieveDataHandler(part);
	final DataSource dataSource = dataHandler.getDataSource();
	final String contentType = parseBaseMimeType(dataSource.getContentType());
	final byte[] content = readContent(retrieveInputStream(dataSource));
	final ByteArrayDataSource result = new ByteArrayDataSource(content, contentType);
	final String dataSourceName = parseDataSourceName(part, dataSource);

	result.setName(dataSourceName);
	return result;
}
 
Example 45
Project: simple-java-mail   File: EmailPopulatingBuilder.java   Source Code and License 5 votes vote down vote up
/**
 * Delegates to {@link #withEmbeddedImage(String, DataSource)}, with a named {@link ByteArrayDataSource} created using the provided name, data and
 * mimetype.
 *
 * @param name     The name of the image as being referred to from the message content body (eg. 'signature').
 * @param data     The byte data of the image to be embedded.
 * @param mimetype The content type of the given data (eg. "image/gif" or "image/jpeg").
 */
public EmailPopulatingBuilder withEmbeddedImage(@Nonnull final String name, @Nonnull final byte[] data, @Nonnull final String mimetype) {
	checkNonEmptyArgument(name, "name");
	checkNonEmptyArgument(data, "data");
	checkNonEmptyArgument(mimetype, "mimetype");
	
	final ByteArrayDataSource dataSource = new ByteArrayDataSource(data, mimetype);
	dataSource.setName(name);
	return withEmbeddedImage(name, dataSource);
}
 
Example 46
Project: simple-java-mail   File: EmailPopulatingBuilderTest.java   Source Code and License 5 votes vote down vote up
@Test
public void testBuilderAddingAttachmentsWithMissingNameWithoutExceptions() {
	builder
			.withAttachment("a", new ByteArrayDataSource(new byte[3], "text/txt"))
			.withAttachment(null, new DataSourceWithDummyName())
			.withAttachment("a", new byte[3], "text/txt")
			.withAttachment(null, new ByteArrayDataSource(new byte[3], "text/txt"))
			.withAttachment(null, new byte[3], "text/txt");
	// ok no exceptions
}
 
Example 47
Project: simple-java-mail   File: EmailHelper.java   Source Code and License 5 votes vote down vote up
public static EmailPopulatingBuilder createDummyEmailBuilder(@Nullable String id, boolean includeSubjectAndBody, boolean basicFields, boolean includeCustomHeaders)
		throws IOException {
	EmailPopulatingBuilder builder = EmailBuilder.startingBlank()
			.fixingMessageId(id)
			.from("lollypop", "[email protected]")
			// don't forget to add your own address here ->
			.to("C.Cane", "[email protected]");
	
	if (!basicFields) {
		// normally not needed, but for the test it is because the MimeMessage will
		// have it added automatically as well, so the parsed Email will also have it then
		builder = builder
			.withReplyTo("lollypop-reply", "[email protected]")
			.withBounceTo("lollypop-bounce", "[email protected]");
	}
	if (includeSubjectAndBody) {
		builder = builder
			.withSubject("hey")
			.withPlainText("We should meet up!")
			.withHTMLText("<b>We should meet up!</b><img src='cid:thumbsup'>");
	}

	if (includeCustomHeaders) {
		builder = builder
			.withHeader("dummyHeader", "dummyHeaderValue")
			.withDispositionNotificationTo("[email protected]")
			.withReturnReceiptTo("Complex Email", "[email protected]");
	}

	// add two text files in different ways and a black thumbs up embedded image ->
	ByteArrayDataSource namedAttachment = new ByteArrayDataSource("Black Tie Optional", "text/plain");
	namedAttachment.setName("dresscode.txt"); // normally not needed, but otherwise the equals will fail
	String base64String = "iVBORw0KGgoAAAANSUhEUgAAACAAAAAgCAYAAABzenr0AAABeElEQVRYw2NgoAAYGxu3GxkZ7TY1NZVloDcAWq4MxH+B+D8Qv3FwcOCgtwM6oJaDMTAUXOhmuYqKCjvQ0pdoDrCnmwNMTEwakC0H4u8GBgYC9Ap6DSD+iewAoIPm0ctyLqBlp9F8/x+YE4zpYT8T0LL16JYD8U26+B7oyz4sloPwenpYno3DchCeROsUbwa05A8eB3wB4kqgIxOAuArIng7EW4H4EhC/B+JXQLwDaI4ryZaDSjeg5mt4LCcFXyIn1fdSyXJQVt1OtMWGhoai0OD8T0W8GohZifE1PxD/o7LlsPLiFNAKRrwOABWptLAcqc6QGDAHQEOAYaAc8BNotsJAOgAUAosG1AFA/AtUoY3YEFhKMAvS2AE7iC1+WaG1H6gY3gzE36hUFJ8mqzbU1dUVBBqQBzTgIDQRkWo5qCZdpaenJ0Zx1aytrc0DDB0foIG1oAYKqC0IZK8D4n1AfA6IzwPxXpCFoGoZVEUDaRGGUTAKRgEeAAA2eGJC+ETCiAAAAABJRU5ErkJggg==";
	
	return builder
			.withAttachment("dresscode.txt", namedAttachment)
			.withAttachment("location.txt", "On the moon!".getBytes(Charset.defaultCharset()), "text/plain")
			.withEmbeddedImage("thumbsup", parseBase64Binary(base64String), "image/png");
}
 
Example 48
Project: openmeetings   File: MailHandler.java   Source Code and License 5 votes vote down vote up
public MimeMessage appendBody(MimeMessage msg, String body) throws MessagingException, IOException {
	// -- Set the subject and body text --
	msg.setDataHandler(new DataHandler(new ByteArrayDataSource(body, "text/html; charset=\"utf-8\"")));

	// -- Set some other header information --
	msg.setHeader("X-Mailer", "XML-Mail");
	msg.setSentDate(new Date());

	return msg;
}
 
Example 49
Project: subethasmtp   File: MessageContentTest.java   Source Code and License 5 votes vote down vote up
/** */
public void testBinaryEightBitMessage() throws Exception
{
	byte[] body = new byte[64];
	new Random().nextBytes(body);

	MimeMessage message = new MimeMessage(this.session);
	message.addRecipient(Message.RecipientType.TO, new InternetAddress("[email protected]"));
	message.setFrom(new InternetAddress("[email protected]"));
	message.setSubject("hello");
	message.setHeader("Content-Transfer-Encoding", "8bit");
	message.setDataHandler(new DataHandler(new ByteArrayDataSource(body, "application/octet-stream")));

	Transport.send(message);

	InputStream in = this.wiser.getMessages().get(0).getMimeMessage().getInputStream();
	ByteArrayOutputStream tmp = new ByteArrayOutputStream();
	byte[] buf = new byte[64];
	int n;
	while ((n = in.read(buf)) != -1)
	{
		tmp.write(buf, 0, n);
	}
	in.close();

	assertTrue(Arrays.equals(body, tmp.toByteArray()));
}
 
Example 50
Project: Raven-Messenger   File: MailControlAndroid.java   Source Code and License 5 votes vote down vote up
public static void sendMailAndroid(final MailProfile mailProfile, String recipient, String subject, String text) throws Exception {  
 	Properties props = new Properties();   
     props.setProperty("mail.transport.protocol", "smtp");   
     props.setProperty("mail.host", mailProfile.getSmtpHost());   
     props.put("mail.smtp.auth", "true");   
     props.put("mail.smtp.port", mailProfile.getSmtpPort());   
     
     try{
     Session session = Session.getInstance(props, new javax.mail.Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
	return new PasswordAuthentication(mailProfile.getUsername(), mailProfile.getPassword());
}
 });
     MimeMessage message = new MimeMessage(session);   
     DataHandler handler = new DataHandler(new ByteArrayDataSource(text.getBytes(), "text/plain"));  
     message.setSender(new InternetAddress(mailProfile.getEmail()));   
     message.setSubject(subject);   
     message.setFrom(new InternetAddress(mailProfile.getEmail()));
     message.setDataHandler(handler);   
     if (recipient.indexOf(',') > 0)   
         message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(recipient));   
     else  
         message.setRecipient(Message.RecipientType.TO, new InternetAddress(recipient));   
     Transport.send(message);   
     }catch(Exception e){
     	e.printStackTrace();
     }
 }
 
Example 51
Project: respiro   File: SMTPMailSender.java   Source Code and License 5 votes vote down vote up
private void addAttachments(MultiPartEmail mail, Message msg) {
    for (Attachment attachment : msg.getAttachments()) {
        try {
            mail.attach(new ByteArrayDataSource(attachment.getContent(), attachment.getMimeType()), attachment.getFileName(), "");
        } catch (EmailException e) {
            throw new RuntimeException(e);
        }
    }
}
 
Example 52
Project: techytax-zk   File: MailHelper.java   Source Code and License 5 votes vote down vote up
public static void sendInvoice(Invoice factuur, byte[] invoiceBuf, User user) throws Exception {
	loadProperties();
	String to = factuur.getEmail();
	String bcc = factuur.getEmailBcc();
	String cc = factuur.getEmailCc();
	String subj = "Factuur " + factuur.getInvoiceNumber();
	Session session = Session.getDefaultInstance(props);
	session.setDebug(true);
	Message msg = new MimeMessage(session);
	InternetAddress[] toAddrs = null, ccAddrs = null, bccAddrs = null;

	if (to != null) {
		toAddrs = InternetAddress.parse(to, false);
		msg.setRecipients(Message.RecipientType.TO, toAddrs);
	} else
		throw new MessagingException("No \"To\" address specified");

	if (cc != null) {
		ccAddrs = InternetAddress.parse(cc, false);
		msg.setRecipients(Message.RecipientType.CC, ccAddrs);
	} 

	if (bcc != null) {
		bccAddrs = InternetAddress.parse(bcc, false);
		msg.setRecipients(Message.RecipientType.BCC, bccAddrs);
	} else {
		bccAddrs = InternetAddress.parse(user.getEmail(), false);
		msg.setRecipients(Message.RecipientType.BCC, bccAddrs);
	}

	if (subj != null)
		msg.setSubject(subj);

	msg.setFrom(new InternetAddress(user.getCompanyName() + " <" + user.getEmail() + ">"));

	MimeMultipart multipart = new MimeMultipart("related");

	BodyPart messageBodyPart = new MimeBodyPart();
	String htmlText = "Zie bijlage.";
	messageBodyPart.setContent(htmlText, "text/html");
	multipart.addBodyPart(messageBodyPart);

	messageBodyPart = new MimeBodyPart();
	DataSource fds = new ByteArrayDataSource(invoiceBuf, "application/pdf");
	messageBodyPart.setDataHandler(new DataHandler(fds));
	messageBodyPart.setHeader("Content-ID", "<application/pdf>");
	messageBodyPart.setFileName("factuur.pdf");
	multipart.addBodyPart(messageBodyPart);

	msg.setContent(multipart);
	Transport tr = session.getTransport("smtp");
	tr.connect(props.getProperty("mail.smtp.host"), 465, props.getProperty("mail.smtp.user"), props.getProperty("mail.smtp.password"));
	msg.saveChanges();
	tr.sendMessage(msg, msg.getAllRecipients());
	tr.close();
}
 
Example 53
Project: omr   File: ParticipationHelperWS.java   Source Code and License 5 votes vote down vote up
/**
 * 
 * @param jp
 * @return
 */
private DataHandler exportToDataHandlerPDF(JasperPrint jp) {
	ByteArrayOutputStream baosPDF = new ByteArrayOutputStream();

	JRPdfExporter exporter = new JRPdfExporter();
	exporter.setParameter(JRExporterParameter.JASPER_PRINT, jp);
	exporter.setParameter(JRExporterParameter.OUTPUT_STREAM, baosPDF);
			
	try {
		exporter.exportReport();
	} catch (JRException e1) {
		throw new JazzOMRRuntimeException("Erro ao tentar exportar relatorio", e1);
	}

	byte[] xmlBytes = null;
	try {
		baosPDF.flush();
		xmlBytes = baosPDF.toByteArray();
		baosPDF.close();
	} catch (IOException e) {
		throw new JazzOMRRuntimeException("Erro ao tentar exportar relatorio", e);
	}

	DataSource source = new ByteArrayDataSource(xmlBytes, "application/pdf");
	DataHandler dataHandler = new DataHandler(source);
	
	return dataHandler;
}
 
Example 54
Project: omr   File: ParticipationHelperWS.java   Source Code and License 5 votes vote down vote up
/**
 * 
 * @param jp
 * @return
 */
private DataHandler exportToDataHandlerPDF(JasperPrint jp) {
	ByteArrayOutputStream baosPDF = new ByteArrayOutputStream();

	JRPdfExporter exporter = new JRPdfExporter();
	exporter.setParameter(JRExporterParameter.JASPER_PRINT, jp);
	exporter.setParameter(JRExporterParameter.OUTPUT_STREAM, baosPDF);
			
	try {
		exporter.exportReport();
	} catch (JRException e1) {
		throw new JazzRuntimeException("Erro ao tentar exportar relatorio", e1);
	}

	byte[] xmlBytes = null;
	try {
		baosPDF.flush();
		xmlBytes = baosPDF.toByteArray();
		baosPDF.close();
	} catch (IOException e) {
		throw new JazzRuntimeException("Erro ao tentar exportar relatorio", e);
	}

	DataSource source = new ByteArrayDataSource(xmlBytes, "application/pdf");
	DataHandler dataHandler = new DataHandler(source);
	
	return dataHandler;
}
 
Example 55
Project: EmailModuleWithTemplates   File: Sender.java   Source Code and License 5 votes vote down vote up
private void setAttachments(List<IMendixObject> attachments, MultiPartEmail multipart) throws CoreException 
{
	if(this.context == null && attachments != null)
		throw new MendixRuntimeException("Context should not be null when sending e-mails with attachments");
	
	if(attachments != null && this.context != null) {
		int i = 1;
	
		for (IMendixObject attachment : attachments) {
			if(attachment != null) {
				if(!Core.isSubClassOf(FILE_DOCUMENT, attachment.getType())) {
					throw new CoreException("Attachment is no fileDocument");
				}
				
				String mimeType = (new MimetypesFileTypeMap()).getContentType((String) attachment.getValue(this.context, FILE_DOCUMENT_NAME));
				InputStream content = Core.getFileDocumentContent(this.context, attachment);
	
				try {
					if(content != null && content.available() > 0) {
						DataSource source = new ByteArrayDataSource(content, mimeType);
						String fileName = (String) attachment.getValue(this.context, FILE_DOCUMENT_NAME);
						
						if("".equals(fileName)) fileName = "Attachment" + i;
						
						multipart.attach(source, fileName, fileName);
					}
				
				} catch (Exception e) 
				{
					throw new CoreException("Unable to attach attachment " + (String) attachment.getValue(this.context, FILE_DOCUMENT_NAME) + ".", e);
				}
			}
			i++;
		}
	}
}
 
Example 56
Project: blcdemo   File: MessageCreator.java   Source Code and License 5 votes vote down vote up
public MimeMessagePreparator buildMimeMessagePreparator(final Map<String, Object> props) {
    MimeMessagePreparator preparator = new MimeMessagePreparator() {

        @Override
        public void prepare(MimeMessage mimeMessage) throws Exception {
            EmailTarget emailUser = (EmailTarget) props.get(EmailPropertyType.USER.getType());
            EmailInfo info = (EmailInfo) props.get(EmailPropertyType.INFO.getType());
            boolean isMultipart = CollectionUtils.isNotEmpty(info.getAttachments());
            MimeMessageHelper message = new MimeMessageHelper(mimeMessage, isMultipart, info.getEncoding());
            message.setTo(emailUser.getEmailAddress());
            message.setFrom(info.getFromAddress());
            message.setSubject(info.getSubject());
            if (emailUser.getBCCAddresses() != null && emailUser.getBCCAddresses().length > 0) {
                message.setBcc(emailUser.getBCCAddresses());
            }
            if (emailUser.getCCAddresses() != null && emailUser.getCCAddresses().length > 0) {
                message.setCc(emailUser.getCCAddresses());
            }
            String messageBody = info.getMessageBody();
            if (messageBody == null) {
                messageBody = buildMessageBody(info, props);
            }
            message.setText(messageBody, true);
            for (Attachment attachment : info.getAttachments()) {
                ByteArrayDataSource dataSource = new ByteArrayDataSource(attachment.getData(), attachment.getMimeType());
                message.addAttachment(attachment.getFilename(), dataSource);
            }
        }
    };
    return preparator;

}
 
Example 57
Project: blynk-server   File: GMailClient.java   Source Code and License 5 votes vote down vote up
private void attachQRs(Multipart multipart, QrHolder[] attachmentData) throws Exception {
    for (QrHolder qrHolder : attachmentData) {
        MimeBodyPart attachmentsPart = new MimeBodyPart();
        ByteArrayDataSource source = new ByteArrayDataSource(qrHolder.data, "image/jpeg");
        attachmentsPart.setDataHandler(new DataHandler(source));
        attachmentsPart.setFileName(qrHolder.makeQRFilename());
        multipart.addBodyPart(attachmentsPart);
    }
}
 
Example 58
Project: blynk-server   File: SparkPostMailClient.java   Source Code and License 5 votes vote down vote up
@Override
public void sendHtmlWithAttachment(String to, String subj, String body, QrHolder[] attachments) throws Exception {
    MimeMessage message = new MimeMessage(session);
    message.setFrom(from);
    message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(to));
    message.setSubject(subj, "UTF-8");

    Multipart multipart = new MimeMultipart();

    MimeBodyPart bodyMessagePart = new MimeBodyPart();
    bodyMessagePart.setContent(body, TEXT_HTML_CHARSET_UTF_8);
    multipart.addBodyPart(bodyMessagePart);

    for (QrHolder qrHolder : attachments) {
        MimeBodyPart attachmentsPart = new MimeBodyPart();
        attachmentsPart.setDataHandler(new DataHandler(new ByteArrayDataSource(qrHolder.data, "image/jpeg")));
        attachmentsPart.setFileName(qrHolder.makeQRFilename());
        multipart.addBodyPart(attachmentsPart);
    }

    message.setContent(multipart);

    try (Transport transport = session.getTransport()) {
        transport.connect(host, username, password);
        transport.sendMessage(message, message.getAllRecipients());
    }

    log.trace("Mail to {} was sent. Subj : {}, body : {}", to, subj, body);
}
 
Example 59
Project: effektif   File: OutgoingEmailServiceImpl.java   Source Code and License 5 votes vote down vote up
protected MimeBodyPart createBodyPartAttachment(Attachment attachment) throws IOException, MessagingException {
  MimeBodyPart bodyPart = new MimeBodyPart();
  bodyPart.setFileName(attachment.getFileName());
  DataSource dataSource = new ByteArrayDataSource(attachment.getInputStream(), attachment.getContentType());
  bodyPart.setDataHandler(new DataHandler(dataSource));
  return bodyPart;
}
 
Example 60
Project: robe   File: MailItemTest.java   Source Code and License 5 votes vote down vote up
@Test
public void getAttachments() throws Exception {
    List<DataSource> sources = new LinkedList<DataSource>();
    sources.add(new ByteArrayDataSource("attachment1", "text"));
    sources.add(new ByteArrayDataSource("attachment2", "text"));

    item.setAttachments(sources);
    assertEquals(sources, item.getAttachments());
}