def send_to_admin(serversmtp, frm, to, error, cur):
    logger.info('Send email about error to admin')
    # Get admin email address from database
    cur.execute("SELECT mb_value FROM `mb_properties` WHERE mb_field='Admin email'")
    admin = cur.fetchone()[0]
    # Create email fo admin
    msg = Message()
    msg.add_header('Subject', 'SRK DPIportal [Mail Sender] Impossible send email!')
    msg.add_header('Date', formatdate(localtime=True))
    msg.add_header('X-Mailer', 'MailSender')
    msg.add_header('Message-ID', make_msgid())
    msg.add_header('From', frm)
    msg.add_header('To', admin)
    msg.set_payload('Subject:' + msg['Subject'] + '\n'
                    'From:' + frm + '\n'
                    'To:' + admin + '\n\n'
                    'Impossible send email to ' + to + '\n'
                    'Error:\n' + error)
    try:
        serversmtp.sendmail(msg['From'],
                            msg['To'].split('; '),
                            msg.get_payload())
        logger.info('Mail was send to %s' % admin)
    except Exception as e:
        logger.error(str(e))
    logger.info('Impossible send email to admin %s' % admin)
Exemple #2
1
def send_auth_email(auth_token, destination, username, password):
    msg = Message()
    msg.add_header("subject", "Cathedral Admin Access")
    msg.set_payload(AUTH_EMAIL.format(auth_token=auth_token))

    server = smtplib.SMTP("smtp.gmail.com:587")
    server.starttls()

    server.login(username, password)
    server.sendmail(username, destination, msg.as_string())

    server.quit()
    def _prepare_payload(self):
        """Serializes a batch request body."""

        for qry in self.context.get_next_query():
            request = self.context.build_request()
            if isinstance(qry, ReadEntityQuery):
                self._get_requests.append(request)
                self._get_queries.append(qry)
            else:
                self._change_requests.append(request)

        main_message = Message()
        main_message.add_header("Content-Type", "multipart/mixed")
        main_message.set_boundary(self._current_boundary)

        if len(self._change_requests) > 0:
            change_set_message = Message()
            change_set_boundary = _create_boundary("changeset_", True)
            change_set_message.add_header("Content-Type", "multipart/mixed")
            change_set_message.set_boundary(change_set_boundary)

            for request in self._change_requests:
                part_message = self._serialize_request(request)
                change_set_message.attach(part_message)
            main_message.attach(change_set_message)

        for request in self._get_requests:
            part_message = self._serialize_request(request)
            main_message.attach(part_message)

        return main_message
Exemple #4
0
def control_to_metadata(control_dir, wheel_dir):
    """Convert deb control to METADATA file."""
    ctrl_info = read_control(control_dir)
    pkg_name = ctrl_info['Package'].replace('-', '_')
    pkg_version = re.search(r'\d.*', ctrl_info['Version'].replace('-', '_'))
    pkg_string = "%s-%s" % (pkg_name, pkg_version)

    metadata = Message()
    metadata.add_header('Metadata-Version', '2.0')
    metadata['Name'] = ctrl_info['Package']
    metadata['Version'] = pkg_version
    metadata['Home-page'] = ctrl_info['Homepage']

    # get maintainer name and email
    maintainer_pattern = r'\s*(?P<maintainer>.*?)\s*?\<(?P<m_email>.*?)\>'
    re_results = re.search(maintainer_pattern, ctrl_info['Maintainer'])
    metadata['Author'] = re_results.group('maintainer')
    metadata['Author-email'] = re_results.group('m_email')

    metadata['Summary'] = ctrl_info['Description'].split('\n', 1)[0]
    metadata['Description'] = ctrl_info['Description']

    # Write wheelfile
    dist_info_dir = wheel_dir + "/" + pkg_string + ".dist-info"
    os.mkdir(dist_info_dir)
    metadata_path = os.path.join(dist_info_dir, 'METADATA')
    write_pkg_info(metadata_path, metadata)

    return (pkg_name, pkg_version)
Exemple #5
0
def limit_reached_alert(user, limit_type, limit, value):
    """
    Send out a notification when a limit is reached.

    :param user: The user who has hit the limit
    :type user: User
    :param limit_type: The type of limit that has been reached
    :type limit_type: str
    :param limit: The limit amount
    :type limit: int
    :param value: The number of messages sent
    :type value: int
    """

    name = get_config('alerts_name')
    faddr = get_config('alerts_from')
    taddr = get_config('alerts_to')

    message = MIMEMessage()
    message.add_header('From', '"%s" <%s>' % (name, faddr))
    if isinstance(taddr, list):
        message.add_header('To', ', '.join(taddr))
    else:
        message.add_header('To', taddr)
    message.add_header('Date', formatdate())
    message.add_header('Subject', 'User %s reached sending limit' % user.email)
    message.set_payload("""Hi,

The user has reached their %s limit of sending messages. They have sent %d
messages and have a limit of %d""" % (limit_type, value, limit))

    # Send the message to the local SMTP server
    smtp = smtplib.SMTP('localhost')
    smtp.sendmail(faddr, taddr, str(message))
    smtp.close()
Exemple #6
0
    def urlgetcontent(self, container, url, data = None, method = None, headers = {}, tostr = False,  encoding = None, rawurl = False, *args, **kwargs):
        '''
        In Python2, bytes = str, so tostr and encoding has no effect.
        In Python3, bytes are decoded into unicode str with encoding.
        If encoding is not specified, charset in content-type is used if present, or default to utf-8 if not.
        See open for available arguments

        :param rawurl: if True, assume the url is already url-encoded, do not encode it again.
        '''
        req = Request(url, data, method, headers, rawurl = rawurl)
        for m in self.open(container, req, *args, **kwargs):
            yield m
        resp = container.retvalue
        encoding = 'utf-8'
        if encoding is None:
            m = Message()
            m.add_header('Content-Type', resp.get_header('Content-Type', 'text/html'))
            encoding = m.get_content_charset('utf-8')
        if not resp.stream:
            content = b''
        else:
            for m in resp.stream.read(container):
                yield m
            content = container.data
        if tostr:
            content = _str(content, encoding)
        container.retvalue = content
