首页 > 解决方案 > 如何在 java 中使用 MessageFormat 格式化邮件内容

问题描述

我有一个要在 java 中发送的自动邮件内容。我想使用 MessageFormat 在 java 中对其进行格式化。

这是包含三个要自定义的参数的邮件内容。

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.

这些参数将在一个数组中检索并插入到邮件的内容中

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);

我想将消息显示为邮件内容以及如何传递我的三个字符串变量而不是 {0}、{1} 和 {2}。我怎样才能在 java 中做到这一点?

标签: javamessageformat

解决方案


你可以做:

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

注意- 单引号'应通过加倍单引号进行转义:''.

未转义的报价:

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);

输出错误:

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

不是我们想要的...

要修复它,我们应该转义引号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);

正确的输出:

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

推荐阅读