Extracts the subject line from an EmailMessage object.
518183
def get_subject(self, msg):
        """"""

        text, encoding = decode_header(msg['subject'])[-1]

        try:
            text = text.decode(encoding)

        # If it's already decoded, ignore error
        except AttributeError:
            pass

        return text
132952
private String extractAttributes(SoyMsg msg) {
    StringBuilder attributes = new StringBuilder();
    Matcher matcher = MESSAGE_ATTRIBUTE_PATTERN.matcher(msg.getDesc());
    while (matcher.find()) {
      attributes.append(matcher.group());
    }
    return attributes.toString();
  }
954027
def parse(cls, msg):
        """"""
        lines = msg.splitlines()
        version, status_code, reason = lines[0].split()
        headers = cls.parse_headers('\r\n'.join(lines[1:]))
        return cls(version=version, status_code=status_code,
                   reason=reason, headers=headers)
279292
def __parse_email_to_employer_line(self, raw_email, raw_enrollment):
        """"""

        e = re.match(self.EMAIL_ADDRESS_REGEX, raw_email, re.UNICODE)
        if not e and self.email_validation:
            cause = "invalid email format: '%s'" % raw_email
            raise InvalidFormatError(cause=cause)

        if self.email_validation:
            email = e.group('email').strip()
        else:
            email = raw_email

        r = re.match(self.ENROLLMENT_REGEX, raw_enrollment, re.UNICODE)
        if not r:
            cause = "invalid enrollment format: '%s'" % raw_enrollment
            raise InvalidFormatError(cause=cause)

        org = r.group('organization').strip()
        date = r.group('date')

        if date:
            try:
                dt = dateutil.parser.parse(r.group('date'))
            except Exception as e:
                cause = "invalid date: '%s'" % date
        else:
            dt = MAX_PERIOD_DATE

        email = self.__encode(email)
        org = self.__encode(org)

        return email, org, dt
286396
def from_response(cls, response_data):
        
        identity = lambda x: x
        return Mail(**_transform_dict(response_data, {
            'guid': ('mail_id', identity),
            'subject': ('mail_subject', identity),
            'sender': ('mail_from', identity),
            'datetime': ('mail_timestamp', lambda x: datetime.utcfromtimestamp(int(x)).replace(tzinfo=utc)),
            'read': ('mail_read', int),
            'excerpt': ('mail_excerpt', identity),
            'body': ('mail_body', identity),
        }))
896172
def _message(self):
        """"""
        ascii_attachments = current_app.extensions['mail'].ascii_attachments
        encoding = self.charset or 'utf-8'

        attachments = self.attachments or []

        if len(attachments) == 0 and not self.alts:
            # No html content and zero attachments means plain text
            msg = self._mimetext(self.body, self.subtype)
        elif len(attachments) > 0 and not self.alts:
            # No html and at least one attachment means multipart
            subtype = self.subtype or 'mixed'
            msg = MIMEMultipart(_subtype=subtype)
            msg.attach(self._mimetext(self.body))
        else:
            # Anything else
            subtype = self.subtype or 'mixed'
            msg = MIMEMultipart(_subtype=subtype)
            alternative = MIMEMultipart(_subtype='alternative')
            alternative.attach(self._mimetext(self.body))
            for mimetype, content in self.alts.items():
                alternative.attach(self._mimetext(content, mimetype))
            msg.attach(alternative)

        if self.subject:
            msg['Subject'] = sanitize_subject(force_text(self.subject),
                                              encoding)

        msg['From'] = sanitize_address(self.sender, encoding)
        msg['To'] = ', '.join(
            list(set(sanitize_addresses(self.recipients, encoding)))
        )

        msg['Date'] = formatdate(self.date, localtime=True)
        # see RFC 5322 section 3.6.4.
        msg['Message-ID'] = self.msgId

        if self.cc:
            msg['Cc'] = ', '.join(
                list(set(sanitize_addresses(self.cc, encoding)))
            )

        if self.reply_to:
            msg['Reply-To'] = sanitize_address(self.reply_to, encoding)

        if self.extra_headers:
            for k, v in self.extra_headers.items():
                msg[k] = v

        SPACES = re.compile(r'[\s]+', re.UNICODE)
        for attachment in attachments:
            f = MIMEBase(*attachment.content_type.split('/'))
            f.set_payload(attachment.data)
            encode_base64(f)

            filename = attachment.filename
            if filename and ascii_attachments:
                # force filename to ascii
                filename = unicodedata.normalize('NFKD', filename)
                filename = filename.encode('ascii', 'ignore').decode('ascii')
                filename = SPACES.sub(u' ', filename).strip()

            try:
                filename and filename.encode('ascii')
            except UnicodeEncodeError:
                if not PY3:
                    filename = filename.encode('utf8')
                filename = ('UTF8', '', filename)

            f.add_header('Content-Disposition',
                         attachment.disposition,
                         filename=filename)

            for key, value in attachment.headers.items():
                f.add_header(key, value)

            if attachment.content_id:
                try:
                    f.replace_header('Content-ID', attachment.content_id)
                except KeyError:
                    f.add_header('Content-ID', attachment.content_id)

            msg.attach(f)
        if message_policy:
            msg.policy = message_policy

        return msg
