Route Notifications Via Username & Email

Format your email field(s) in notifications as {usernames:user1:user2}{emails:account@example.com} or {usernames:user1:user2:user3} or as usual.

// Allow Gravity Form notification email fields to use usernames and email
// Format your email fields in notifications as {usernames:user1:user2:user3} or {usernames:user1:user2}{emails:account@example.com}
add_filter( 'gform_notification', function ( $notification, $form, $entry ) {

   // reusable function for translating routes
   function typewheel_gform_notification_translate_routes( $routes ) {

      if ( strpos( $routes, '{usernames' ) !== false || strpos( $routes, '{emails' ) !== false ) {

         // parse the username and email batches
         $routes = str_replace( array( '} {', '},{' ), '}{', $routes );
         $batches = explode( '}{', substr( $routes, 1, -1 ) );

         foreach ( $batches as $key => $batch ) {

            if ( strpos( $batch, 'usernames' ) !== false )
               $usernames = explode( ':', $batch );

            if ( strpos( $batch, 'emails' ) !== false )
               $emails = explode( ':', $batch );

         }

         $to = array(); // initialize the to array

         // loop through users and grab the email
         if ( isset( $usernames ) ) {
            unset( $usernames[0] );
            foreach ( $usernames as $username ) {
               $user = get_user_by( 'login', $username );
               if ( $user !== false ) $to[] = $user->user_email;
            }
         }

         // loop through the email addresses
         if ( isset( $emails ) ) {
            unset( $emails[0] );
            foreach ( $emails as $email ) $to[] = $email;
         }

         // add all addresses to the notification
         $routes = implode( ',', $to );

      }

      return $routes;

   } // end typewheel_gform_notification_translate_routes()

   // run all email fields in the notification through route translation
   if ( $notification['toType'] == 'email' ) {

      $notification['to'] = typewheel_gform_notification_translate_routes( $notification['to'] );

   } else if ( $notification['toType'] == 'routing' ) {

      foreach ( $notification['routing'] as $key => $route )
         $notification['routing'][ $key ]['email'] = typewheel_gform_notification_translate_routes( $notification['routing'][ $key ]['email'] );

   }

   $notification['from'] = typewheel_gform_notification_translate_routes( $notification['from'] );
   $notification['replyTo'] = typewheel_gform_notification_translate_routes( $notification['replyTo'] );
   $notification['bcc'] = typewheel_gform_notification_translate_routes( $notification['bcc'] );

   return $notification;

}, 10, 3 );

#