Messaging

Overview

This document describes how to use the messaging capabilities of the BlackBerry® device. It includes the following sections:

Email messages

Packages: net.rim.blackberry.api.mail, net.rim.blackberry.api.mail.event

Creating and sending email messages

To create and send email messages, you must set the default Session, retrieve a Store instance, create the email message and store it in a retrieved sent folder, and set up and send the email message.

Click for code sample: Create and send a text email message

//Get the Store from the default mail Session. 
Store store = Session.getDefaultInstance().getStore(); 
 
//retrieve the sent folder 
Folder[] folders = store.list(Folder.SENT); 
Folder sentfolder = folders[0]; 
 
//create a new message and store it in the sent folder 
Message msg = new Message(sentfolder); 
Address recipients[] = new Address[1]; 
 
try 
{ 
    recipients[0]= new Address("user@company.com", "user"); 
   
    //add the recipient list to the message 
    msg.addRecipients(Message.RecipientType.TO, recipients); 
   
    //set a subject for the message 
    msg.setSubject(“Test email”); 
   
    //sets the body of the message 
    msg.setContent("This is a test email from my BlackBerry device"); 
   
    //sets priority 
    msg.setPriority(Message.Priority.HIGH); 
   
    //send the message 
    Transport.send(msg); 
} 
 
catch (Exception me) 
{ 
    System.err.printIn(me); 
}

Accessing HTML email messages

BlackBerry devices can receive an email message that contains HTML, plain text, or both. To access HTML content, BlackBerry devices must be running BlackBerry® Device Software 4.5 or later and must be associated with BlackBerry® Enterprise Server 4.1 SP6 or later or BlackBerry® Internet Service 2.5 or later. You cannot send HTML email messages from a BlackBerry device.

You can access the body of an email message in both HTML and plain text format. You can access the HTML body by using the MimeBodyPart class, and you can access the plain text body by using the TextBodyPart class, both of which are packaged inside a Multipart object.

The hierarchy of an email message can vary based on the content within the email message. Factors include whether the email body is in HTML or plain text format (or both), whether the email message contains a type of attachment supported by the BlackBerry Attachment Service, or whether the email message contains a type of attachment that is not supported by the BlackBerry Attachment Service. Because the hierarchy of an email message can vary, your application should be able to adapt to any hierarchy structure.

Click for code sample: Extract the HTML and plain text content from an email message

public class MessageViewScreen extends MainScreen
{
    private boolean _hasSupportedAttachment;
    private boolean _hasUnsupportedAttachment;
    private String _plainTextMessage = "";
    private String _htmlMessage = "";

