MessageRecipients messageRecipients,
MessageRecipient messageSender)
throws RecipientException, MessageException {
// Maintain a record of recipients for who the message send failed
MessageRecipients failures = new MessageRecipients();
// Maintain references to multiple recipients so a failure can be
// recorded against multiple recipients where to/cc/bcc are combined
// and can each contain multiple values.
List multipleRecipients = new ArrayList();
MimeMessage message;
try {
message = new MimeMessage(session);
if (multiChannelMessage.getCharacterEncoding() != null) {
message.setSubject(
multiChannelMessage.getSubject(),
multiChannelMessage.getCharacterEncoding());
} else {
message.setSubject( multiChannelMessage.getSubject() );
}
if (messageSender != null) {
message.setFrom( messageSender.getAddress() );
}
} catch (Exception e) {
// Failure to create the message hence no failure logged here
throw new MessageException(e);
}
Iterator recipientsIterator = messageRecipients.getIterator();
MessageRecipient recipient = null;
while (recipientsIterator.hasNext()) {
recipient = (MessageRecipient) recipientsIterator.next();
int recipientType = RecipientInternals.getRecipientType(recipient);
try {
switch (recipientType) {
case RecipientInternals.TO_RECIPIENT:
{
message.addRecipient(Message.RecipientType.TO,
recipient.getAddress());
multipleRecipients.add(recipient);
break;
}
case RecipientInternals.CC_RECIPIENT:
{
message.addRecipient(Message.RecipientType.CC,
recipient.getAddress());
multipleRecipients.add(recipient);
break;
}
case RecipientInternals.BCC_RECIPIENT:
{
message.addRecipient(Message.RecipientType.BCC,
recipient.getAddress());
multipleRecipients.add(recipient);
break;
}
}
} catch (MessagingException me) {
// This exception can come from addRecipient so the
// recipient needs to be added to the failures here
// and it will not already have been added to the
// multipleRecipients list so no need to remove it.
logger.warn("message-recipient-addition-failed-for",
recipient.getAddress(), me);
recipient.setFailureReason(me.getMessage());
failures.addRecipient(recipient);
}
}
// obtain device name for message header generation
// from last recipient added
String currentDeviceName = recipient.getDeviceName();
// Try and send the messsage
try {
message = (MimeMessage) addHeaders(multiChannelMessage,
message,
currentDeviceName);
MimeMultipart content =
multiChannelMessage.generateTargetMessageAsMimeMultipart(
currentDeviceName);
message.setContent(content, content.getContentType());
Transport.send(message);
} catch (MessagingException me) {
for (Iterator i = multipleRecipients.iterator(); i.hasNext();) {
MessageRecipient failedRecipient = (MessageRecipient) i.next();
logger.warn("message-send-failed-to",
failedRecipient.getAddress());
logger.error(me);
failedRecipient.setFailureReason(me.getMessage());
failures.addRecipient( failedRecipient );
}
}
// Return any failures
return failures;