Printing variable values in Java
Question
I've got an object which is a new MimeMessage called message and I want to find out what it's passing to my outgoing mail server. I however have no idea how one gets a variable like this printed out in Java. Here's some code:
private String sendConfirmationEmail (String to, String from, String subject, String body, boolean CCSender) {
try
{
// String smtpHost = Properties.smtp;
String smtpHost = Properties.smtp;
String fromAddress = from;
String toAddress = to;
Properties properties = System.getProperties();
properties.put("mail.smtp.host", smtpHost);
Session session = Session.getInstance(properties, null);
MimeMessage message = new MimeMessage(session);
message.setFrom(new InternetAddress(fromAddress));
message.setRecipient(Message.RecipientType.TO,
new InternetAddress(toAddress));
if (CCSender) {
message.setRecipient(Message.RecipientType.CC,
new InternetAddress(from));
}
message.setSubject(subject);
message.setText(body);
System.out.println(message); <=== I want this to work!
message.saveChanges();
Transport.send(message);
return "1:success";
}
catch(Exception e)
{
return "0:failure "+e.toString();
}
}
Any help would be much appreciated.
Thanks.
Solution
For MimeMessage
, you can call message.writeTo(System.out);
. You will probably want to do this after calling message.saveChanges()
to ensure consistency.
OTHER TIPS
If it's a class you have control of, you override it's toString() method
If you have no control over it, you'll have to write a method like
String valueOf(Message message) {
StringBuilder sb = new StringBuilder();
sb.append(message.someValue());
sb.append(message.someOtherValue());
return sb.toString();
}
and use valueOf in your debug message
For MimeMessage, I'd rely on it having a toString implementation for its content
String valueOf(Message message) {
return message.getContent().toString();
}
You could create a decorator class implementing the base interface, and logging/printing everything returned by the wrapped class' toString()
(or whatever other methods the base interface has).