Java: Send A Letter With Binary Content In Memory

Download our Java samples from this page.
Find this sample in directory /test/com/postalmethods/client

This sample demonstrates how to send a letter through PostalMethods using the Address Outside method when the document to be sent is stored in memory as binary data as opposed to being read from the file system. This example is using an HTML file and shows how to encode is as binary but this sample is most useful when you create a binary document, such as a PDF, in memory.

package com.postalmethods.client;
import static org.junit.Assert.assertTrue;
import org.junit.Before;
import org.junit.Test;
import com.postalmethods.client.api.SendLetterAndAddressResponse;
import com.postalmethods.client.model.Address;
import com.postalmethods.client.model.BytesLetterContent;
import com.postalmethods.client.model.LetterContent;
 * Integration test that calls the SendLetterAndAddress web method.
 * <p>
 * For details about PostalMethods.SendLetterAndAddress see 
 * <a href="">the PostalMethods.SendLetterAndAddress reference</a>
public class SendLetterAndAddressWithBytesLetterContent {
    private PostalMethodsClient client;
    public void setUp() {
        client = new PostalMethodsClientFactory().build();
    public void testSendLetterAndAddressAsBytes() {
        Address address = new Address("George Washington", "", "The White House", "1600 Pennsylvania Ave", "", "Washington", "DC", "20500", "USA");
        String description = "Java: test letter with address";
        // Create document in memory.
        // This example uses a hard-coded HTML document.  You can create your
        // document any way you like as long as you provide a byte[] as shown
        // below.
        String documentType = "HTML";
        String document = "<html><body><h2>I just called to say 'I Love You'</h2></body></html>.";
        LetterContent letterContent = new BytesLetterContent( document.getBytes(), documentType );
        System.out.println("Making call to SendLetterAndAddress...");
        SendLetterAndAddressResponse response = client.sendLetterAndAddress(description, letterContent, address);
        System.out.println("Service call completed:\n" + response.getResult().toString());
        int code = response.getResult().getCode();
        assertTrue(code > 0);
        System.out.println("New letter id is: " + code);