Exemple #7
0
    def _get_email_mesg(self, header, body):
        """ Return an email message.

        Create an email message object from the provided header and body
        and return the email message object.

        Params
        ======
            header: Dictionary contain email message header contents.
            body: Either a string or a file containing the body of the message.

        Return
        ======
            A valid email message object ready to send via SMTP.
        """
        from email.message import Message

        mesg = Message()
        for h,v in header.items():
            mesg.add_header(h, v)

        try:
            mesg.set_payload(body.read())
        except AttributeError:
            mesg.set_payload(body)

        return mesg
Exemple #8
0
    def __thread_send_email(email_subject, email_from, email_from_password,
                            email_to, email_content, email_smtp_host,
                            email_smtp_port):
        msg = Message()

        msg['Subject'] = email_subject
        msg['From'] = email_from
        msg['To'] = email_to

        msg.add_header('Content-Type', 'text/html')
        msg.set_payload(email_content)

        logging.info('send_email() - sending an e-mail to `%s`...', email_to)

        try:
            s = SMTP(host=email_smtp_host, port=email_smtp_port)
            s.starttls()
            s.login(msg['From'], email_from_password)
            s.sendmail(msg['From'], [msg['To']], msg.as_string())
            s.quit()

            logging.info(
                'send_email() - e-mail to `%s` has been sent successfully!',
                email_to)
        except SMTPException as error:
            logging.error('send_email() - unable to send an e-mail to `%s`.',
                          email_to)
            logging.error('send_email() - error: `%s`.', error)
            raise error
Exemple #9
0
    def _serialize_request(request):
        """Serializes a part of a batch request to a string. A part can be either a GET request or
            a change set grouping several CUD (create, update, delete) requests.

        :type request: RequestOptions
        """
        eol = "\r\n"
        method = request.method
        if "X-HTTP-Method" in request.headers:
            method = request.headers["X-HTTP-Method"]
        lines = [
            "{method} {url} HTTP/1.1".format(method=method, url=request.url),
            *[':'.join(h) for h in request.headers.items()]
        ]
        if request.data:
            lines.append(eol)
            lines.append(json.dumps(request.data))
        buffer = eol + eol.join(lines) + eol
        payload = buffer.encode('utf-8').lstrip()

        message = Message()
        message.add_header("Content-Type", "application/http")
        message.add_header("Content-Transfer-Encoding", "binary")
        message.set_payload(payload)
        return message
Exemple #10
0
def enviar_email(data, paciente, medico, contato, sistema_operacional,
                 data_resp):
    hoje = date.today()
    server = smtplib.SMTP('smtp.gmail.com:587')
    email_content = f'''
  <p>Prezado(a){paciente},</p>

  </p>Segue o resultado da analise do seu exame realizado pela nossa inteligencia artificial no dia: {hoje}</p>

  {data_resp.to_html()}

  </p> De acordo com a inteligencia utilizada, seu diagnostico foi {data} para diabetes.</p>

  </p>A nossa equipe sugere que o(a) paciente, procure o(a) Dr.(a) {medico}.</p>

  <p>Grato,Equipe Vinicius Mattoso</p>'''

    msg = Message()
    msg['Subject'] = f'Resultado do exame avaliado no dia: {hoje}'

    msg['From'] = sistema_operacional.email
    msg['To'] = contato
    password = sistema_operacional.key
    msg.add_header('Content-Type', 'text/html')
    msg.set_payload(email_content)

    s = smtplib.SMTP('smtp.gmail.com: 587')
    s.starttls()
    # Login Credentials for sending the mail
    s.login(msg['From'], password)
    s.sendmail(msg['From'], [msg['To']], msg.as_string().encode('utf-8'))
Exemple #11
0
 def urlgetcontent(self,
                   container,
                   url,
                   data=None,
                   method=None,
                   headers={},
                   tostr=False,
                   encoding=None,
                   *args,
                   **kwargs):
     '''
     In Python2, bytes = str, so tostr and encoding has no effect.
     In Python3, bytes are decoded into unicode str with encoding.
     If encoding is not specified, charset in content-type is used if present, or default to utf-8 if not.
     See open for available arguments
     '''
     req = Request(url, data, method, headers)
     for m in self.open(container, req, *args, **kwargs):
         yield m
     resp = container.retvalue
     encoding = 'utf-8'
     if encoding is None:
         m = Message()
         m.add_header('Content-Type',
                      resp.get_header('Content-Type', 'text/html'))
         encoding = m.get_content_charset('utf-8')
     if not resp.stream:
         content = b''
     else:
         for m in resp.stream.read(container):
             yield m
         content = container.data
     if tostr:
         content = _str(content, encoding)
     container.retvalue = content
Exemple #12
0
    def https_open(self, request):
        global disable_network
        if disable_network:
            raise URLError('Network access is disabled')

        url = request.get_full_url()
        data = GetRequestData(request)
        digest = DigestFromRequest(request)
        response_file_path = os.path.join(RESPONSE_DATA_DIR, digest)

        requests_seen.append(request)

        if os.path.exists(response_file_path):
            f = open(response_file_path, mode='rb')
            m = Message()
            m.add_header('Content-Type', 'application/json')
            resp = addinfourl(f, headers=m, url=url, code=200)
            resp.msg = 'Success'
            resp.code = 200
            return resp

        # The file was not there. Create a missing resource file.
        missing_response_file_path = os.path.join(RESPONSE_DATA_DIR,
                                                  '{}.missing'.format(digest))
        with open(missing_response_file_path, mode='wb') as f:
            s = json.dumps({
                "url": url,
                "data": StringFromBytes(data),
                "digest": digest
            })
            f.write(s.encode('utf-8'))

        raise URLError(
            'URL is not cached. Created missing request record: {}.missing'.
            format(digest))