1240170
def email(to='medusa@sweeting.me', _from=default_from, subject='BOT MSG', message="Info email", attachments=None):
    """"""
    for attachment in attachments or []:
        filename = attachment.strip()
        try:
            result = run_cmd('uuencode %s %s | mailx -s "%s" %s' % (filename, filename, subject, to))[0]
            return "Sending email From: %s; To: %s; Subject: %s; Attachment: %s (%s)" % (_from, to, subject, filename, result or 'Succeded')
        except Exception as error:
            return str(error)

    if not attachments:
        p = os.popen("/usr/sbin/sendmail -t", "w")
        p.write("From: %s\n" % _from)
        p.write("To: %s\n" % to)
        p.write("Subject: %s\n" % subject)
        p.write("\n")   # blank line separating headers from body
        p.write('%s\n' % message)
        result = p.close()

    if not result:
        return "Sent email From: %s; To: %s; Subject: %s; Attachments: %s)" % (_from, to, subject, ','.join(attachments or []))
    else:
        return "Error: %s. Please fix Postfix:\n %s" % (result, help_str)
1270353
def subject(self):
        
        template_name = self.subject_template_name() if \
            callable(self.subject_template_name) \
            else self.subject_template_name
        subject = loader.render_to_string(
            template_name, self.get_context(), request=self.request
        )
        return ''.join(subject.splitlines())
113231
def fetch_plaintext_by_subject(self, email_name):
        
        if not email_name:
            raise EmailException("Subject cannot be null")

        results = self.__imap_search(SUBJECT=email_name)
        sources = self.fetch_plaintext(results)

        return sources
452076
def _extract_email(data):
    
    ret = ''
    elements = data.get('elements', [])
    if len(elements) > 0:
        ret = elements[0].get('handle~', {}).get('emailAddress', '')
    return ret
557930
def _parse_outgoing_mail(sender, to, msgstring):
    
    global OUTBOX
    OUTBOX.append(email.message_from_string(msgstring))
    return
114001
def get(self):
        """"""

        # First retrieve all header bytes in order to extract
        # length of the message remainder.
        header = ''
        while len(header) < self.HEADER_LENGTH:
            chunk = self._sock.recv(self.HEADER_LENGTH - len(header))
            chunk = chunk.decode() if self._encode else chunk
            if chunk == '':
                return None
            header += chunk
        length = int(header)

        # Then retrieve the remainder of the message.
        message = ''
        while len(message) < length:
            chunk = self._sock.recv(length - len(message))
            chunk = chunk.decode() if self._encode else chunk
            if chunk == '':
                return None
            message += chunk
        return message
1294019
def _extract(self):
        
        self.log.debug("Extracting emails from text content")
        for item in self.data:
            emails = extract_emails(item, self.domain, self.fuzzy)
            self.results.extend(emails)
        self.log.debug("Email extraction completed")
        return list(set(self.results))
966218
def get_mime_message(subject, text):
    
    message = MIMEText(
        "<html>" +
        str(text).replace("\n", "<br>") +
        "</html>", "html"
    )
    message["subject"] = str(subject)
    return message
576361
def get_subject(self, text):
        
        first_line = text.splitlines(True)[0]
        # TODO second line should be empty
        if first_line.startswith('SUBJECT:'):
            subject = first_line[len('SUBJECT:'):]
        else:
            subject = first_line
        return subject.strip()
382197
def get_raw_email(self):
        
        if 'email' in self.payload:
            raw_email = email.message_from_string(self.payload['email'])
            return raw_email
        else:
            return None
1059186
def email_message(
        self,
        recipient,  # type: Text
        subject_template,  # type: Text
        body_template,  # type: Text
        sender=None,  # type: Optional[AbstractUser]
        message_class=EmailMessage,
        **kwargs
    ):
        
        from_email = "%s %s <%s>" % (
            sender.first_name,
            sender.last_name,
            email.utils.parseaddr(settings.DEFAULT_FROM_EMAIL)[1],
        )
        reply_to = "%s %s <%s>" % (sender.first_name, sender.last_name, sender.email)

        headers = {"Reply-To": reply_to}
        kwargs.update({"sender": sender, "recipient": recipient})

        subject_template = loader.get_template(subject_template)
        body_template = loader.get_template(body_template)

        subject = subject_template.render(
            kwargs
        ).strip()  # Remove stray newline characters

        body = body_template.render(kwargs)

        return message_class(subject, body, from_email, [recipient], headers=headers)