    public MessageViewScreen(Message message)
    {
        super();
        findEmailBody(message.getContent());
 
        if( _hasSupportedAttachment )
        {
            this.add(new LabelField("This message has a supported attachment."));
        } 
        else if( _hasUnsupportedAttachment )
        {
            this.add(new LabelField("This message has an unsupported attachment type."));
        } 
        else
        {
            this.add(new LabelField("This message has no attachment."));
        }
 
        this.add(new SeparatorField());
        this.add(new EditField("Plain Text Message Body: ", _plainTextMessage));
        this.add(new SeparatorField());
        this.add(new EditField("HTML Message Body: ", _htmlMessage));
    } 
    //This method reads an email message to find the email body
    private void findEmailBody(Object obj)
    {
        //Reset the attachment flags.
        _hasSupportedAttachment = false;
        _hasUnsupportedAttachment = false;
 
        if(obj instanceof Multipart)
        {
            Multipart mp = (Multipart)obj;  
            //Extract all of the parts within the Multipart message. 
            for(int count=0; count < mp.getCount(); ++count)
            {                  
                findEmailBody(mp.getBodyPart(count));
            }
        } 
        else if (obj instanceof TextBodyPart)
        {
            //This message only has a text body.
            TextBodyPart tbp = (TextBodyPart)obj;
            readEmailBody(tbp);
        }
        else if (obj instanceof MimeBodyPart)
        { 
            MimeBodyPart mbp = (MimeBodyPart)obj;  
            if (mbp.getContentType().indexOf(ContentType.TYPE_TEXT_HTML_STRING) != -1)
            {   
                //The message has no attachments.
                //Read the email body, which may contain a 
                //TexBodyPart, MimeBodyPart or both.
                readEmailBody(mbp);  
            }
            else if  (mbp.getContentType().equals(ContentType.TYPE_MULTIPART_MIXED_STRING)  
                    || mbp.getContentType().equals(ContentType.TYPE_MULTIPART_ALTERNATIVE_STRING))  
            {  
                //The message has attachments or we are at the 
                //top level of the message. Dig deeper to find the body.
                //Extract all of the parts within the MimeBodyPart message.
                findEmailBody(mbp.getContent());  
            }
        }  
        else if (obj instanceof SupportedAttachmentPart)  
        { 
            //This is a supported attachment.  
            _hasSupportedAttachment = true;  
        }  
        else if (obj instanceof UnsupportedAttachmentPart)
        {  
            //This is an unsupported attachment.  
            _hasUnsupportedAttachment = true;
        }
    }
    private void readEmailBody(TextBodyPart tbp)
    {  
        //This is the plain text body.  
        _plainTextMessage = (String)tbp.getContent();
 
        //Determine if all of the text body part is present.  
        if (tbp.hasMore() && !tbp.moreRequestSent())
        {  
            //It does, request more of the message.  
            try
            {  
                Transport.more((BodyPart)tbp, true);
                Status.show("Requesting more of the plain text message body. " +
                            "Reopen the screen to view it once more has been received."); 
            }  
            catch (Exception ex)  
            {  
                Dialog.alert("Exception: " + ex.toString());  
            }  
        }  
    }
 
    //Displays the HTML or plain text body of the email message.  
    private void readEmailBody(MimeBodyPart mbp)  
    {  
        //Extract the content of the message.
        //Note that getContent() and getContentType() can both return null.
        //A production application should check for null in the following two statements.
        Object obj = mbp.getContent();
        String mimeType = mbp.getContentType();
        String body = null;
        //Determine if the data returned is a String or a byte array. 
        //If the BlackBerry is able to convert the HTML content  
        //into a String, then a String should be returned. If  
        //the encoding is not supported, a byte array is returned  
        //to allow your application to work with the raw data.
        if (obj instanceof String)  
        {  
            body = (String) obj;  
        }  
        else if (obj instanceof byte[])  
        {
            body = new String((byte[])obj);  
        }
        if (mimeType.indexOf(ContentType.TYPE_TEXT_PLAIN_STRING)  != -1)  
        {  
            //This is the plain text body.  
            _plainTextMessage = body;
 
            //Determine if all of the text body part is present.  
            if (mbp.hasMore() && !mbp.moreRequestSent())
            {  
                //It does, request more of the message.  
                try  
                {  
                    Transport.more((BodyPart)mbp, true);
                    Status.show("Requesting more of the plain text  message body. " +
                    		"Reopen the screen to view it once more has been received.");  
                }  
                catch (Exception ex)  
                {  
                    Dialog.alert("Exception: " + ex.toString());  
                }  
            }  
        }  
        else if (mimeType.indexOf(ContentType.TYPE_TEXT_HTML_STRING)  != -1)  
        {  
            //This is the HTML body part of the message.  
            _htmlMessage = body;   
            //Determine if all of the HTML body part is present. 
            if (mbp.hasMore() && !mbp.moreRequestSent()) 
            { 
                //It does, request more of the message.  
                try 
                {
                    Transport.more((BodyPart)mbp, true);
                    Status.show("Requesting more of the HTML message  body." +
                    		"Reopen the screen to view it once more has been received.");
                } 
                catch (Exception ex) 
                { 
                    Dialog.alert("Exception: " + ex.toString()); 
                }
            }
        }
    }
}

Handling email attachments

The BlackBerry device supports different types of formatted files as email attachments. For a list of supported attachments, see the information about the BlackBerry Attachment Service in the BlackBerry® Enterprise Server Feature and Technical Overview at www.blackberry.com/go/serverdocs and the BlackBerry® Internet Service Feature and Technical Overview at www.blackberry.com/go/docs/smartphone_users.

