Dart Requires Chilkat v11.0.0+
Dart
Find an email by subject and fetch it by IMAP UID
See more Email Object Examples
Search the selected INBOX by subject and fetch the first matching UID into an Email. The example requests complete attachment bodies and uses peek mode to preserve the read flag. Configure your own IMAP TLS endpoint and credentials.
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('MAIL_USER', 'MAIL_PASSWORD');
} on ChilkatException catch (e) {
print(e.lastErrorText);
return;
}
try {
imap.selectMailbox('INBOX');
} on ChilkatException catch (e) {
print(e.lastErrorText);
return;
}
final matches = CkMessageSet();
try {
imap.queryMbx('SUBJECT "Sample message"', true, matches);
} on ChilkatException catch (e) {
print(e.lastErrorText);
return;
}
if (matches.count == 0) {
print('No matching message in INBOX.');
try {
imap.disconnect();
} on ChilkatException catch (e) {
print(e.lastErrorText);
return;
}
return;
}
// The search returned UIDs. Use the same identifier type for the fetch.
final uid = matches.getId(0);
final email = CkEmail();
try {
imap.fetchEmail(false, uid, true, email);
} on ChilkatException catch (e) {
print(e.lastErrorText);
return;
}
print('Mailbox INBOX, UIDVALIDITY ${imap.uidValidity}, UID $uid');
try {
imap.disconnect();
} on ChilkatException catch (e) {
print(e.lastErrorText);
return;
}
// The downloaded Email remains usable after disconnecting.
print('Subject: ${email.subject} Files: ${email.numAttachments}');
try {
email.saveEml('imap-received.eml');
} on ChilkatException catch (e) {
print(e.lastErrorText);
return;
}
print('Saved imap-received.eml.');
}