Exemple #13
0
    async def urlgetcontent(self,
                            container,
                            url,
                            data=None,
                            method=None,
                            headers={},
                            tostr=False,
                            encoding=None,
                            rawurl=False,
                            *args,
                            **kwargs):
        '''
        In Python2, bytes = str, so tostr and encoding has no effect.
        In Python3, bytes are decoded into unicode str with encoding.
        If encoding is not specified, charset in content-type is used if present, or default to utf-8 if not.
        See open for available arguments

        :param rawurl: if True, assume the url is already url-encoded, do not encode it again.
        '''
        req = Request(url, data, method, headers, rawurl=rawurl)
        with (await self.open(container, req, *args, **kwargs)) as resp:
            encoding = 'utf-8'
            if encoding is None:
                m = Message()
                m.add_header('Content-Type',
                             resp.get_header('Content-Type', 'text/html'))
                encoding = m.get_content_charset('utf-8')
            if not resp.stream:
                content = b''
            else:
                content = await resp.stream.read(container)
            if tostr:
                content = _str(content, encoding)
            return content
    def _construct_multipart_request(self, request):
        """
        :type request: office365.runtime.http.request_options.RequestOptions
        """
        request.method = HttpMethod.Post
        boundary = create_boundary("PageBoundary", True)
        request.set_header(
            "Content-Type",
            "multipart/form-data; boundary={0}".format(boundary))

        main_message = Message()
        main_message.add_header(
            "Content-Type",
            "multipart/form-data; boundary={0}".format(boundary))
        main_message.set_boundary(boundary)

        c_type, enc = get_mime_type(self._presentation.name)
        presentation_message = Message()
        presentation_message.add_header("Content-Type", c_type)
        presentation_message.add_header("Content-Disposition",
                                        "form-data; name=\"Presentation\"")
        presentation_message.set_payload(self._presentation.read())
        main_message.attach(presentation_message)

        for name, file in self._files.items():
            file_message = Message()
            c_type, enc = get_mime_type(file.name)
            file_message.add_header("Content-Type", c_type)
            file_message.add_header("Content-Disposition",
                                    "form-data; name=\"{0}\"".format(name))
            file_content = file.read()
            file_message.set_payload(file_content)
            main_message.attach(file_message)

        request.data = _message_to_payload(main_message)
Exemple #15
0
    def _prepare_payload(self):
        """
        Serializes a batch request body.
        """
        main_message = Message()
        main_message.add_header("Content-Type", "multipart/mixed")
        main_message.set_boundary(self.current_query.current_boundary)

        if self.current_query.has_change_sets:
            change_set_message = Message()
            change_set_boundary = create_boundary("changeset_", True)
            change_set_message.add_header("Content-Type", "multipart/mixed")
            change_set_message.set_boundary(change_set_boundary)

            for qry in self.current_query.change_sets:
                request = qry.build_request()
                message = self._serialize_request(request)
                change_set_message.attach(message)
            main_message.attach(change_set_message)

        for qry in self.current_query.get_queries:
            request = qry.build_request()
            message = self._serialize_request(request)
            main_message.attach(message)

        return message_as_bytes_or_string(main_message)
 def test_encode_subject(self):
     email = Message()
     email.add_header('Subject', 'Vielen Dank für Ihren Fahrkartenkauf! (Auftrag TSYLM7)')
     email.add_header('From', '_value')
     email['categorized'] = {}
     out_mail = EmailCleanup('_from', 'to', '%(outro)s').prepare_outbound(email)
     self.assertEqual(str(out_mail['Subject']),
                      '=?iso-8859-1?q?=28was=3A_Vielen_Dank_f=FCr_Ihren_Fahrkartenkauf!_=28Auftr?=\n =?iso-8859-1?q?ag_TSYLM7=29=29?=')
def create_message(sender_email: str, receiver_email: str, subject: str, html_body):
    message = Message()
    message["Subject"] = subject
    message["From"] = sender_email
    message["To"] = receiver_email
    message.add_header('Content-Type', 'text/html')
    message.set_payload(html_body)
    return message
Exemple #18
0
 def addmimeblob(self, blob, mimetype, filename):
     attach = Message()
     attach['Content-Type'] = mimetype
     attach.add_header('Content-Disposition', 'inline', filename=filename)
     attach.set_payload(blob)
     encode_base64(attach)
     self._endtext()
     self._attached.append(attach)
Exemple #19
0
def write_headers(socket, headers):
    if headers:
        msg = Message()
        for key, values in normalized_headers(headers.items()).iteritems():
            for value in values:
                msg.add_header(key, value)
        header_data = msg.as_string()
        yield socket.sendall(header_data.rstrip("\n").replace("\n", "\r\n") + "\r\n")
    yield socket.sendall("\r\n")
 def send_mail(self, recipient, payload, subject=None):
     msg = Message()
     msg['Subject'] = subject
     msg['From'] = Environment().mail_username
     msg['To'] = recipient
     msg.add_header('Content-Type', 'text/html')
     msg.set_payload(payload)
     self.server.sendmail(Environment().mail_username, recipient,
                          msg.as_string())
Exemple #21
0
    def test_unit__decoded_mail__check_validity_for_comment_content__err__is_autoreply_email(
        self, header_name, header_value
    ):
        message = Message()
        message.add_header(header_name, header_value)

        uid = 1
        decodedmail = DecodedMail(message, uid)
        with pytest.raises(AutoReplyEmailNotAllowed):
            decodedmail.check_validity_for_comment_content()
Exemple #22
0
def _find_content_encoding(response, default='iso8859-1'):
    from email.message import Message
    content_type = response.headers.get('Content-Type')
    if content_type:
        msg = Message()
        msg.add_header('Content-Type', content_type)
        charset = msg.get_content_charset(default)
    else:
        charset = default
    return charset
Exemple #23
0
def _find_content_encoding(response, default='iso8859-1'):
    from email.message import Message
    content_type = response.headers.get('Content-Type')
    if content_type:
        msg = Message()
        msg.add_header('Content-Type', content_type)
        charset = msg.get_content_charset(default)
    else:
        charset = default
    return charset
Exemple #24
0
 def message_from_record(self, record):
     from email.message import Message
     msg = Message()
     lineiter = iter(self.format(record).splitlines())
     for line in lineiter:
         if not line:
             break
         pieces = line.split(':', 1)
         msg.add_header(*[x.strip() for x in pieces])
     msg.set_payload('\r\n'.join(lineiter))
     return msg
Exemple #25
0
def send_mail(from_addr, to_addr, subject, body):

    msg = Message()
    msg['Subject'] = subject
    msg['From'] = from_addr
    msg['To'] = to_addr if isinstance(to_addr, str) else ', '.join(to_addr)
    msg.add_header('Content-Type', 'text/html')
    msg.set_payload(body)

    smtp = SMTP('localhost')
    smtp.sendmail(from_addr, to_addr, msg.as_string())
    smtp.quit()
