0
# Core Messaging
1
2
This document covers the foundational messaging components of the Jakarta Mail API: Session management, Message handling, Transport operations, and Store connectivity.
3
4
## Session Management
5
6
The Session class is the main entry point for the Jakarta Mail API, managing configuration properties and providing access to protocol providers.
7
8
### Session Creation
9
10
```java { .api }
11
class Session {
12
static Session getInstance(Properties props);
13
static Session getInstance(Properties props, Authenticator authenticator);
14
static Session getDefaultInstance(Properties props);
15
static Session getDefaultInstance(Properties props, Authenticator authenticator);
16
}
17
```
18
19
**Parameters:**
20
- `props` (Properties): Configuration properties for mail protocols
21
- `authenticator` (Authenticator): Authentication callback for credentials
22
23
### Session Configuration
24
25
```java { .api }
26
class Session {
27
Properties getProperties();
28
String getProperty(String name);
29
void setProvider(Provider provider) throws NoSuchProviderException;
30
Provider getProvider(String protocol) throws NoSuchProviderException;
31
Provider[] getProviders();
32
}
33
```
34
35
### Session Services
36
37
```java { .api }
38
class Session {
39
Store getStore() throws NoSuchProviderException;
40
Store getStore(String protocol) throws NoSuchProviderException;
41
Store getStore(URLName url) throws NoSuchProviderException;
42
Transport getTransport() throws NoSuchProviderException;
43
Transport getTransport(String protocol) throws NoSuchProviderException;
44
Transport getTransport(Address address) throws NoSuchProviderException;
45
Folder getFolder(URLName url) throws MessagingException;
46
}
47
```
48
49
**Common Protocols:**
50
- `"smtp"` - Simple Mail Transfer Protocol
51
- `"imap"` - Internet Message Access Protocol
52
- `"pop3"` - Post Office Protocol version 3
53
54
### Authentication and Security
55
56
```java { .api }
57
class Session {
58
void setPasswordAuthentication(URLName url, PasswordAuthentication pw);
59
PasswordAuthentication getPasswordAuthentication(URLName url);
60
PasswordAuthentication requestPasswordAuthentication(
61
InetAddress addr, int port, String protocol,
62
String prompt, String defaultUserName);
63
}
64
```
65
66
### Debug Support
67
68
```java { .api }
69
class Session {
70
void setDebug(boolean debug);
71
boolean getDebug();
72
void setDebugOut(PrintStream out);
73
PrintStream getDebugOut();
74
}
75
```
76
77
### Usage Example
78
79
```java
80
Properties props = new Properties();
81
props.put("mail.smtp.host", "smtp.gmail.com");
82
props.put("mail.smtp.port", "587");
83
props.put("mail.smtp.auth", "true");
84
props.put("mail.smtp.starttls.enable", "true");
85
86
Session session = Session.getInstance(props, new Authenticator() {
87
protected PasswordAuthentication getPasswordAuthentication() {
88
return new PasswordAuthentication("user@example.com", "password");
89
}
90
});
91
```
92
93
## Message Handling
94
95
The Message class represents email messages with support for headers, content, recipients, and flags.
96
97
### Message Creation
98
99
```java { .api }
100
abstract class Message implements Part {
101
Message(Session session);
102
Session getSession();
103
}
104
```
105
106
### Address Management
107
108
```java { .api }
109
abstract class Message {
110
abstract Address[] getFrom() throws MessagingException;
111
abstract void setFrom() throws MessagingException;
112
abstract void setFrom(Address address) throws MessagingException;
113
abstract void addFrom(Address[] addresses) throws MessagingException;
114
115
abstract Address[] getRecipients(RecipientType type) throws MessagingException;
116
Address[] getAllRecipients() throws MessagingException;
117
abstract void setRecipients(RecipientType type, Address[] addresses) throws MessagingException;
118
abstract void addRecipients(RecipientType type, Address[] addresses) throws MessagingException;
119
120
Address[] getReplyTo() throws MessagingException;
121
void setReplyTo(Address[] addresses) throws MessagingException;
122
}
123
```
124
125
### Recipient Types
126
127
```java { .api }
128
static class Message.RecipientType {
129
static final RecipientType TO;
130
static final RecipientType CC;
131
static final RecipientType BCC;
132
}
133
```
134
135
### Message Properties
136
137
```java { .api }
138
abstract class Message {
139
abstract String getSubject() throws MessagingException;
140
abstract void setSubject(String subject) throws MessagingException;
141
142
abstract Date getSentDate() throws MessagingException;
143
abstract void setSentDate(Date date) throws MessagingException;
144
abstract Date getReceivedDate() throws MessagingException;
145
146
int getMessageNumber();
147
boolean isExpunged();
148
149
abstract Flags getFlags() throws MessagingException;
150
abstract void setFlags(Flags flag, boolean set) throws MessagingException;
151
boolean isSet(Flags.Flag flag) throws MessagingException;
152
}
153
```
154
155
### Message Operations
156
157
```java { .api }
158
abstract class Message {
159
abstract Message reply(boolean replyToAll) throws MessagingException;
160
abstract void saveChanges() throws MessagingException;
161
162
void setFlag(Flags.Flag flag, boolean set) throws MessagingException;
163
boolean match(SearchTerm term) throws MessagingException;
164
}
165
```
166
167
### Usage Example
168
169
```java
170
Message message = new MimeMessage(session);
171
message.setFrom(new InternetAddress("sender@example.com"));
172
message.setRecipients(Message.RecipientType.TO,
173
InternetAddress.parse("recipient@example.com"));
174
message.setRecipients(Message.RecipientType.CC,
175
InternetAddress.parse("cc@example.com"));
176
message.setSubject("Meeting Reminder");
177
message.setSentDate(new Date());
178
message.setText("Don't forget our meeting at 3 PM today.");
179
```
180
181
## Transport Operations
182
183
The Transport class handles message delivery through various protocols, primarily SMTP.
184
185
### Static Send Methods
186
187
```java { .api }
188
abstract class Transport extends Service {
189
static void send(Message msg) throws MessagingException;
190
static void send(Message msg, Address[] addresses) throws MessagingException;
191
static void send(Message msg, String user, String password) throws MessagingException;
192
}
193
```
194
195
**Parameters:**
196
- `msg` (Message): The message to send
197
- `addresses` (Address[]): Specific recipient addresses (overrides message recipients)
198
- `user` (String): Username for authentication
199
- `password` (String): Password for authentication
200
201
### Instance Methods
202
203
```java { .api }
204
abstract class Transport extends Service {
205
abstract void sendMessage(Message msg, Address[] addresses) throws MessagingException;
206
207
void addTransportListener(TransportListener l);
208
void removeTransportListener(TransportListener l);
209
210
void addConnectionListener(ConnectionListener l);
211
void removeConnectionListener(ConnectionListener l);
212
}
213
```
214
215
### Usage Examples
216
217
```java
218
// Simple send using session configuration
219
Transport.send(message);
220
221
// Send with explicit authentication
222
Transport.send(message, "username", "password");
223
224
// Send to specific addresses (bypassing message recipients)
225
Address[] recipients = {new InternetAddress("override@example.com")};
226
Transport.send(message, recipients);
227
228
// Instance-based sending with connection management
229
Transport transport = session.getTransport("smtp");
230
transport.connect("smtp.example.com", "username", "password");
231
transport.sendMessage(message, message.getAllRecipients());
232
transport.close();
233
```
234
235
## Store Operations
236
237
The Store class provides access to message storage systems like IMAP and POP3 servers.
238
239
### Store Connection
240
241
```java { .api }
242
abstract class Store extends Service {
243
abstract Folder getDefaultFolder() throws MessagingException;
244
abstract Folder getFolder(String name) throws MessagingException;
245
abstract Folder getFolder(URLName url) throws MessagingException;
246
247
Folder[] getPersonalNamespaces() throws MessagingException;
248
Folder[] getUserNamespaces(String user) throws MessagingException;
249
Folder[] getSharedNamespaces() throws MessagingException;
250
}
251
```
252
253
### Store Events
254
255
```java { .api }
256
abstract class Store extends Service {
257
void addStoreListener(StoreListener l);
258
void removeStoreListener(StoreListener l);
259
void addFolderListener(FolderListener l);
260
void removeFolderListener(FolderListener l);
261
}
262
```
263
264
### Usage Example
265
266
```java
267
Store store = session.getStore("imap");
268
store.connect("imap.example.com", "username", "password");
269
270
// Get default folder (usually root)
271
Folder defaultFolder = store.getDefaultFolder();
272
273
// Get specific folders
274
Folder inbox = store.getFolder("INBOX");
275
Folder sent = store.getFolder("Sent");
276
277
// Check folder existence
278
if (inbox.exists()) {
279
inbox.open(Folder.READ_WRITE);
280
// Work with folder
281
inbox.close();
282
}
283
284
store.close();
285
```
286
287
## Service Base Class
288
289
Both Transport and Store extend the Service class, providing common connectivity operations.
290
291
```java { .api }
292
abstract class Service implements AutoCloseable {
293
abstract void connect() throws MessagingException;
294
abstract void connect(String host, String user, String password) throws MessagingException;
295
abstract void connect(String user, String password) throws MessagingException;
296
abstract void connect(String host, int port, String user, String password) throws MessagingException;
297
298
abstract boolean isConnected();
299
abstract void close() throws MessagingException;
300
301
URLName getURLName();
302
Session getSession();
303
304
void addConnectionListener(ConnectionListener l);
305
void removeConnectionListener(ConnectionListener l);
306
}
307
```
308
309
## Provider System
310
311
The Provider class describes protocol implementations available to the Session.
312
313
```java { .api }
314
class Provider {
315
Provider(Type type, String protocol, String className, String vendor, String version);
316
317
Type getType();
318
String getProtocol();
319
String getClassName();
320
String getVendor();
321
String getVersion();
322
323
static class Type {
324
static final Type STORE;
325
static final Type TRANSPORT;
326
}
327
}
328
```
329
330
## Core Types
331
332
```java { .api }
333
abstract class Address implements Serializable {
334
abstract String getType();
335
abstract String toString();
336
abstract boolean equals(Object address);
337
}
338
339
class URLName {
340
URLName(String protocol, String host, int port, String file, String username, String password);
341
URLName(URL url);
342
URLName(String url);
343
344
String getProtocol();
345
String getHost();
346
int getPort();
347
String getFile();
348
String getUsername();
349
String getPassword();
350
URL getURL() throws MalformedURLException;
351
}
352
353
abstract class Authenticator {
354
protected PasswordAuthentication getPasswordAuthentication();
355
356
public String getDefaultUserName();
357
public InetAddress getRequestingSite();
358
public int getRequestingPort();
359
public String getRequestingProtocol();
360
public String getRequestingPrompt();
361
}
362
363
class PasswordAuthentication {
364
PasswordAuthentication(String userName, String password);
365
String getUserName();
366
String getPassword();
367
}
368
```
369
370
## Exception Handling
371
372
```java { .api }
373
class MessagingException extends Exception {
374
MessagingException();
375
MessagingException(String s);
376
MessagingException(String s, Exception e);
377
378
Exception getNextException();
379
boolean setNextException(Exception ex);
380
}
381
382
class NoSuchProviderException extends MessagingException {
383
NoSuchProviderException();
384
NoSuchProviderException(String s);
385
}
386
387
class AuthenticationFailedException extends MessagingException {
388
AuthenticationFailedException();
389
AuthenticationFailedException(String s);
390
}
391
392
class SendFailedException extends MessagingException {
393
SendFailedException();
394
SendFailedException(String s);
395
396
Address[] getValidSentAddresses();
397
Address[] getValidUnsentAddresses();
398
Address[] getInvalidAddresses();
399
}
400
```
401
402
### Error Handling Example
403
404
```java
405
try {
406
Transport.send(message);
407
} catch (SendFailedException ex) {
408
System.err.println("Send failed: " + ex.getMessage());
409
Address[] invalid = ex.getInvalidAddresses();
410
Address[] validUnsent = ex.getValidUnsentAddresses();
411
Address[] validSent = ex.getValidSentAddresses();
412
413
// Handle partial failure cases
414
if (validSent != null) {
415
System.out.println("Successfully sent to: " + Arrays.toString(validSent));
416
}
417
} catch (MessagingException ex) {
418
System.err.println("Messaging error: " + ex.getMessage());
419
}
420
```