Creating and sending attachments

To send an email message with an attachment, create the Multipart object, create and add the attachment file to this object, and structure and send the email message.

Click for code sample: Create and send an email message with an attachment

//create a multipart 
Multipart mp = new Multipart(); 
  
//data for the content of the file 
String fileData = "<html>just a simple test</html>"; 
String messageData = "Mail Attachment Demo"; 
 
//create the file 
SupportedAttachmentPart sap = new
    SupportedAttachmentPart(mp,"text/html","file.html", fileData.getBytes()); 
 
TextBodyPart tbp = new TextBodyPart(mp,messageData); 
   
//add the message and file to the multipart 
mp.addBodyPart(tbp); 
mp.addBodyPart(sap); 
   
//create a message in the sent items folder 
Folder[] folders = Session.getDefaultInstance().getStore().list(Folder.SENT); 
   
Message message = new Message(folders[0]); 
   
//add recipients to the message and send 
try 
{ 
    Address toAdd = new Address("email@company.com","my email"); 
    Address[] toAdds = new Address[1]; 
    toAdds[0] = toAdd; 
    message.addRecipients(Message.RecipientType.TO,toAdds); 
    message.setContent(mp); 
    Transport.send(message); 
} 
  
catch (Exception e) 
{ 
    Dialog.inform(e.toString()); 
}

Downloading attachments

BlackBerry device users can use menu items to manage email attachments manually. To automatically download attachments in email messages in the background when messages arrive in the message list, you can use the DownloadProgressListener interface and the AttachmentDownloadManager class.

Note: The BlackBerry Attachment Service receives all attachments before third-party attachment handlers. For more information about the BlackBerry Attachment Service, see the BlackBerry Enterprise Server Administration Guide.

For an example of how to download attachments, see the AttachmentDemo sample application provided with the BlackBerry® Java® Development Environment.

Creating and sending PIN messages

Each BlackBerry device has a unique PIN (personal identification number) and supports PIN-to-PIN messaging sent using the messages application. To allow your application to create and send PIN messages from a BlackBerry device, you must set the default Session, retrieve a Store instance, set the destination PIN address, create the PIN message and store it in a retrieved sent folder, and set up and send the PIN message.

Click for code sample: Create and send a text PIN message

Store store = Session.getDefaultInstance().getStore();
 
//retrieve the sent folder
Folder[] folders = store.list(Folder.SENT);
Folder sentfolder = folders[0];
  
//create a new message and store it in the sent folder
Message msg = new Message(sentfolder);
PINAddress[] recipients = new PINAddress[1];
  
try
{
    //create a pin address with destination address of 20000001
    recipients[0]= new PINAddress("20000001", "Robert");
}
 
catch (AddressException ae)
{
    System.err.println(ae);
}
 
try
{
    //add the recipient list to the message
    msg.addRecipients(Message.RecipientType.TO, recipients);
 
    //set a subject for the message
    msg.setSubject("Test pin message");
  
    //sets the body of the message
    msg.setContent("This is a test pin message from my BlackBerry device");
  
    //send the message
    Transport.send(msg);
}
 
catch (MessagingException me)
{
    System.err.println(me);
}

Application messages [back to top]

Packages: net.rim.blackberry.api.messagelist

You can use the messagelist package to create application messages. An ApplicationMessage is a custom message that appears in the messages application and invokes your application when the user opens it or chooses a menu item that you provide for the message. For more information, see the Application Integration overview.

SMS and MMS messages [back to top]

Packages: javax.wireless.messaging, net.rim.blackberry.api.sms, net.rim.blackberry.api.mms

You can create applications that send and receive SMS (Short Message Service) messages or MMS (Multimedia Messaging Service) messages. SMS support is provided through JSR 120. MMS support is provided through JSR 205. You can perform the following actions:

Sending and receiving SMS messages

You can send SMS messages by using the javax.wireless.messaging APIs and the BlackBerry Invoke API.