Exemple #26
0
def prepare_message(
    sender_: EmailAddress,
    recipient_: EmailAddress,
    subject: typing.Text,
    text: typing.Text,
) -> MIMEBase:

    sender = Address(sender_.name, addr_spec=sender_.address)
    recipient = Address(recipient_.name, addr_spec=recipient_.address)

    html = markdown.markdown(text)

    plaintext_message = EmailMessage()
    plaintext_message["Subject"] = subject
    plaintext_message["From"] = sender
    plaintext_message["To"] = (recipient, )
    plaintext_message.set_content(text)

    plaintext_message.add_alternative(html, subtype="html")

    encrypted_text = encrypt_text(recipient.addr_spec,
                                  plaintext_message.as_string())

    encrypted_message = MIMEBase(_maintype="multipart",
                                 _subtype="encrypted",
                                 protocol="application/pgp-encrypted")
    encrypted_message["Subject"] = subject
    encrypted_message["From"] = str(sender)
    encrypted_message["To"] = str(recipient)

    encrypted_message_part1 = Message()
    encrypted_message_part1.add_header(_name="Content-Type",
                                       _value="application/pgp-encrypted")
    encrypted_message_part1.add_header(
        _name="Content-Description", _value="PGP/MIME version identification")
    encrypted_message_part1.set_payload("Version: 1" + "\n")

    encrypted_message_part2 = Message()
    encrypted_message_part2.add_header(_name="Content-Type",
                                       _value="application/octet-stream",
                                       name="encrypted.asc")
    encrypted_message_part2.add_header(_name="Content-Description",
                                       _value="OpenPGP encrypted message")
    encrypted_message_part2.add_header(_name="Content-Disposition",
                                       _value="inline",
                                       filename="encrypted.asc")
    encrypted_message_part2.set_payload(encrypted_text)

    encrypted_message.attach(encrypted_message_part1)
    encrypted_message.attach(encrypted_message_part2)

    return encrypted_message
Exemple #27
0
def sendMail():
    # Initializing SMTP
    s = smtplib.SMTP('smtp.gmail.com', 587)

    # start TLS for security
    s.starttls()

    # Mail ID and credential from where all the mails will be sent are to be given here
    # USE CHRIST ID!!! Personal mails have restrictions on the number of mails that can be sent
    s.login("Your Mail ID Ex- [email protected]",
            "Your Password")

    # The content variable will hold the JSON request body
    content = request.get_json()

    # Access the otp field that is within the JSON request
    otp = content['otp']
    # Access the email field that is within the JSON request
    email = content['email']

    # Email content definition
    email_cont = """
        <html>
          <head>  
          <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
          <title>Open Elective OTP</title>
          </head>
          <body>
          <h1>Your Open Elective authentication OTP is <strong>""" + otp + """</strong></h1>
          </body>
        </html>
        """

    # Construction of the message to be sent
    msg = Message()
    msg['Subject'] = "Open Elective OTP"
    msg['From'] = 'CHRIST (Deemed to be University)'
    msg['To'] = 'You'
    msg.add_header('Content-Type', 'text/html')
    msg.set_payload(email_cont)

    # Sending the Mail
    # The mail ID specified above to be given here again
    s.sendmail("Your Mail ID Ex- [email protected]",
               email, msg.as_string())

    # Close SMTP session
    s.quit()

    # Sends a success response
    resp = jsonify(success=True)
    return resp
Exemple #28
0
def create_msg(v,rcptlist=None,origmsg=None,template=None):
  """Create a DSN message from a template.  Template must be '\n' separated.
     v - an object whose attributes are used for substitutions.  Must
       have sender and receiver attributes at a minimum.
     rcptlist - used to set v.rcpt if given
     origmsg - used to set v.subject and v.spf_result if given
     template - a '\n' separated string with python '%(name)s' substitutions.
  """
  if not template:
    return None
  if hasattr(v,'perm_error'):
    # likely to be an spf.query, try translating for backward compatibility
    q = v
    v = Vars()
    try:
      v.heloname = q.h
      v.sender = q.s
      v.connectip = q.i
      v.receiver = q.r
      v.sender_domain = q.o
      v.result = q.result
      v.perm_error = q.perm_error
    except: v = q
  if rcptlist:
    v.rcpt = '\n\t'.join(rcptlist)
  if origmsg:
    try: v.subject = origmsg['Subject']
    except: v.subject = '(none)'
    try:
      v.spf_result = origmsg['Received-SPF']
    except: v.spf_result = None

  msg = Message()

  msg.add_header('X-Mailer','PyMilter-'+Milter.__version__)
  msg.set_type('text/plain')

  hdrs,body = template.split('\n\n',1)
  for ln in hdrs.splitlines():
    name,val = ln.split(':',1)
    msg.add_header(name,(val % v.__dict__).strip())
  msg.set_payload(body % v.__dict__)
  # add headers if missing from old template
  if 'to' not in msg:
    msg.add_header('To',v.sender)
  if 'from' not in msg:
    msg.add_header('From','postmaster@%s'%v.receiver)
  if 'auto-submitted' not in msg:
    msg.add_header('Auto-Submitted','auto-generated')
  return msg
Exemple #29
0
 def test_attachment_name_badly_encoded(self):
     msg = Message()
     msg["From"] = "*****@*****.**"
     msg["Message-ID"] = "<dummy>"
     msg.set_payload(b"Dummy content")
     msg.add_header(b'Content-Disposition', b'attachment', filename=b'non-ascii-\xb8\xb1\xb1\xbe.jpg')
     scrubber = Scrubber("*****@*****.**", msg)
     try:
         attachments = scrubber.scrub()[1]
     except UnicodeDecodeError:
         print(format_exc())
         self.fail("Could not decode the filename")
     self.assertEqual(attachments,
             [(0, u'attachment.bin', 'text/plain', None, b'Dummy content')])
