Send a message

  1. Import the required classes and interfaces.
    import net.rim.blackberry.api.mail.Address;
    import net.rim.blackberry.api.mail.AddressException;
    import net.rim.blackberry.api.mail.Folder;
    import net.rim.blackberry.api.mail.Message;
    import net.rim.blackberry.api.mail.MessagingException;
    import net.rim.blackberry.api.mail.Session;
    import net.rim.blackberry.api.mail.Store;
    import net.rim.blackberry.api.mail.Transport;
    
  2. Declare a Message object.
    Message msg;
  3. Specify a folder in which to save a copy of the sent message.
    Store store = Session.getDefaultInstance().getStore();
    Folder[] folders = store.list(Folder.SENT);
    Folder sentfolder = folders[0];
    msg = new Message(sentfolder);
  4. Create an array of Address objects.
    Address toList[] = new Address[1];
  5. In a try block, add each address to the array.
    try 
    {
       toList[0]= new Address("ming.li@example.com", "Ming Li");
    }
  6. In a catch block, manage a AddressException, which is thrown if an address is invalid.
    catch(AddressException e) 
    {
       System.out.println(e.toString());
    }
  7. Invoke Message.addRecipients() and provide the type of recipient (TO, CC, or BCC) and the array of addresses to add as parameters to the method.
  8. If the message has multiple types of recipients, invoke Message.addRecipients() once for each recipient type.
    msg.addRecipients(Message.RecipientType.TO, toList);
  9. Invoke Message.setFrom(Address).
    Address from = new Address("ming.li@example.com", "Ming Li");
    msg.setFrom(from);
  10. Invoke Message.setSubject(String).
    msg.setSubject("Test Message");
  11. Invoke Message.setContent(String). (Typically, the BlackBerry® device application retrieves content from text that a BlackBerry device user types in a field.)
    try 
    {
       msg.setContent("This is a test message.");
    } 
    catch(MessagingException e) 
    {
       System.out.println(e.getMessage());
    }
  12. Invoke Session.getTransport() and store the returned object in a variable of type Transport. The Transport object represents the messaging transport protocol.
    Transport trans = Session.getTransport();
  13. Invoke Transport.send(Message) to send the message.
    try 
    {
       trans.send(msg);
    } 
    catch(MessagingException e) 
    {
       System.out.println(e.getMessage());
    }

Was this information helpful? Send us your comments.