Python email.utils.formatdate() Examples

The following are 30 code examples of email.utils.formatdate(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module email.utils , or try the search function .
Example #1
Source File: utils.py    From ffplayout-engine with GNU General Public License v3.0 8 votes vote down vote up
def send_mail(self, msg):
        if _mail.recip:
            # write message to temp file for rate limit
            with open(self.temp_msg, 'w+') as f:
                f.write(msg)

            self.current_time()

            message = MIMEMultipart()
            message['From'] = _mail.s_addr
            message['To'] = _mail.recip
            message['Subject'] = _mail.subject
            message['Date'] = formatdate(localtime=True)
            message.attach(MIMEText('{} {}'.format(self.time, msg), 'plain'))
            text = message.as_string()

            try:
                server = smtplib.SMTP(_mail.server, _mail.port)
            except socket.error as err:
                playout_logger.error(err)
                server = None

            if server is not None:
                server.starttls()
                try:
                    login = server.login(_mail.s_addr, _mail.s_pass)
                except smtplib.SMTPAuthenticationError as serr:
                    playout_logger.error(serr)
                    login = None

                if login is not None:
                    server.sendmail(_mail.s_addr, _mail.recip, text)
                    server.quit() 
Example #2
Source File: smtp.py    From satori with Apache License 2.0 8 votes vote down vote up
def send_mail(send_from, send_to, subject, text, files=[], server="localhost", ssl=False, username=None, password=None):
    msg = MIMEMultipart('alternative')
    msg.set_charset('utf-8')
    msg['From'] = send_from
    msg['To'] = send_to
    msg['Date'] = formatdate(localtime=True)
    msg['Subject'] = subject
    part = MIMEText(text)
    part.set_charset('utf-8')
    msg.attach(part)
    if ssl:
        smtp = smtplib.SMTP_SSL(server)
    else:
        smtp = smtplib.SMTP(server)
    if username:
        smtp.login(username, password)
    smtp.sendmail(send_from, send_to, msg.as_string())
    smtp.close() 
Example #3
Source File: test_App.py    From dataserv with MIT License 7 votes vote down vote up
def test_success(self):

        # create header date and authorization signature
        blockchain = BtcTxStore()
        wif = blockchain.create_key()
        address = blockchain.get_address(wif)
        header_date = formatdate(timeval=mktime(datetime.now().timetuple()),
                                 localtime=True, usegmt=True)
        message = app.config["ADDRESS"] + " " + header_date
        header_authorization = blockchain.sign_unicode(wif, message)
        headers = {"Date": header_date, "Authorization": header_authorization}
        url = '/api/register/{0}'.format(address)
        rv = self.app.get(url, headers=headers)
        data = json.loads(rv.data.decode("utf-8"))
        self.assertEqual(address, data["btc_addr"])
        self.assertEqual(rv.status_code, 200) 
Example #4
Source File: utils.py    From GerbLook with BSD 2-Clause "Simplified" License 7 votes vote down vote up
def send_email(msg_to, msg_subject, msg_body, msg_from=None,
        smtp_server='localhost', envelope_from=None,
        headers={}):

  if not msg_from:
    msg_from = app.config['EMAIL_FROM']

  if not envelope_from:
    envelope_from = parseaddr(msg_from)[1]

  msg = MIMEText(msg_body)

  msg['Subject'] = Header(msg_subject)
  msg['From'] = msg_from
  msg['To'] = msg_to
  msg['Date'] = formatdate()
  msg['Message-ID'] = make_msgid()
  msg['Errors-To'] = envelope_from

  if request:
    msg['X-Submission-IP'] = request.remote_addr

  s = smtplib.SMTP(smtp_server)
  s.sendmail(envelope_from, msg_to, msg.as_string())
  s.close() 
Example #5
Source File: sendmail.py    From WordOps with MIT License 7 votes vote down vote up
def WOSendMail(send_from, send_to, subject, text, files, server="localhost",
               port=587, username='', password='', isTls=True):
    msg = MIMEMultipart()
    msg['From'] = send_from
    msg['To'] = send_to
    msg['Date'] = formatdate(localtime=True)
    msg['Subject'] = subject

    msg.attach(MIMEText(text))

    for f in files:
        part = MIMEBase('application', "octet-stream")
        part.set_payload(open(f, "rb").read())
        encoders.encode_base64(part)
        part.add_header('Content-Disposition', 'attachment; filename="{0}"'
                        .format(os.path.basename(f)))
        msg.attach(part)

    smtp = smtplib.SMTP(server, port)
    if isTls:
        smtp.starttls()

    smtp.sendmail(send_from, send_to, msg.as_string())
    smtp.quit() 
Example #6
Source File: auth.py    From deepWordBug with Apache License 2.0 6 votes vote down vote up
def add_auth(self, request):
        if self.credentials is None:
            raise NoCredentialsError
        if 'Date' in request.headers:
            del request.headers['Date']
        request.headers['Date'] = formatdate(usegmt=True)
        if self.credentials.token:
            if 'X-Amz-Security-Token' in request.headers:
                del request.headers['X-Amz-Security-Token']
            request.headers['X-Amz-Security-Token'] = self.credentials.token
        new_hmac = hmac.new(self.credentials.secret_key.encode('utf-8'),
                            digestmod=sha256)
        new_hmac.update(request.headers['Date'].encode('utf-8'))
        encoded_signature = encodebytes(new_hmac.digest()).strip()
        signature = ('AWS3-HTTPS AWSAccessKeyId=%s,Algorithm=%s,Signature=%s' %
                     (self.credentials.access_key, 'HmacSHA256',
                      encoded_signature.decode('utf-8')))
        if 'X-Amzn-Authorization' in request.headers:
            del request.headers['X-Amzn-Authorization']
        request.headers['X-Amzn-Authorization'] = signature 
Example #7
Source File: mail.py    From osm-wikidata with GNU General Public License v3.0 6 votes vote down vote up
def send_mail_main(subject, body, config=None):
    if config is None:
        config = current_app.config

    mail_to = config['ADMIN_EMAIL']
    mail_from = config['MAIL_FROM']
    msg = MIMEText(body, 'plain', 'UTF-8')

    msg['Subject'] = subject
    msg['To'] = mail_to
    msg['From'] = mail_from
    msg['Date'] = formatdate()
    msg['Message-ID'] = make_msgid()

    s = smtplib.SMTP(config['SMTP_HOST'])
    s.sendmail(mail_from, [mail_to], msg.as_string())
    s.quit() 
Example #8
Source File: auth.py    From faces with GNU General Public License v2.0 6 votes vote down vote up
def _set_necessary_date_headers(self, request):
        # The spec allows for either the Date _or_ the X-Amz-Date value to be
        # used so we check both.  If there's a Date header, we use the date
        # header.  Otherwise we use the X-Amz-Date header.
        if 'Date' in request.headers:
            del request.headers['Date']
            datetime_timestamp = datetime.datetime.strptime(
                request.context['timestamp'], SIGV4_TIMESTAMP)
            request.headers['Date'] = formatdate(
                int(calendar.timegm(datetime_timestamp.timetuple())))
            if 'X-Amz-Date' in request.headers:
                del request.headers['X-Amz-Date']
        else:
            if 'X-Amz-Date' in request.headers:
                del request.headers['X-Amz-Date']
            request.headers['X-Amz-Date'] = request.context['timestamp'] 
Example #9
Source File: tasks.py    From fomalhaut-panel with MIT License 6 votes vote down vote up
def send_mail_by_postfix(mail_to, content_type, content,
                         subject=DEFAULT_EMAIL_NOTIFY_SUBJECT,
                         mail_from=EMAIL_NOTIFY_NAME,
                         server=EMAIL_SMTP_SERVER):
    """
    使用 Postfix 作为 SMTP Server 来发送邮件
    """
    logger.debug('run send_mail_by_postfix')
    if type(mail_to) != list:
        raise TypeError('mail_to is not a list')

    if content_type not in ('plain', 'html'):
        raise ValueError('content_type is not plain or html')

    msg = MIMEMultipart()
    msg['From'] = mail_from
    msg['To'] = COMMASPACE.join(mail_to)
    msg['Date'] = formatdate(localtime=True)
    msg['Subject'] = subject
    msg.attach(MIMEText(content, _subtype=content_type, _charset='utf-8'))

    smtp = smtplib.SMTP(server)
    smtp.sendmail(mail_from, mail_to, msg.as_string())
    smtp.close()
    logger.info('邮件发送成功') 
Example #10
Source File: smtp.py    From satori with Apache License 2.0 6 votes vote down vote up
def send_mail(send_from, send_to, subject, text, files=[], server="localhost", ssl=False, username=None, password=None):
    msg = MIMEMultipart('alternative')
    msg.set_charset('utf-8')
    msg['From'] = send_from
    msg['To'] = send_to
    msg['Date'] = formatdate(localtime=True)
    msg['Subject'] = subject
    part = MIMEText(text)
    part.set_charset('utf-8')
    msg.attach(part)
    if ssl:
        smtp = smtplib.SMTP_SSL(server)
    else:
        smtp = smtplib.SMTP(server)
    if username:
        smtp.login(username, password)
    smtp.sendmail(send_from, send_to, msg.as_string())
    smtp.close() 
Example #11
Source File: message.py    From GTDWeb with GNU General Public License v2.0 6 votes vote down vote up
def message(self):
        encoding = self.encoding or settings.DEFAULT_CHARSET
        msg = SafeMIMEText(self.body, self.content_subtype, encoding)
        msg = self._create_message(msg)
        msg['Subject'] = self.subject
        msg['From'] = self.extra_headers.get('From', self.from_email)
        msg['To'] = self.extra_headers.get('To', ', '.join(self.to))
        if self.cc:
            msg['Cc'] = ', '.join(self.cc)
        if self.reply_to:
            msg['Reply-To'] = self.extra_headers.get('Reply-To', ', '.join(self.reply_to))

        # Email header names are case-insensitive (RFC 2045), so we have to
        # accommodate that when doing comparisons.
        header_names = [key.lower() for key in self.extra_headers]
        if 'date' not in header_names:
            msg['Date'] = formatdate()
        if 'message-id' not in header_names:
            # Use cached DNS_NAME for performance
            msg['Message-ID'] = make_msgid(domain=DNS_NAME)
        for name, value in self.extra_headers.items():
            if name.lower() in ('from', 'to'):  # From and To are already handled
                continue
            msg[name] = value
        return msg 
Example #12
Source File: auth.py    From faces with GNU General Public License v2.0 6 votes vote down vote up
def add_auth(self, request):
        if self.credentials is None:
            raise NoCredentialsError
        if 'Date' in request.headers:
            del request.headers['Date']
        request.headers['Date'] = formatdate(usegmt=True)
        if self.credentials.token:
            if 'X-Amz-Security-Token' in request.headers:
                del request.headers['X-Amz-Security-Token']
            request.headers['X-Amz-Security-Token'] = self.credentials.token
        new_hmac = hmac.new(self.credentials.secret_key.encode('utf-8'),
                            digestmod=sha256)
        new_hmac.update(request.headers['Date'].encode('utf-8'))
        encoded_signature = encodebytes(new_hmac.digest()).strip()
        signature = ('AWS3-HTTPS AWSAccessKeyId=%s,Algorithm=%s,Signature=%s' %
                     (self.credentials.access_key, 'HmacSHA256',
                      encoded_signature.decode('utf-8')))
        if 'X-Amzn-Authorization' in request.headers:
            del request.headers['X-Amzn-Authorization']
        request.headers['X-Amzn-Authorization'] = signature 
Example #13
Source File: auth.py    From faces with GNU General Public License v2.0 6 votes vote down vote up
def _set_necessary_date_headers(self, request):
        # The spec allows for either the Date _or_ the X-Amz-Date value to be
        # used so we check both.  If there's a Date header, we use the date
        # header.  Otherwise we use the X-Amz-Date header.
        if 'Date' in request.headers:
            del request.headers['Date']
            datetime_timestamp = datetime.datetime.strptime(
                request.context['timestamp'], SIGV4_TIMESTAMP)
            request.headers['Date'] = formatdate(
                int(calendar.timegm(datetime_timestamp.timetuple())))
            if 'X-Amz-Date' in request.headers:
                del request.headers['X-Amz-Date']
        else:
            if 'X-Amz-Date' in request.headers:
                del request.headers['X-Amz-Date']
            request.headers['X-Amz-Date'] = request.context['timestamp'] 
Example #14
Source File: auth.py    From deepWordBug with Apache License 2.0 6 votes vote down vote up
def _set_necessary_date_headers(self, request):
        # The spec allows for either the Date _or_ the X-Amz-Date value to be
        # used so we check both.  If there's a Date header, we use the date
        # header.  Otherwise we use the X-Amz-Date header.
        if 'Date' in request.headers:
            del request.headers['Date']
            datetime_timestamp = datetime.datetime.strptime(
                request.context['timestamp'], SIGV4_TIMESTAMP)
            request.headers['Date'] = formatdate(
                int(calendar.timegm(datetime_timestamp.timetuple())))
            if 'X-Amz-Date' in request.headers:
                del request.headers['X-Amz-Date']
        else:
            if 'X-Amz-Date' in request.headers:
                del request.headers['X-Amz-Date']
            request.headers['X-Amz-Date'] = request.context['timestamp'] 
Example #15
Source File: test_Farmer.py    From dataserv with MIT License 6 votes vote down vote up
def test_authentication_timeout(self):
        def callback():
            blockchain = BtcTxStore()
            wif = blockchain.create_key()
            address = blockchain.get_address(wif)
            farmer = Farmer(address)

            timeout = farmer.get_server_authentication_timeout()

            date = datetime.now() - timedelta(seconds=timeout)
            header_date = formatdate(timeval=mktime(date.timetuple()),
                                     localtime=True, usegmt=True)
            message = farmer.get_server_address() + " " + header_date
            header_authorization = blockchain.sign_unicode(wif, message)
            headers = {"Date": header_date,
                       "Authorization": header_authorization}
            farmer.authenticate(headers)
        self.assertRaises(storjcore.auth.AuthError, callback) 
Example #16
Source File: auth.py    From faces with GNU General Public License v2.0 6 votes vote down vote up
def add_auth(self, request):
        if self.credentials is None:
            raise NoCredentialsError
        if 'Date' in request.headers:
            del request.headers['Date']
        request.headers['Date'] = formatdate(usegmt=True)
        if self.credentials.token:
            if 'X-Amz-Security-Token' in request.headers:
                del request.headers['X-Amz-Security-Token']
            request.headers['X-Amz-Security-Token'] = self.credentials.token
        new_hmac = hmac.new(self.credentials.secret_key.encode('utf-8'),
                            digestmod=sha256)
        new_hmac.update(request.headers['Date'].encode('utf-8'))
        encoded_signature = encodebytes(new_hmac.digest()).strip()
        signature = ('AWS3-HTTPS AWSAccessKeyId=%s,Algorithm=%s,Signature=%s' %
                     (self.credentials.access_key, 'HmacSHA256',
                      encoded_signature.decode('utf-8')))
        if 'X-Amzn-Authorization' in request.headers:
            del request.headers['X-Amzn-Authorization']
        request.headers['X-Amzn-Authorization'] = signature 
Example #17
Source File: test_Farmer.py    From dataserv with MIT License 5 votes vote down vote up
def test_authentication_bad_sig(self):
        def callback():
            blockchain = BtcTxStore()
            wif = blockchain.create_key()
            address = blockchain.get_address(wif)
            farmer = Farmer(address)

            header_date = formatdate(timeval=mktime(datetime.now().timetuple())
                                     , localtime=True, usegmt=True)
            header_authorization = blockchain.sign_unicode(wif, "lalala-wrong")
            headers = {"Date": header_date,
                       "Authorization": header_authorization}
            farmer.authenticate(headers)
        self.assertRaises(storjcore.auth.AuthError, callback) 
Example #18
Source File: test_Farmer.py    From dataserv with MIT License 5 votes vote down vote up
def test_authentication_timeout_future_success(self):
        blockchain = BtcTxStore()
        wif = blockchain.create_key()
        address = blockchain.get_address(wif)
        farmer = Farmer(address)

        timeout = farmer.get_server_authentication_timeout() - 5

        date = datetime.now() + timedelta(seconds=timeout)
        header_date = formatdate(timeval=mktime(date.timetuple()),
                                 localtime=True, usegmt=True)
        message = farmer.get_server_address() + " " + header_date
        header_authorization = blockchain.sign_unicode(wif, message)
        headers = {"Date": header_date, "Authorization": header_authorization}
        self.assertTrue(farmer.authenticate(headers)) 
Example #19
Source File: test_Farmer.py    From dataserv with MIT License 5 votes vote down vote up
def test_authentication_no_date(self):
        def callback():
            blockchain = BtcTxStore()
            wif = blockchain.create_key()
            address = blockchain.get_address(wif)
            farmer = Farmer(address)

            header_date = formatdate(timeval=mktime(datetime.now().timetuple())
                                     , localtime=True, usegmt=True)
            message = farmer.get_server_address() + " " + header_date
            header_authorization = blockchain.sign_unicode(wif, message)
            headers = {"Date": None, "Authorization": header_authorization}
            farmer.authenticate(headers)
        self.assertRaises(storjcore.auth.AuthError, callback) 
Example #20
Source File: test_email_renamed.py    From oss-ftp with MIT License 5 votes vote down vote up
def test_formatdate(self):
        now = time.time()
        self.assertEqual(utils.parsedate(utils.formatdate(now))[:6],
                         time.gmtime(now)[:6]) 
Example #21
Source File: heuristics.py    From deepWordBug with Apache License 2.0 5 votes vote down vote up
def datetime_to_header(dt):
    return formatdate(calendar.timegm(dt.timetuple())) 
Example #22
Source File: heuristics.py    From pex with Apache License 2.0 5 votes vote down vote up
def datetime_to_header(dt):
    return formatdate(calendar.timegm(dt.timetuple())) 
Example #23
Source File: heuristics.py    From Safejumper-for-Desktop with GNU General Public License v2.0 5 votes vote down vote up
def datetime_to_header(dt):
    return formatdate(calendar.timegm(dt.timetuple())) 
Example #24
Source File: heuristics.py    From anpr with Creative Commons Attribution 4.0 International 5 votes vote down vote up
def datetime_to_header(dt):
    return formatdate(calendar.timegm(dt.timetuple())) 
Example #25
Source File: heuristics.py    From Mastering-Elasticsearch-7.0 with MIT License 5 votes vote down vote up
def datetime_to_header(dt):
    return formatdate(calendar.timegm(dt.timetuple())) 
Example #26
Source File: heuristics.py    From Mastering-Elasticsearch-7.0 with MIT License 5 votes vote down vote up
def datetime_to_header(dt):
    return formatdate(calendar.timegm(dt.timetuple())) 
Example #27
Source File: utils.py    From oss-ftp with MIT License 5 votes vote down vote up
def http_date(timeval=None):
    """返回符合HTTP标准的GMT时间字符串,用strftime的格式表示就是"%a, %d %b %Y %H:%M:%S GMT"。
    但不能使用strftime,因为strftime的结果是和locale相关的。
    """
    return formatdate(timeval, usegmt=True) 
Example #28
Source File: test_email_renamed.py    From oss-ftp with MIT License 5 votes vote down vote up
def test_formatdate_usegmt(self):
        now = time.time()
        self.assertEqual(
            utils.formatdate(now, localtime=False),
            time.strftime('%a, %d %b %Y %H:%M:%S -0000', time.gmtime(now)))
        self.assertEqual(
            utils.formatdate(now, localtime=False, usegmt=True),
            time.strftime('%a, %d %b %Y %H:%M:%S GMT', time.gmtime(now))) 
Example #29
Source File: test_email_renamed.py    From oss-ftp with MIT License 5 votes vote down vote up
def test_formatdate_localtime(self):
        now = time.time()
        self.assertEqual(
            utils.parsedate(utils.formatdate(now, localtime=True))[:6],
            time.localtime(now)[:6]) 
Example #30
Source File: __init__.py    From quart with MIT License 5 votes vote down vote up
def default(self, object_: Any) -> Any:
        if isinstance(object_, date):
            return formatdate(timeval=mktime((object_.timetuple())), localtime=False, usegmt=True)
        if isinstance(object_, UUID):
            return str(object_)
        if hasattr(object_, "__html__"):
            return str(object_.__html__())
        return super().default(object_)