def test_happy_path(): p = ActivityOverTime() msg = Message() msg.set_payload('Hello world!', 'utf-8') msg["Date"] = 'Fri, 9 Jun 2006 12:34:56 -0200' p.process(msg) generated = p.report_snippet() assert '"x": ["2006-06-09"], "y": [1]' in generated msg = Message() # no payload this time msg["Date"] = 'Sun, 13 Jun 2006 12:34:56 -0200' p.process(msg) generated = p.report_snippet() assert '"x": ["2006-06-09", "2006-06-13"], "y": [1, 1]' in generated
def send_async_email(email_data): """Background task to send an email with Flask-Mail.""" msg = Message(email_data['subject'], sender=app.config['MAIL_DEFAULT_SENDER'], recipients=[email_data['to']]) msg.body = email_data['body'] with app.app_context(): mail.send(msg)
def load_mail(filename): """Read email from fixtures of an user.""" # XXX tofix: set fixtures in a more convenient way to not # have dirty hacking on relative path dir_path = os.path.dirname(os.path.realpath(__file__)) path = '{}/fixtures'.format(dir_path) with open('{}/{}'.format(path, filename)) as f: data = f.read() return Message(data)
def filename_from_content_disposition(content_disposition): """ Extract and validate filename from a Content-Disposition header. """ msg = Message('Content-Disposition: %s' % content_disposition) filename = msg.get_filename() if filename: # Basic sanitation. filename = os.path.basename(filename).lstrip('.').strip() if filename: return filename
def __init__(self, raw_data): """Parse an RFC2822,5322 mail message.""" self.raw = raw_data try: self.mail = Message(raw_data) except Exception as exc: log.error('Parse message failed %s' % exc) raise exc if self.mail.defects: # XXX what to do ? log.warn('Defects on parsed mail %r' % self.mail.defects) self.warning = self.mail.defects self.get_bodies()
def test_happy_path(): p = DowHourHeatmap() msg = Message() msg.set_payload('Hello world!', 'utf-8') msg["Date"] = 'Fri, 9 Jun 2006 12:34:56 -0200' p.process(msg) generated = p.report_snippet() assert '"type": "heatmap"' in generated assert '"Mon", "Tue", "Wed"' in generated hrs = [0] * 24 assert generated.count(str(hrs)) == 6 # element 12 + 2 is 1, because it is UTC hrs[14] = 1 assert str(hrs) in generated
def message_factory(message): m = Message(message) logger.debug('Handling mail from %s with subject "%s"', m['From'], m['Subject']) logger.debug(m['Date']) try: d = dateparse(m['Date']) except ValueError: logger.warning( 'Mail from %s with subject "%s" Does not have a ' '"Date" header! Some features will fail because of ' 'this!', m['From'], m['Subject']) d = datetime.now() m.set_date(d.timestamp()) return m
def forward(self, command, forward_to, m_from=None): if type(command) is not str: logger.error( "Trying to forward message %s without setting the " "command to use!", command) m = Message() m['From'] = m_from or self['to'] m['To'] = forward_to m['Subject'] = "Fwd: " + self['subject'] m.set_payload(self.get_payload()) run(command + " " + m['To'], stdout=PIPE, input=m.as_string().encode('utf-8'), shell=True, check=True) return self
def filename_from_content_disposition(content_disposition): """ Extract and validate filename from a Content-Disposition header. :param content_disposition: Content-Disposition value :return: the filename if present and valid, otherwise `None` """ # attachment; filename=jakubroztocil-httpie-0.4.1-20-g40bd8f6.tar.gz msg = Message('Content-Disposition: %s' % content_disposition) filename = msg.get_filename() if filename: # Basic sanitation. filename = os.path.basename(filename).lstrip('.').strip() if filename: return filename
def get_fields(self, uid, fields): """ Return an mailbox.Message object containing only the requested header fields of the message with UID. The fields parameter is a string ofheader fields seperated by spaces, e.g. 'From SUBJECT date' Raise KeyError if there if there is no message with that UID. """ (code, data) = self._server.uid('fetch', uid, "(BODY.PEEK[HEADER.FIELDS (%s)])" % fields) if code != 'OK': raise ImapNotOkError("%s in fetch_header(%s)" % (code, uid)) try: rfc822string = data[0][1] except TypeError: raise KeyError("No UID %s in get_fields" % uid) result = Message(rfc822string) return result
def process_message(self, page): id_ = fid, tid, mid = page.id headers = { 'GGE-Url': page.url, 'GGE-Id': '{}/{}/{}'.format(*id_), 'GGE-Forum-Id': fid, 'GGE-Topic-Id': tid, 'GGE-Message-Id': mid, } msg = Message(str(page)) for k, v in headers.items(): msg.add_header(k, v) self.mbox.add(msg) self.summary['messages'] += 1
def __init__(self, raw): """Initialize structure from a raw mail.""" try: self.mail = Message(raw) except Exception as exc: log.error('Parse message failed %s' % exc) raise if self.mail.defects: # XXX what to do ? log.warn('Defects on parsed mail %r' % self.mail.defects) self.recipients = self._extract_recipients() self.parts = self._extract_parts() self.headers = self._extract_headers() self.subject = self.mail.get('Subject') tmp_date = parsedate_tz(self.mail['Date']) self.date = datetime.fromtimestamp(mktime_tz(tmp_date)) self.external_message_id = self.mail.get('Message-Id') self.external_parent_id = self.mail.get('In-Reply-To') self.size = len(raw)
def get_message(self, key): info, payload = self.get(key) return Message(payload)
def get_message(self, key): """Return a Message representation or raise a KeyError.""" return Message(self._get(key))
def as_message(self): """Returns the mail as an instance of ``mailbox.Message``.""" return Message(self.render())
def __init__(self, raw): try: self.mail = Message(raw) except Exception, exc: log.error('Parse message failed %s' % exc) raise