Exemple #30
0
def send_sms(data):
    text, coding, parts_count = detect_coding(data['text'])

    result = {
        'sent_text': data['text'],
        'parts_count': parts_count,
        'mobiles': {}
    }

    for mobile in data['mobiles']:
        # generate message_id
        message_id = str(uuid.uuid4())

        result['mobiles'][mobile] = {}
        result['mobiles'][mobile]['message_id'] = message_id
        result['mobiles'][mobile]['dlr_status'] = os.path.join(
            os.path.dirname(request.url),
            os.path.basename(current_app.config['SENT']), message_id)

        if not validate_mobile(mobile):
            current_app.logger.info(
                'Message from [%s] to [%s] have invalid mobile number' %
                (auth.username(), mobile))
            result['mobiles'][mobile][
                'response'] = 'Failed: invalid mobile number'
            continue

        if access_mobile(mobile):
            lock_file = os.path.join(current_app.config['OUTGOING'],
                                     message_id + '.LOCK')
            m = Message()
            m.add_header('From', auth.username())
            m.add_header('To', mobile)
            m.add_header('Alphabet', coding)
            if data.get('queue'):
                result.update({'queue': data['queue']})
                m.add_header('Queue', result.get('queue'))
            m.set_payload(text)

            with open(lock_file, write_mode) as fp:
                if use_python3:
                    fp.write(m.as_bytes())
                else:
                    fp.write(m.as_string())

            msg_file = lock_file.split('.LOCK')[0]
            os.rename(lock_file, msg_file)
            os.chmod(msg_file, 0o660)
            current_app.logger.info(
                'Message from [%s] to [%s] placed to the spooler as [%s]' %
                (auth.username(), mobile, msg_file))
            result['mobiles'][mobile]['response'] = 'Ok'
        else:
            current_app.logger.info(
                'Message from [%s] to [%s] have forbidden mobile number' %
                (auth.username(), mobile))
            result['mobiles'][mobile][
                'response'] = 'Failed: forbidden mobile number'

    return result
Exemple #31
0
def gut_message(message: Message) -> Message:
    """
    Remove body from a message, and wrap in a message/external-body.
    """
    wrapper = Message()
    wrapper.add_header('Content-Type',
                       'message/external-body',
                       access_type='x-spam-deleted',
                       expiration=time.strftime("%a, %d %b %Y %H:%M:%S %z"),
                       size=str(len(message.get_payload())))

    message.set_payload('')
    wrapper.set_payload([message])

    return wrapper
 def test_attachment_name_badly_encoded(self):
     msg = Message()
     msg["From"] = "*****@*****.**"
     msg["Message-ID"] = "<dummy>"
     msg.set_payload(b"Dummy content")
     msg.add_header(b'Content-Disposition', b'attachment',
                    filename=b'non-ascii-\xb8\xb1\xb1\xbe.jpg')
     scrubber = Scrubber(msg)
     try:
         attachments = scrubber.scrub()[1]
     except UnicodeDecodeError:
         print(format_exc())
         self.fail("Could not decode the filename")
     self.assertEqual(
         attachments,
         [(0, u'attachment.bin', 'text/plain', None, b'Dummy content')])
 def add_payload(message, obj):
     payload = Message()
     encoding = obj.get("encoding", "utf-8")
     if encoding and (encoding.upper() in ("BASE64", "7BIT", "8BIT", "BINARY")):
         payload.add_header("Content-Transfer-Encoding", encoding)
     else:
         payload.set_charset(encoding)
     mime = obj.get("mime", None)
     if mime:
         payload.set_type(mime)
     if "text" in obj:
         payload.set_payload(obj["text"])
     elif "payload" in obj:
         payload.set_payload(obj["payload"])
     if "filename" in obj and obj["filename"]:
         payload.add_header("Content-Disposition", "attachment", filename=obj["filename"])
     message.attach(payload)
Exemple #34
0
def ftp_listdir(url):
    assert url.lower().startswith('ftp://')
    from email.message import Message
    res = urlopen(url)
    content_type = res.headers.get('Content-Type')
    if content_type:
        msg = Message()
        msg.add_header('Content-Type', content_type)
        charset = msg.get_content_charset('utf-8')
    else:
        charset = 'utf-8'
    if content_type and content_type.startswith('text/html'):
        files = parse_html_ftplist(res.read().decode(charset))
    else:
        files = parse_text_ftplist(res.read().decode(charset))
    res.close()
    return files
Exemple #35
0
def emsg(kv):
    from email.message import Message
    from email.generator import Generator
    from StringIO import StringIO

    m = Message()
    m['Content-type'] = 'multipart/formdata'
    for k,v in kv.items():
        p = Message()
        p.add_header('Content-Disposition', 'form-data', name=k)
        p.set_payload(v)
        m.attach(p)
#print m.as_string()
    fp = StringIO()
    g = Generator(fp)
    g.flatten(m)
    return fp.getvalue()
Exemple #36
0
def ftp_listdir(url):
    assert url.lower().startswith('ftp://')
    from email.message import Message
    res = urlopen(url)
    content_type = res.headers.get('Content-Type')
    if content_type:
        msg = Message()
        msg.add_header('Content-Type', content_type)
        charset = msg.get_content_charset('utf-8')
    else:
        charset = 'utf-8'
    if content_type and content_type.startswith('text/html'):
        files = parse_html_ftplist(res.read().decode(charset))
    else:
        files = parse_text_ftplist(res.read().decode(charset))
    res.close()
    return files
Exemple #37
0
 def build_message(self, subject=None, body=None):
     email = Message()
     email.add_header("From", self.myself)
     email.add_header("To", self.myself)
     email.add_header("Date", formatdate(None, self.use_local_timezone))
     if subject is not None:
         email.add_header("Subject", subject)
     if body is not None:
         email.set_payload(body)
     return email
Exemple #38
0
def _prepare_message(txt):
    """ Apply the proper encoding to all email fields.
        The body will be Latin-1, the headers will be 'quopri'd when necessary.
    """
    def plain(val):
        """ Return True when val is plain ASCII """
        try:
            val.decode('ascii')
            return True
        except:
            return False

    # Use Latin-1 because not all email clients know UTF-8.
    code = 'ISO-8859-1'

    msg = Message()
    payload = []
    body = False
    header = False
    for line in txt.encode(code, 'replace').split('\n'):
        if header and not line:
            body = True
        if body:
            payload.append(line)
        else:
            m = RE_HEADER.search(line)
            if m:
                header = True
                keyword = m.group(1).strip()
                value = m.group(2).strip()
                if plain(value):
                    # Don't encode if not needed, because some email clients
                    # choke when headers like "date" are encoded.
                    msg.add_header(keyword, value)
                else:
                    header = Header(value, code)
                    msg[keyword] = header

    msg.set_payload('\n'.join(payload), code)

    # Check for proper encoding, else call it explicitly
    if not msg.has_key('Content-Transfer-Encoding'):
        encode_quopri(msg)

    return msg.as_string()
