prepareMailtoBasedMessage method Null safety

MessageBuilder prepareMailtoBasedMessage(
  1. Uri mailto,
  2. MailAddress from
)

Convenience method for creating a message based on a mailto URI from the sender specified in from.

The following fields are supported:

  • mailto to recpient address(es)
  • cc - CC recipient address(es)
  • subject - the subject header field
  • body - the body header field
  • in-reply-to - message ID to which the new message is a reply

Implementation

static MessageBuilder prepareMailtoBasedMessage(
    Uri mailto, MailAddress from) {
  final builder = MessageBuilder()
    ..from = [from]
    ..setContentType(MediaType.textPlain, characterSet: CharacterSet.utf8)
    ..transferEncoding = TransferEncoding.automatic;
  final to = <MailAddress>[];
  for (final value in mailto.pathSegments) {
    to.addAll(value.split(',').map((email) => MailAddress(null, email)));
  }
  final queryParameters = mailto.queryParameters;
  for (final key in queryParameters.keys) {
    final value = queryParameters[key];
    switch (key.toLowerCase()) {
      case 'subject':
        builder.subject = value;
        // Defaults to QP-encoding
        builder.subjectEncoding = HeaderEncoding.Q;
        break;
      case 'to':
        to.addAll(value!.split(',').map((email) => MailAddress(null, email)));
        break;
      case 'cc':
        builder.cc = value!
            .split(',')
            .map((email) => MailAddress(null, email))
            .toList();
        break;
      case 'body':
        builder.text = value;
        break;
      case 'in-reply-to':
        builder.setHeader(key, value);
        break;
      default:
        print('unsuported mailto parameter $key=$value');
    }
  }
  builder.to = to;
  return builder;
}