Parse email addresses
484478
def __parse_addr(self, addr):
        

        from email.utils import parseaddr

        value = parseaddr(addr)
        return value[0], value[1]
947693
def from_email(self, value):
        
        if isinstance(value, str):
            value = From(value, None)
        if isinstance(value, tuple):
            value = From(value[0], value[1])
        self._from_email = value
94801
public static Set<String> parseUniqueEmails(final String emailList,
      final String splitRegex) {
    final Set<String> uniqueEmails = new HashSet<>();

    if (emailList == null) {
      return uniqueEmails;
    }

    final String[] emails = emailList.trim().split(splitRegex);
    for (final String email : emails) {
      if (!email.isEmpty()) {
        uniqueEmails.add(email);
      }
    }

    return uniqueEmails;
  }
877485
def get_recipients(self, name):
        
        to_str = self.render_string(self.data[name])
        formatted_emails = [
            email.utils.formataddr(addr_pair)
            for addr_pair in email.utils.getaddresses([to_str])
        ]
        return [i for i in formatted_emails if i]
82698
public static function parseEmailAddress($email)
    {
        $pattern = sprintf('/^(?<local>%s)@(?<domain>%s)$/iD', self::EMAIL_REGEX_LOCAL, self::EMAIL_REGEX_DOMAIN);

        if (!preg_match($pattern, $email, $parts)) {
            throw new InvalidEmailException(sprintf('"%s" is not a valid email', $email));
        }

        return array_map('strtolower', [$parts['local'], $parts['domain']]);
    }
352999
def getaddresses(fieldvalues):
    """"""
    all = COMMASPACE.join(fieldvalues)
    a = _AddressList(all)
    return a.addresslist
1010020
def is_email_address(string):
    
    return string and isinstance(string, base_string) \
        and REGEX_PATTERN_EMAIL_ADDRESS.match(string.strip().lower())