Note: You cannot send SMS messages directly from a BlackBerry device that operates on a CDMA network. For detailed information and workarounds for this issue, see the BlackBerry Support Community Forums.

Click for code sample: Create and send an SMS message

MessageConnection mc = (MessageConnection)Connector.open(_openString);
TextMessage m = (TextMessage)mc.newMessage(MessageConnection.TEXT_MESSAGE); 
m.setAddress( "sms://5558888" );
m.setPayloadText( "An SMS Message for you" ); 
Invoke.invokeApplication( Invoke.APP_TYPE_MESSAGES, MessageArguments( m ) );

To receive SMS messages using BlackBerry JDE 4.6.0 or later, use the MessageListener interface. If you are using an earlier version of the BlackBerry JDE, use the MessageConnection interface.

Note: If you want specific SMS messages to be saved in an SMS message folder, you must specify the folder location using MessageArguments when the SMS message is received by the BlackBerry device. Applications cannot access SMS messages that are stored on the BlackBerry device.

To listen for incoming SMS messages that appear in the message list, set the port number argument in Connector.open() to 0Connector.open("sms://:0").

Click for code sample: Receive an SMS message using the MessageListener interface

MessageConnection _mc = (MessageConnection)Connector.open("sms://:0");  
_mc.setMessageListener(this); 
   
... 
   
public void notifyIncomingMessage(MessageConnection conn)  
{ 
    Message m = _mc.receive(); 
    String address = m.getAddress(); 
    String msg = null; 
    if ( m instanceof TextMessage ) 
    { 
        TextMessage tm = (TextMessage)m; 
        msg = tm.getPayloadText(); 
    } 
    else  if (m instance of BinaryMessage) 
    { 
        StringBuffer buf = new StringBuffer(); 
        byte[] data = ((BinaryMessage) m).getPayloadData(); 
   
        // convert Binary Data to Text 
        msg = new String(data, "UTF-8"); 
     } 
     else 
     {
         System.out.println("Invalid Message Format"); 
         System.out.println("Received SMS text from  " + address + " : " + msg); 
     }
}

Click for code sample: Receive an SMS message using the MessageConnection interface

MessageConnection _mc = (MessageConnection)Connector.open("sms://:0");  
   
for(;;) 
{ 
    Message m = _mc.receive(); 
    String address = m.getAddress(); 
    String msg = null; 
 
    if ( m instanceof TextMessage ) 
    { 
        TextMessage tm = (TextMessage)m; 
        msg = tm.getPayloadText(); 
    } 
    else if (m instance of BinaryMessage) 
    { 
        StringBuffer buf = new StringBuffer(); 
        byte[] data = ((BinaryMessage) m).getPayloadData(); 
        // convert Binary Data to Text 
        msg = new String(data, "UTF-8");    
    } 
    else 
    {
        System.out.println("Invalid Message Format"); 
        System.out.println("Received SMS text from " + address  + " : " + msg); 
    }
}

Sending and receiving MMS messages

MMS messages consist of an MMS header and body. The MMS header consists of address, priority, subject, and delivery information. The MMS body contains the multimedia attachment portion.

Sending MMS messages is similar to sending SMS messages, except that you must pass in the MULTIPART_MESSAGE constant when creating the MessageConnection object.

Click for code sample: Create and send an MMS message with text and a .jpeg file attachment

MessageConnection mc = (MessageConnection)Connector.open(_openString);
MultipartMessage mulMsg = 
    (MultipartMessage)msgConn.newMessage(MessageConnection.MULTIPART_MESSAGE);
mulMsg.setAddress(address);
mulMsg.setAddress("mms://mail@mail.com");
mulMsg.setSubject("JAVA MMS TEST");

String mimeType = "text/plain"; 
String encoding = "UTF-8";
String text = "Hello from my java midlet";
byte[] contents = text.getBytes(encoding);
MessagePart msgPart = new MessagePart(contents, 0, contents.length, 
    mimeType, "id1", "contentLocation", encoding);
mulMsg.addMessagePart(msgPart); 