Exemple #39
0
def _prepare_message(txt):
    """ Apply the proper encoding to all email fields.
        The body will be Latin-1, the headers will be 'quopri'd when necessary.
    """
    def plain(val):
        """ Return True when val is plain ASCII """
        try:
            val.decode('ascii')
            return True
        except:
            return False

    # Use Latin-1 because not all email clients know UTF-8.
    code = 'ISO-8859-1'

    msg = Message()
    payload = []
    body = False
    header = False
    for line in txt.encode(code, 'replace').split('\n'):
        if header and not line:
            body = True
        if body:
            payload.append(line)
        else:
            m = RE_HEADER.search(line)
            if m:
                header = True
                keyword = m.group(1).strip()
                value = m.group(2).strip()
                if plain(value):
                    # Don't encode if not needed, because some email clients
                    # choke when headers like "date" are encoded.
                    msg.add_header(keyword, value)
                else:
                    header = Header(value, code)
                    msg[keyword] = header

    msg.set_payload('\n'.join(payload), code)

    # Check for proper encoding, else call it explicitly
    if not msg.has_key('Content-Transfer-Encoding'):
        encode_quopri(msg)

    return msg.as_string()
Exemple #40
0
def multipart_form_message(images, form_data={}):
  """Return a MIMEMultipart message to upload images via an HTTP form POST request.

  Args:
    images: a list of (encoded_image, filename) tuples.
    form_data: dict of name, value form fields.
  """
  message = MIMEMultipart('form-data', None)
  for name, val in form_data.iteritems():
    part = Message()
    part.add_header('Content-Disposition', 'form-data', name=name)
    part.set_payload(val)
    message.attach(part)

  for im, filename in images:
    message.attach(form_data_image(im, filename))

  return message
    def addMail(self, body="", filename="foo", to=ADDRESS,
                frm="*****@*****.**", subject="sent subject",
                headers={}):
        msg = Message()
        msg.add_header("To", to)
        msg.add_header(
            "Delivered-To", UUID + "@deliver.local")
        msg.add_header("From", frm)
        msg.add_header("Subject", subject)
        for header, value in headers.iteritems():
            msg.add_header(header, value)
        msg.set_payload(body)

        path = os.path.join(self.directory, "new", filename)
        with open(path, "w") as f:
            f.write(msg.as_string())

        return msg.as_string(), path
Exemple #42
0
    def test_sendmail_with_email_header(self):
        """Check the timeline is ok even if there is an email.header.Header.

        See https://bugs.launchpad.net/launchpad/+bug/885972
        """
        fake_mailer = RecordingMailer()
        self.useFixture(ZopeUtilityFixture(fake_mailer, IMailDelivery, 'Mail'))
        subject_str = self.getUniqueString('subject')
        subject_header = email.header.Header(subject_str)
        message = Message()
        message.add_header('From', '*****@*****.**')
        message['Subject'] = subject_header
        message.add_header('To', '*****@*****.**')
        with CaptureTimeline() as ctl:
            sendmail.sendmail(message)
        self.assertEqual(fake_mailer.from_addr, '*****@*****.**')
        self.assertEqual(fake_mailer.to_addr, ['*****@*****.**'])
        self.checkTimelineHasOneMailAction(ctl.timeline, subject=subject_str)
Exemple #43
0
 def message_from_record(self, record, suppressed):
     """Creates a new message for a record as email message object
     (:class:`email.message.Message`).  `suppressed` is the number
     of mails not sent if the `record_limit` feature is active.
     """
     from email.message import Message
     msg = Message()
     lineiter = iter(self.format(record).splitlines())
     for line in lineiter:
         if not line:
             break
         pieces = line.split(':', 1)
         msg.add_header(*[x.strip() for x in pieces])
     body = '\r\n'.join(lineiter)
     if suppressed:
         body += '\r\n\r\nThis message occurred additional %d ' \
                 'time(s) and was suppressed' % suppressed
     msg.set_payload(body)
     return msg
 def add_payload(message, obj):
     payload = Message()
     encoding = obj.get("encoding", "utf-8")
     if encoding and (encoding.upper() in ("BASE64", "7BIT", "8BIT", "BINARY")):
         payload.add_header("Content-Transfer-Encoding", encoding)
     else:
         payload.set_charset(encoding)
     mime = obj.get("mime", None)
     if mime:
         payload.set_type(mime)
     if "text" in obj:
         payload.set_payload(obj["text"])
     elif "payload" in obj:
         payload.set_payload(obj["payload"])
     if "filename" in obj and obj["filename"]:
         payload.add_header(
             "Content-Disposition", "attachment", filename=obj["filename"]
         )
     message.attach(payload)
Exemple #45
0
def multipart_form_message(media, form_data={}):
    """Return a MIMEMultipart message to upload encoded media via an HTTP form POST request.

  Args:
    media: a list of (encoded_data, filename) tuples.
    form_data: dict of name, value form fields.
  """
    message = MIMEMultipart("form-data", None)
    if form_data:
        for name, val in form_data.iteritems():
            part = Message()
            part.add_header("Content-Disposition", "form-data", name=name)
            part.set_payload(val)
            message.attach(part)

    for im, filename in media:
        message.attach(form_data_media(im, filename))

    return message
Exemple #46
0
 def read(self, length=None):
     offset = self._offset
     byte_range = 'bytes=%d-' % offset
     if length is not None:
         byte_range += '%d' % (offset + length)
     response = self._request('GET', {
         'Range': byte_range,
         'Accept-Encoding': ', '.join(decode_dict),
     })
     try:
         status = response.status
         if status in GOOD_STATUS_SET:
             length = response.getheader('content-length')
             if (
                 length is None or
                 status == httplib.REQUESTED_RANGE_NOT_SATISFIABLE
             ):
                 body = b''
             else:
                 encoding = response.getheader(
                     'content-encoding',
                     'identity',
                 ).lower()
                 body = response.read(int(length))
                 if encoding != 'identity':
                     body = decode_dict[encoding](body)
                 self._offset += len(body)
                 # On python3, response.msg is an email.message.Message
                 # instance, but not on python2. So align with python2.
                 encoding_parser = Message()
                 encoding_parser.add_header(
                     'content-type',
                     response.getheader('content-type', 'text/plain'),
                 )
                 self.encoding = encoding_parser.get_content_charset(
                     self.encoding,
                 )
             return body
     finally:
         response.close()
     if status in TEMPFAIL_STATUS_SET:
         raise HTTPFileTempFail(status)
     raise HTTPFileError(status)
    def send(self, message: Message, envelop: Envelop):
        message['Subject'] = envelop.subject
        message['From'] = envelop.from_addr
        message['To'] = envelop.to_addr

        if envelop.cc_addr:
            message['Cc'] = envelop.cc_addr
        if envelop.bcc_addr:
            message['Bcc'] = envelop.bcc_addr

        if envelop.headers:
            for k, v in envelop.headers.items():
                if k in message:
                    message.replace_header(k, v)
                else:
                    message.add_header(k, v)

        # https://pybit.es/python-MIME-bcc.html
        return self._smtp_sender.send_message(message)
