sendEmail method

  1. @override
Future<bool> sendEmail({
  1. required String domain,
  2. required String from,
  3. required List<String> recipients,
  4. required String body,
  5. bool useTls = true,
})
override

Sends an email from from to recipients at the given domain.

body is the full email content including headers. If useTls is true, attempts to use STARTTLS when supported. Returns true if the email was accepted by the remote server.

Implementation

@override
Future<bool> sendEmail({
  required String domain,
  required String from,
  required List<String> recipients,
  required String body,
  bool useTls = true,
}) async {
  // No recipients to deliver to (nothing to send):
  if (recipients.isEmpty) {
    return false;
  }

  try {
    // Resolve MX records
    var mxRecords = await dnsResolver.resolveMX(domain);
    if (mxRecords.isEmpty) {
      _log.severe(
        "No MX record for `$domain`! Can't deliver e-mail> from: $from ; to: $recipients",
      );
      return false;
    }

    var mxServer = selectMXServerAddress(mxRecords);

    Socket socket = await connectToMXServer(mxServer);

    final handler = _SocketHandler(
      hostname: hostname,
      socket: socket,
      from: from,
      recipients: recipients,
      body: body,
      useTls: useTls,
    );

    return handler.result;
  } catch (e, s) {
    _log.severe(
      "Error sending e-mail from `$from` to `${recipients.join(', ')}`",
      e,
      s,
    );
    return false;
  }
}