fillTemplate static method
Fills the given template
with values extracted from the provided message
.
Optionally extends the template fields by defining them in the parameters
field.
Currently the following templates are supported:
<from>
: specifies the message sender (name plus email)
<date>
: specifies the message date
<to>
: the to
recipients
<cc>
: the cc
recipients
<subject>
: the subject of the message
Note that for date formatting Dart's intl library is used: https://pub.dev/packages/intl
You might want to specify the default locale by setting Intl.defaultLocale
first.
Implementation
static String fillTemplate(
String template,
MimeMessage message, {
Map<String, String>? parameters,
}) {
final definedVariables = <String>[];
var from = message.decodeHeaderMailAddressValue('sender');
if (from?.isEmpty ?? true) {
from = message.decodeHeaderMailAddressValue('from');
}
if (from?.isNotEmpty ?? false) {
definedVariables.add('from');
template = template.replaceAll('<from>', from!.first.toString());
}
final date = message.decodeHeaderDateValue('date');
if (date != null) {
definedVariables.add('date');
final dateStr = DateFormat.yMd().add_jm().format(date);
template = template.replaceAll('<date>', dateStr);
}
final to = message.to;
if (to?.isNotEmpty ?? false) {
definedVariables.add('to');
template = template.replaceAll('<to>', _renderAddresses(to!));
}
final cc = message.cc;
if (cc?.isNotEmpty ?? false) {
definedVariables.add('cc');
template = template.replaceAll('<cc>', _renderAddresses(cc!));
}
final subject = message.decodeSubject();
if (subject != null) {
definedVariables.add('subject');
template = template.replaceAll('<subject>', subject);
}
if (parameters != null) {
for (final key in parameters.keys) {
definedVariables.add(key);
template = template.replaceAll('<$key>', parameters[key]!);
}
}
// remove any undefined variables from template:
final optionalInclusionsExpression = RegExp(r'\[\[\w+\s[\s\S]+?\]\]');
RegExpMatch? match;
while (
(match = optionalInclusionsExpression.firstMatch(template)) != null) {
final sequence = match!.group(0)!;
//print('sequence=$sequence');
final separatorIndex = sequence.indexOf(' ', 2);
final name = sequence.substring(2, separatorIndex);
var replacement = '';
if (definedVariables.contains(name)) {
replacement =
sequence.substring(separatorIndex + 1, sequence.length - 2);
}
template = template.replaceAll(sequence, replacement);
}
return template;
}