532993
def maillist_parse(file)
      maillist = []

      # if file doesn't exist, just return empty array, otherwise, parse for emails
      if File.exist?(file)
        File.readlines(file).each do |line|
          if index = (line =~ /\#/)
            # line contains some kind of comment
            # check if there is any useful info, ignore it not
            unless line[0, index].strip.empty?
              maillist << Origen::Users::User.new(line[0, index].strip).email
            end
          else
            # if line is not empty, generate an email
            unless line.strip.empty?
              maillist << Origen::Users::User.new(line.strip).email
            end
          end
        end
      end
      maillist
    end
33204
def normalize(email_address, resolve=True):
    
    address = utils.parseaddr(email_address)
    local_part, domain_part = address[1].lower().split('@')

    # Plus addressing is supported by Microsoft domains and FastMail
    if domain_part in MICROSOFT_DOMAINS:
        if '+' in local_part:
            local_part = local_part.split('+')[0]

    # GMail supports plus addressing and throw-away period delimiters
    elif _is_gmail(domain_part, resolve):
        local_part = local_part.replace('.', '').split('+')[0]

    # Yahoo domain handling of - is like plus addressing
    elif _is_yahoo(domain_part, resolve):
        if '-' in local_part:
            local_part = local_part.split('-')[0]

    # FastMail has domain part username aliasing and plus addressing
    elif _is_fastmail(domain_part, resolve):
        domain_segments = domain_part.split('.')
        if len(domain_segments) > 2:
            local_part = domain_segments[0]
            domain_part = '.'.join(domain_segments[1:])
        elif '+' in local_part:
            local_part = local_part.split('+')[0]

    return '@'.join([local_part, domain_part])
700455
private function parseAddresses($list) {
        $addresses = [];

        foreach ($list as $item) {
            $address = (object) $item;

            if (!property_exists($address, 'mailbox')) {
                $address->mailbox = false;
            }
            if (!property_exists($address, 'host')) {
                $address->host = false;
            }
            if (!property_exists($address, 'personal')) {
                $address->personal = false;
            }

            $personalParts = imap_mime_header_decode($address->personal);

            $address->personal = '';
            foreach ($personalParts as $p) {
                $address->personal .= $p->text;
            }

            $address->mail = ($address->mailbox && $address->host) ? $address->mailbox.'@'.$address->host : false;
            $address->full = ($address->personal) ? $address->personal.' <'.$address->mail.'>' : $address->mail;

            $addresses[] = $address;
        }

        return $addresses;
    }
1211570
def deserialize_email_messages(messages: List[str]):
    """"""
    return [
        pickle.loads(zlib.decompress(base64.b64decode(m)))
        for m in messages
    ]
588930
private String parseAddress(String address) {
        try {
            StringBuilder buf = new StringBuilder();
            InternetAddress[] netAddrs = InternetAddress.parseHeader(address, false);
            for (InternetAddress netAddr : netAddrs) {
                if (buf.length() > 0) {
                    buf.append(SP);
                }

                buf.append(LB);

                String personal = netAddr.getPersonal();
                if (personal != null && (personal.length() != 0)) {
                    buf.append(Q).append(personal).append(Q);
                } else {
                    buf.append(NIL);
                }
                buf.append(SP);
                buf.append(NIL); // should add route-addr
                buf.append(SP);
                try {
                    // Remove quotes to avoid double quoting
                    MailAddress mailAddr = new MailAddress(netAddr.getAddress().replaceAll("\"", "\\\\\""));
                    buf.append(Q).append(mailAddr.getUser()).append(Q);
                    buf.append(SP);
                    buf.append(Q).append(mailAddr.getHost()).append(Q);
                } catch (Exception pe) {
                    buf.append(NIL + SP + NIL);
                }
                buf.append(RB);
            }

            return buf.toString();
        } catch (AddressException e) {
            throw new RuntimeException("Failed to parse address: " + address, e);
        }
    }
531594
function(apiKey, contactList, fromAddress,
        toAddress, ccAddresses, bccAddresses, contentType, subject, htmlBody,
        textBody, _templateId) {}
1124100
def parse_query s
    query = {}

    subs = HookManager.run("custom-search", :subs => s) || s
    begin
      subs = SearchManager.expand subs
    rescue SearchManager::ExpansionError => e
      raise ParseError, e.message
    end
    subs = subs.gsub(/\b(to|from):(\S+)\b/) do
      field, value = $1, $2
      email_field, name_field = %w(email name).map { |x| "#{field}_#{x}" }
      if(p = ContactManager.contact_for(value))
        "#{email_field}:#{p.email}"
      elsif value == "me"
        '(' + AccountManager.user_emails.map { |e| "#{email_field}:#{e}" }.join(' OR ') + ')'
      else
        "(#{email_field}:#{value} OR #{name_field}:#{value})"
      end
    end

    ## gmail style "is" operator
    subs = subs.gsub(/\b(is|has):(\S+)\b/) do
      field, label = $1, $2
      case label
      when "read"
        "-label:unread"
      when "spam"
        query[:load_spam] = true
        "label:spam"
      when "deleted"
        query[:load_deleted] = true
        "label:deleted"
      else
        "label:#{$2}"
      end
    end

    ## labels are stored lower-case in the index
    subs = subs.gsub(/\blabel:(\S+)\b/) do
      label = $1
      "label:#{label.downcase}"
    end

    ## if we see a label:deleted or a label:spam term anywhere in the query
    ## string, we set the extra load_spam or load_deleted options to true.
    ## bizarre? well, because the query allows arbitrary parenthesized boolean
    ## expressions, without fully parsing the query, we can't tell whether
    ## the user is explicitly directing us to search spam messages or not.
    ## e.g. if the string is -(-(-(-(-label:spam)))), does the user want to
    ## search spam messages or not?
    ##
    ## so, we rely on the fact that turning these extra options ON turns OFF
    ## the adding of "-label:deleted" or "-label:spam" terms at the very
    ## final stage of query processing. if the user wants to search spam
    ## messages, not adding that is the right thing; if he doesn't want to
    ## search spam messages, then not adding it won't have any effect.
    query[:load_spam] = true if subs =~ /\blabel:spam\b/
    query[:load_deleted] = true if subs =~ /\blabel:deleted\b/
    query[:load_killed] = true if subs =~ /\blabel:killed\b/

    ## gmail style attachments "filename" and "filetype" searches
    subs = subs.gsub(/\b(filename|filetype):(\((.+?)\)\B|(\S+)\b)/) do
      field, name = $1, ($3 || $4)
      case field
      when "filename"
        debug "filename: translated #{field}:#{name} to attachment:\"#{name.downcase}\""
        "attachment:\"#{name.downcase}\""
      when "filetype"
        debug "filetype: translated #{field}:#{name} to attachment_extension:#{name.downcase}"
        "attachment_extension:#{name.downcase}"
      end
    end

    lastdate = 2<<32 - 1
    firstdate = 0
    subs = subs.gsub(/\b(before|on|in|during|after):(\((.+?)\)\B|(\S+)\b)/) do
      field, datestr = $1, ($3 || $4)
      realdate = Chronic.parse datestr, :guess => false, :context => :past
      if realdate
        case field
        when "after"
          debug "chronic: translated #{field}:#{datestr} to #{realdate.end}"
          "date:#{realdate.end.to_i}..#{lastdate}"
        when "before"
          debug "chronic: translated #{field}:#{datestr} to #{realdate.begin}"
          "date:#{firstdate}..#{realdate.end.to_i}"
        else
          debug "chronic: translated #{field}:#{datestr} to #{realdate}"
          "date:#{realdate.begin.to_i}..#{realdate.end.to_i}"
        end
      else
        raise ParseError, "can't understand date #{datestr.inspect}"
      end
    end

    ## limit:42 restrict the search to 42 results
    subs = subs.gsub(/\blimit:(\S+)\b/) do
      lim = $1
      if lim =~ /^\d+$/
        query[:limit] = lim.to_i
        ''
      else
        raise ParseError, "non-numeric limit #{lim.inspect}"
      end
    end

    debug "translated query: #{subs.inspect}"

    qp = Xapian::QueryParser.new
    qp.database = @xapian
    qp.stemmer = Xapian::Stem.new($config[:stem_language])
    qp.stemming_strategy = Xapian::QueryParser::STEM_SOME
    qp.default_op = Xapian::Query::OP_AND
    valuerangeprocessor = Xapian::NumberValueRangeProcessor.new(DATE_VALUENO,
                                                                'date:', true)
    qp.add_valuerangeprocessor(valuerangeprocessor)
    NORMAL_PREFIX.each { |k,info| info[:prefix].each {
      |v| qp.add_prefix k, v }
    }
    BOOLEAN_PREFIX.each { |k,info| info[:prefix].each {
      |v| qp.add_boolean_prefix k, v, info[:exclusive] }
    }

    begin
      xapian_query = qp.parse_query(subs, Xapian::QueryParser::FLAG_PHRASE   |
                                          Xapian::QueryParser::FLAG_BOOLEAN  |
                                          Xapian::QueryParser::FLAG_LOVEHATE |
                                          Xapian::QueryParser::FLAG_WILDCARD)
    rescue RuntimeError => e
      raise ParseError, "xapian query parser error: #{e}"
    end

    debug "parsed xapian query: #{Util::Query.describe(xapian_query, subs)}"

    if xapian_query.nil? or xapian_query.empty?
      raise ParseError, "couldn't parse \"#{s}\" as xapian query " \
                        "(special characters aren't indexed)"
    end

    query[:qobj] = xapian_query
    query[:text] = s
    query
  end
447519
def extract_emails(results: str, domain: str, fuzzy: bool) -> List[str]:
    """"""
    pattern: Pattern = re.compile(r'([\w.-]+@[\w.-]+)')
    hits: List[str] = pattern.findall(results)
    if fuzzy:
        seed = domain.split('.')[0]
        emails: List[str] = [x.lower() for x in hits if x.split('@')[1].__contains__(seed)]
    else:
        emails: List[str] = [x.lower() for x in hits if x.endswith(domain)]
    return list(set(emails))
1226522
def user_parse(data):
        """"""
        _user = data.get('oauth', {}).get('user', {})
        yield 'id', _user.get('id')
        yield 'username', _user.get('username')
        first_name, _, last_name = _user.get('display_name').partition(' ')
        yield 'first_name', first_name
        yield 'last_name', last_name
402894
def parse_headers(cls, msg):
        
        return list(email.parser.Parser().parsestr(msg).items())