InputStream is = getClass().getResourceAsStream("image.jpg");
mimeType = "image/jpeg"; 
contents = new byte[is.available()];
is.read(contents); 
msgPart = new MessagePart(contents, 0, contents.length, 
    mimeType, "id2", "bg.jpg", null);
mulMsg.addMessagePart(msgPart);

Invoke.invokeApplication( Invoke.APP_TYPE_MESSAGES, MessageArguments( m ) );

To receive MMS messages when using BlackBerry JDE 4.6.0 or later, use the MessageListener interface. If you are using an earlier version of the BlackBerry JDE, use the MessageConnection interface.

To listen for incoming MMS messages that appear in the message list, set the selected Connector.open() application ID to 0.

Click for code sample: Receive an MMS message using the MessageListener interface

MessageConnection _mc = 
    (MessageConnection)Connector.open("mms://+123456789:applicationID");  
_mc.setMessageListener(this); 
   
... 
   
public void notifyIncomingMessage(MessageConnection conn)  
{ 
    Message m = _mc.receive(); 
    String address = m.getAddress(); 
    String msg = null; 
    if ( m instanceof TextMessage ) 
    { 
        MultipartMessage mpm = (MultipartMessage)msg;
        String subject = mpm.getSubject();
        String date = mpm.getTimestamp().toString();
        MessagePart[] parts = mpm.getMessageParts(); 
    } 
    else  if (parts != null)
    {
        for (int i = 0; i < parts.length; i++)
        {
            MessagePart mp = parts[i];
            String mimeType = mp.getMIMEType();
            String contentLocation = mp.getContentLocation();
            byte[] ba = mp.getContent();
            try
            {
                Image image = Image.createImage(ba, 0, ba.length);
            } 
        } 
    } 
    else 
    {
        System.out.println("Invalid Message Format"); 
        System.out.println("Received MMS text from  " + address + " : " + msg); 
    }
}

Click for code sample: Receive an MMS message using the MessageConnection interface

public MessagePart[] receiveTextAndImageMMS() throws IOException 
{
 
    final Connection connection;
    
    try 
    {
        connection = Connector.open("mms://:5555");
    } 
    catch (Exception e) 
    {
        throw new IOException("unable to open connection:" + e.getMessage());
    }
 
    try 
    {
        final MessageConnection con = (MessageConnection) connection;
        final MultipartMessage message;
        try 
        {
            message = (MultipartMessage) con.receive();
        } 
        catch (IOException e) 
        {
            throw new IOException("unable to receive MMS message: " + e.getMessage());
        }
 
        final MessagePart[] parts = message.getMessageParts();
        if (parts == null || parts.length == 0) 
        {
            throw new IOException("received MMS message has no parts");
        }
 
        MessagePart textPart = null;
        MessagePart imagePart = null;
 
        for (int i = 0; i < parts.length; i++) 
        {
            final MessagePart part = parts[i];
            if (part == null) 
            {
                continue; // should never happen, but just to be safe
            }
            final String mimeType = part.getMIMEType();
            if (mimeType == null) {
                continue; // should never happen, but just to be safe
            }
 
            if (mimeType.equals("text/plain")) 
            {
                textPart = part;
            } 
            else if (mimeType.startsWith("image/")) 
           {
               imagePart = part;
           }
        }
 
        if (textPart == null && imagePart == null) 
        {
           throw new IOException("no text or image parts found in received MMS message");
        } 
        else if (textPart == null) 
        {
            throw new IOException("no text parts found in received MMS message");
        } 
        else if (imagePart == null) 
        {
            throw new IOException("no image parts found in received MMS message");
        }
 
        return new MessagePart[] { textPart, imagePart };
       } 
       finally 
       {
           connection.close();
    }
}

Configuring listeners for outgoing and sent messages

In addition to providing notification to applications when messages are received (using the MessageListener interface), you can also configure application notification for outgoing and sent SMS messages and MMS messages. For SMS messages, you can configure your application to track sent SMS messages by passing an instance of a class that implements the OutboundMessageListener interface when invoking MessageConnection.setMessageListener(). Notification using this interface occurs only after the message is sent successfully. If the send operation fails, the application is not notified.

