Dart Requires Chilkat v11.0.0+
Dart
Extract signed invoice XML from an Italian PEC message
See more Email Object Examples
Search the PEC folder by subject, fetch one envelope by UID, and inspect the attachments of each nested email. Match .xml.p7m by filename and verify the opaque CMS signature before loading the XML. This checks signature integrity. Certificate trust and invoice schema validation are separate application decisions.
Chilkat Dart Downloads
import 'package:chilkat/chilkat.dart';
void main() {
// Assumes Chilkat is unlocked. See Global Unlock Sample.
final imap = CkImap();
imap.ssl = true;
imap.port = 993;
imap.requireSslCertVerify = true;
imap.peekMode = true;
imap.autoDownloadAttachments = true;
try {
imap.connect('imap.example.com');
} on ChilkatException catch (e) {
print(e.lastErrorText);
return;
}
try {
imap.login('IMAP_USERNAME', 'IMAP_PASSWORD');
} on ChilkatException catch (e) {
print(e.lastErrorText);
return;
}
try {
imap.selectMailbox('INBOX/postacert');
} on ChilkatException catch (e) {
print(e.lastErrorText);
return;
}
final messages = CkMessageSet();
try {
imap.queryMbx('SUBJECT "POSTA CERTIFICATA: Invio File"', true, messages);
} on ChilkatException catch (e) {
print(e.lastErrorText);
return;
}
if (messages.count == 0) {
print('No matching PEC envelope.');
imap.disconnect();
return;
}
final envelope = CkEmail();
try {
imap.fetchEmail(false, messages.getId(0), true, envelope);
} on ChilkatException catch (e) {
print(e.lastErrorText);
return;
}
imap.disconnect();
final nested = CkEmail();
final name = CkStringBuilder();
var verified = 0;
var i = 0;
while (i < envelope.numAttachedMessages) {
try {
envelope.getAttachedEmail(i, nested);
} on ChilkatException catch (e) {
print(e.lastErrorText);
return;
}
var j = 0;
while (j < nested.numAttachments) {
name.setString(nested.getAttachmentFilename(j));
if (name.endsWith('.xml.p7m', false)) {
final data = CkBinData();
try {
nested.getAttachmentBd(j, data);
} on ChilkatException catch (e) {
print(e.lastErrorText);
return;
}
final cms = CkCrypt2();
try {
cms.opaqueVerifyBd(data);
} on ChilkatException catch (e) {
print(e.lastErrorText);
return;
}
final invoice = CkXml();
try {
invoice.loadBd(data, true);
} on ChilkatException catch (e) {
print(e.lastErrorText);
return;
}
print('${name.getAsString()} XML root: ${invoice.tag}');
verified++;
}
j++;
}
i++;
}
print('Verified XML invoices: $verified');
}