1
0
Fork 0
mrtiboute/lib/utils/mailer.dart

53 lines
2.3 KiB
Dart

import 'package:desktopapp/utils/logger.dart';
import 'package:desktopapp/utils/requests.dart';
import 'package:enough_mail/enough_mail.dart';
class Mailer {
/// High level mail API example
static Future<void> mailExample() async {
const email = 'trexricher1997@gmail.com';
const password = 'rugnxbafhcwsykzt';
Logger.log(LoggerType.info, Mailer, 'Discovering settings for $email');
final config = await Discover.discover(email);
if (config == null) {
Logger.log(LoggerType.info, Mailer,
'Unable to autodiscover settings for $email');
return;
}
Logger.log(LoggerType.info, Mailer, 'Settings for $email : $config');
final account = MailAccount.fromDiscoveredSettings(
'my account', email, password, config);
final mailClient = MailClient(account, isLogEnabled: true);
try {
await mailClient.connect();
Logger.log(LoggerType.info, Mailer, 'Connected to $email');
await mailClient.selectInbox();
mailClient.eventBus.on<ImapEvent>().listen((ImapEvent event) async {
if (event.eventType == ImapEventType.exists) {
final evt = event as ImapMessagesExistEvent;
if (evt.newMessagesExists <= evt.oldMessagesExists) return;
final sequence = MessageSequence();
if (evt.newMessagesExists - evt.oldMessagesExists > 1) {
sequence.addRange(evt.oldMessagesExists, evt.newMessagesExists);
} else {
sequence.add(evt.newMessagesExists);
}
final messages = await mailClient.fetchMessageSequence(sequence,
fetchPreference: FetchPreference.full);
for (final message in messages) {
var mailEvt = MailLoadEvent(message, mailClient);
var content = mailEvt.message.decodeSubject();
var mess = mailEvt.message.decodeTextPlainPart();
Logger.log(LoggerType.info, Mailer, 'New message $content : $mess');
Requests.sendAlert('*$content* $mess');
}
}
});
Logger.log(LoggerType.info, Mailer, 'Start polling mail for $email');
await mailClient.startPolling(const Duration(seconds: 30));
Logger.log(LoggerType.info, Mailer, 'Finish polling mail for $email');
} on MailException catch (e) {
Logger.log(LoggerType.error, Mailer, 'High level API failed with $e');
}
}
}