Search code examples
javamessageformat

How can i format the content of the mail by using MessageFormat in java


I have an automatic mail content that I want to send in java. I want to format it in java using MessageFormat.

Here is the content of the mail containing three parameters to customize.

Bonjour,

Nous vous confirmons la reception du {0}$ correspondant à l'achat de votre
{1} correspondant au forunisseur {3}

Si cela vous convient, nous vous enverrons la facture detaille avec toute les justificatifs
et le detail des commandes

Nous restons à votre entière disposition pour toute informations complementaires

A très bientôt.

Ceci est un message automatique , merci de ne pas repondre à ce mail.

These parameters will be retrieved in an array and will be inserted in the content of the mail

String[] data = new String[] {"15","p1","Tera"};
String montant = data[0];
String produit = data[1];
String fournisseur = data[2];
String message = "Bonjour, ..."; //The content of the mail above
MessageFormat mf = new MessageFormat(message);
System.out.println(mf);

I want to display the message as in the content of the mail and how to pass my three string variables instead of {0}, {1} and {2}. How can I do this in java ?


Solution

  • You can do:

    String message = "Bonjour, ..."
    MessageFormat mf = new MessageFormat(message); 
    String formattedStr = mf.format(new Object[]{"15", "p1", "Tera"});
    

    Note - single quote ' should be escaped by doubling the single quote: ''.

    Unescaped quote:

    String msg = "Bonjour,\n" +
            "{0}$ correspondant à l'achat de votre {1} correspondant au forunisseur {2}\n";
    MessageFormat mf = new MessageFormat(msg);
    String formattedStr = mf.format(new Object[]{"15", "p1", "Tera"});
    System.out.println(formattedStr);
    

    Incorrect output:

    Bonjour,
    15$ correspondant à lachat de votre {1} correspondant au forunisseur {2}
    

    Not what we wanted...

    To fix it, we should escape the quote l'achat --> l''achat:

    String msg = "Bonjour,\n" +
            "{0}$ correspondant à l''achat de votre {1} correspondant au forunisseur {2}\n";
    MessageFormat mf = new MessageFormat(msg);
    String formattedStr = mf.format(new Object[]{"15", "p1", "Tera"});
    System.out.println(formattedStr);
    

    Correct output:

    Bonjour,
    15$ correspondant à l'achat de votre p1 correspondant au forunisseur Tera