Exemple #48
0
def multipart_form_message(media, form_data={}):
    """Return a MIMEMultipart message to upload encoded media via an HTTP form POST request.

  Args:
    media: a list of (encoded_data, filename) tuples.
    form_data: dict of name, value form fields.
  """
    message = MIMEMultipart('form-data', None)
    if form_data:
        for (name, val) in iteritems(form_data):
            part = Message()
            part.add_header('Content-Disposition', 'form-data', name=name)
            part.set_payload(val)
            message.attach(part)

    for im, filename in media:
        message.attach(form_data_media(im, filename))

    return message
Exemple #49
0
def add_dkim_signature(msg: Message, email_domain: str):
    if msg["DKIM-Signature"]:
        LOG.d("Remove DKIM-Signature %s", msg["DKIM-Signature"])
        del msg["DKIM-Signature"]

    # Specify headers in "byte" form
    # Generate message signature
    sig = dkim.sign(
        msg.as_string().encode(),
        DKIM_SELECTOR,
        email_domain.encode(),
        DKIM_PRIVATE_KEY.encode(),
        include_headers=DKIM_HEADERS,
    )
    sig = sig.decode()

    # remove linebreaks from sig
    sig = sig.replace("\n", " ").replace("\r", "")

    msg.add_header("DKIM-Signature", sig[len("DKIM-Signature: "):])
Exemple #50
0
def main(config):
    """main routine"""
    # Define the emails and couples
    # Only one sub-tuple level is supported
    emails = config['EMAILS']
    couples = config['COUPLES']
    sender = config['SENDER']
    content = config['CONTENT']

    # Find a random possible case
    persons = get_persons(couples)
    random_case = lets_do_santa_claus_job(couples)

    # Send mails
    message = Message()
    message.add_header('from', sender)
    message.add_header('subject','[Confidentiel] Message du Père-Noël')
    message.add_header('to', sender)

    server = smtplib.SMTP(config['MAIL_HOST'], config['MAIL_PORT'])
    server.starttls()
    server.login(config['MAIL_USERNAME'], config['MAIL_PASSWORD'])

    for i in range(len(persons)):
        recipients = emails[persons[i]]
        message.replace_header('to', recipients)
        message.set_payload(content.format(mail_receiver=persons[i], gift_receiver=random_case[i]))

        server.sendmail(sender, [recipients], message.as_string())
        print persons[i], ' => ', random_case[i]

    server.quit()
def send_sms(data):
    text, coding, parts_count = detect_coding(data['text'])

    result = {
        'sent_text': data['text'],
        'parts_count': parts_count,
        'mobiles': {}
    }

    for mobile in data['mobiles']:
        # generate message_id
        message_id = str(uuid.uuid4())

        result['mobiles'][mobile] = {}
        result['mobiles'][mobile]['message_id'] = message_id
        result['mobiles'][mobile]['dlr_status'] = os.path.join(os.path.dirname(request.url),
                                                  os.path.basename(current_app.config['SENT']), message_id)

        if not validate_mobile(mobile):
            current_app.logger.info('Message from [%s] to [%s] have invalid mobile number' % (auth.username(), mobile))
            result['mobiles'][mobile]['response'] = 'Failed: invalid mobile number'
            continue

        if access_mobile(mobile):
            lock_file = os.path.join(current_app.config['OUTGOING'], message_id + '.LOCK')
            m = Message()
            m.add_header('From', auth.username())
            m.add_header('To', mobile)
            m.add_header('Alphabet', coding)
            if data.get('queue'):
                result.update({'queue' : data['queue']})
                m.add_header('Queue', result.get('queue'))
            m.set_payload(text)

            with open(lock_file, write_mode) as fp:
                if use_python3:
                    fp.write(m.as_bytes())
                else:
                    fp.write(m.as_string())

            msg_file = lock_file.split('.LOCK')[0]
            os.rename(lock_file, msg_file)
            os.chmod(msg_file, 0o660)
            current_app.logger.info('Message from [%s] to [%s] placed to the spooler as [%s]' % (auth.username(), mobile, msg_file))
            result['mobiles'][mobile]['response'] = 'Ok'
        else:
            current_app.logger.info('Message from [%s] to [%s] have forbidden mobile number' % (auth.username(), mobile))
            result['mobiles'][mobile]['response'] = 'Failed: forbidden mobile number'

    return result
Exemple #52
0
 def toEmail(self):
   try:
     msg = Message()
     msg.add_header('From', self.sender)
     msg.add_header('Subject', self.subject)
     msg.add_header('Date', str(self.date))
     msg.add_header('To', self.receiver)
     msg.add_header('Sms-Id', self.sms_id)
     msg.set_payload(self.body)
     msg.timestamp = time.localtime(self.timestamp)
     msg.sms_id = self.sms_id
     email.encoders.encode_quopri(msg)
     msg.set_charset('utf-8')
     return msg
   except:
     print sender, type(sender)
     print receiver
     print subject
     print timestamp
     print sms_id
     print body
     raise
Exemple #53
0
    def _format_msg(self, error_data, to, date, orig):
        provider = to.split('@')[1]

        msg = Message()
        msg.add_header(
            'From', 'bitmask-bouncer@localhost (Bitmask Local Agent)')
        msg.add_header('To', to)
        msg.add_header('Subject', 'Undelivered Message')
        msg.add_header('Date', date)
        msg.set_payload(BOUNCE_TEMPLATE.format(
            raw_error=error_data,
            provider=provider,
            orig=orig))

        return msg.as_string()