For example:

...
public void run()
{
    try 
    {
         //closed by the stop() method
         _mc = (MessageConnection)Connector.open("sms://:0");
               
         if (_mc != null)
         {
              _mc.setMessageListener(new OutboundSMSListener());
         }
    }
    catch
    {
        ...
    }
}

To notify your application about SMS messages before they are sent, pass an instance of a class that implements the SendListener interface when invoking addSendListener(SendListener listener). You can also use this interface to modify the contents of the SMS message before sending and to prevent messages from being sent if SendListener.sendMessage(Message message) returns false.

Click for code sample: Configure an SMS SendListener

import javax.wireless.messaging.Message;
import javax.wireless.messaging.TextMessage;
import net.rim.device.api.system.Application;
import net.rim.blackberry.api.sms.SMS;
import net.rim.blackberry.api.sms.SendListener;

public class SMSSendListenerDemo extends Application 
{

    public static void main(String[] args) 
    {
        final SMSSendListenerDemo app = new SMSSendListenerDemo();
        app.invokeLater(new SetupRunnable());
        app.enterEventDispatcher();
    }

    private static class MySMSSendListener implements SendListener 
    {
        public boolean sendMessage(Message message) 
        {
            if (message instanceof TextMessage) 
            {
                String address = ((TextMessage) message).getAddress();
                if (address != null && address.endsWith("5551212")) 
                {
                    // do not allow SMS to be sent to 5551212
                    return false;
                }
            }
            return true;
        }
    }

    private static class SetupRunnable implements Runnable 
    {
        public void run() 
        {
            SendListener listener = new MySMSSendListener();
            SMS.addSendListener(listener);
        }
    }
}

Note: When an SMS message is marked for sending, the message in the message list is marked with PENDING status. The SendListener is notified at this time. If SendListener does not send the message, the SMS message in the message list is marked with a red X, and your application is notified with the failure reason.

To set up notification for MMS messages before they are sent, pass an instance of a class that implements the SendListener interface when invoking addSendListener(SendListener listener). You can also prevent messages from being sent if SendListener.sendMessage(Message message) returns false. Unlike SMS messages, you cannot use this interface to modify the contents of an MMS message before it is sent.

Click for code sample: Configure an MMS SendListener

import javax.wireless.messaging.Message;
import javax.wireless.messaging.MultipartMessage;
import net.rim.device.api.system.Application;
import net.rim.blackberry.api.mms.MMS;
import net.rim.blackberry.api.mms.SendListener;

public class MMSSendListenerDemo extends Application 
{

    public static void main(String[] args) 
    {
        final MMSSendListenerDemo app = new MMSSendListenerDemo();
        app.invokeLater(new SetupRunnable());
        app.enterEventDispatcher();
    }

    private static class MyMMSSendListener implements SendListener 
    {
        public boolean sendMessage(Message message) 
        {
            if (message instanceof MultipartMessage) 
            {
                MultipartMessage mmsMessage = ((MultipartMessage) message);
                String[] addresses = mmsMessage.getAddresses("to");
                int addressesLength = (addresses == null) ? 0 : addresses.length;
                for (int i = 0; i < addressesLength; i++) 
                {
                    final String address = addresses[i];
                    if (address != null && address.endsWith("5551212")) 
                    {
                        // do not allow MMS to be sent to 5551212
                        return false;
                    }
                }
            }
            return true;
        }
    }

    private static class SetupRunnable implements Runnable 
    {
        public void run() 
        {
            final SendListener listener = new MyMMSSendListener();
            MMS.addSendListener(listener);
        }
    }
}

Copyright 1999-2010 Research In Motion Limited. 295 Phillip Street, Waterloo, Ontario, Canada, N2L 3W8. All Rights Reserved.
Copyright 1993-2003 Sun Microsystems, Inc. 901 San Antonio Road, Palo Alto, California, 94303, U.S.A.
Copyright 2002-2003 Nokia Corporation All Rights Reserved.
Java is a trademark or registered trademark of Sun Microsystems, Inc. in the US and other countries.