Use the send method of the Transport class to send the message.
try {
Transport.send(msg);
} catch (MessagingException e) {
// When failure occurs in sending the message
} |
Furthermore, when you want to send more than one message, you can send them with one connection by creating the Transport object.
// Acquire Transport class object
Transport transport = null;
try {
transport = session.getTransport("smtp");
} catch (NoSuchProviderException e) {
// When provider is not found
// Does not occur because the SMTP provider is set up by default settings
}
try {
// Connecting to the SMTP server
transport.connect();
// Update the header before sending
msg.saveChanges();
// Send message
transport.sendMessage(msg, msg.getAllRecipients());
// Repeated invocation of sendMessage() method when sending multiple messages.
// transport.sendMessage(msg2, msg2.getAllRecipients());
// ...
} catch (MessagingException e) {
// When connecting to the SMTP server or when an attempt to send message fails
} finally {
try{
// Disconnection from the SMTP server
transport.close();
}catch(MessagingException e){
// When fails to disconnect server
}
} |