def gen_invoice(name, email, rate, fnum):
    msg = Message()
    msg.add_header('From', 'FCCH Billing <*****@*****.**>')
    msg.add_header('To', '"' + name + '" <' + email + '>')
    msg.add_header('Cc', '"FCCH Billing" <*****@*****.**>')
    msg.add_header('Subject', 'Fort Collins Creator Hub ' + month + ' Invoice')
    msg.add_header('Content-type', 'text/plain')
    msg.set_payload('''\
Dear %(name)s,

This is a friendly semi-automated reminder that your Fort Collins Creator
Hub monthly membership fee of $%(rate)s for %(month)s is due by the first
of that month. If you've already paid, please do accept my apologies. If
you've configured automatic payment via our credit card billing system or
your bank's billpay, please consider this a reminder that you will soon
be charged.

You can choose to pay by check (or bank billpay) made out to Fort Collins
Creator Hub and sent to:

Fort Collins Creator Hub
PO Box 271094
Fort Collins CO 80527

Or, you can pay by credit card via the Payments page on our website:
http://www.fortcollinscreatorhub.org/

Thanks!
''' % {
    'name': name,
    'rate': rate,
    'month': month,
})

    fon = '%04d-%s.email' % (fnum, name.lower().replace(' ', '-'))
    fo = open(fon, 'wt')
    fo.write(msg.as_string())
    fo.close()
Exemple #55
0
def sendmail_sendmail(subject, body, to=USER_EMAIL, from_addr=FROM_EMAIL):
    m = Message()
    m.add_header('To', to)
    m.add_header('Subject', subject)
    m.add_header('From', from_addr)
    m.set_payload(body)

    sendmail = Popen('sendmail -t', stdin=PIPE, shell=True)
    sendmail.communicate(input=m.as_string())
Exemple #56
0
    def write_line(self, data):
        """
            Write a line *data* to socket. It appends a **newline** at
            the end of the *data* before sending it.
            
            The string MUST NOT contain **newline** otherwise an AssertionError will
            raise.
            
            Parameters:
            
            **data**
                String containing the data to be sent.
        """
        assert('\n' not in data)
        self.write_lock.acquire()
        try:
            try:
                data = data.encode('utf-8')
            except AttributeError:
                pass
            if self._debug_socket: 
                _log.debug("<:%d: %s", len(data), data.decode('utf-8')[:130])

            if self._http:
                msg = Message()
                msg.add_header('Content-Transfer-Encoding', '8bit')
                msg.add_header('Content-Type', 'application/json-rpc')
                msg.add_header('Content-Length', str(len(data)))
                msg.set_payload(data, charset='utf-8')
                self._wbuffer += 'HTTP/1.0 200 OK\n'+msg.as_string()
                #print(self._wbuffer)
            else:
                self._wbuffer += data + b'\n'
            sbytes = 0
            while self._wbuffer:
                try:
                    sbytes = self._sck.send(self._wbuffer)
                except IOError:
                    _log.debug("Write socket error: IOError (timeout: %r)",
                        self._sck.gettimeout())
                    _log.debug(traceback.format_exc(0))
                    return 0
                except socket.error:
                    _log.debug("Write socket error: socket.error (timeout: %r)",
                        self._sck.gettimeout())
                    _log.debug(traceback.format_exc(0))
                    return 0
                except:
                    raise
                if sbytes == 0: 
                    break
                self._wbuffer = self._wbuffer[sbytes:]
            if self._wbuffer:
                _log.warning("%d bytes left in write buffer", len(self._wbuffer))
            return len(self._wbuffer)
        finally:
            self.write_lock.release()
Exemple #57
0
def limit_reached_alert(user, limit_type, limit, value):
    """
    Send out a notification when a limit is reached.

    :param user: The user who has hit the limit
    :type user: User
    :param limit_type: The type of limit that has been reached
    :type limit_type: str
    :param limit: The limit amount
    :type limit: int
    :param value: The number of messages sent
    :type value: int
    """

    name  = get_config('alerts_name')
    faddr = get_config('alerts_from')
    taddr = get_config('alerts_to')

    message = MIMEMessage()
    message.add_header('From', '"%s" <%s>' % (name, faddr))
    if isinstance(taddr, list):
        message.add_header('To', ', '.join(taddr))
    else:
        message.add_header('To', taddr)
    message.add_header('Date', formatdate())
    message.add_header('Subject', 'User %s reached sending limit' % user.email)
    message.set_payload("""Hi,

The user has reached their %s limit of sending messages. They have sent %d
messages and have a limit of %d""" % (limit_type, value, limit)
    )

    # Send the message to the local SMTP server
    smtp = smtplib.SMTP('localhost')
    smtp.sendmail(faddr, taddr, str(message))
    smtp.close()
Exemple #58
0
def send_mail(nick_name, receivers, subject, content):
    server = smtplib.SMTP(smtp_server, smtp_port)
    server.login(user, passwd)
    rec_list = [rec for rec in receivers.split(";") if rec.find("@") != -1]
    msg = Message()
    msg.add_header("from", formataddr((nick_name, sender)))
    for rec in rec_list:
        msg.add_header("to", rec)
    msg.add_header("subject", subject)
    msg.set_payload(content)
    logger.debug("mail:%s"%msg.as_string())
    server.sendmail(sender, rec_list, msg.as_string())
    server.close()
    def send(self, url):
        msg = Message()
        msg.add_header('From', '%s %s' % (self.name, self.email))
        for to in self.recipients:
            msg.add_header('To', to)
        msg.add_header('Subject', self.subject)
        msg.set_payload(self.status.getvalue())

        try:
            mailer = smtplib.SMTP(self.host, self.port)
        except socket.error, e:
            error = 'Error initializing SMTP host. If you are using localhost, make sure that sendmail is properly configured.\nError message: %s' % e
            log.error(error)
            raise Exception(error)
            sys.exit(-1)
def send_email(email_msg, subject):
    to = ['*****@*****.**','*****@*****.**','*****@*****.**','*****@*****.**', '*****@*****.**']
    msg = Message()
    msg.add_header('From', 'Diederik van Liere <*****@*****.**>')
    for t in to:
        msg.add_header('To', t)
    msg.add_header('Subject', subject)
    msg.set_payload(email_msg.getvalue())
    mailer = smtplib.SMTP("smtp.gmail.com", 587)
    mailer.ehlo()
    mailer.starttls()
    mailer.ehlo()
    mailer.login(gmail_user, gmail_pwd)
    mailer.sendmail('*****@*****.**', to, msg.as_string())

    # Should be mailer.quit(), but that crashes...
    mailer.close()