Python email.utils.make_msgid() Examples

The following are 29 code examples of email.utils.make_msgid(). 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 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 #2
Source File: git_multimail_upstream.py    From pagure with GNU General Public License v2.0 6 votes vote down vote up
def __init__(self, environment, refname, short_refname, old, new, rev):
        Change.__init__(self, environment)
        self.change_type = {
            (False, True): "create",
            (True, True): "update",
            (True, False): "delete",
        }[bool(old), bool(new)]
        self.refname = refname
        self.short_refname = short_refname
        self.old = old
        self.new = new
        self.rev = rev
        self.msgid = make_msgid()
        self.diffopts = environment.diffopts
        self.graphopts = environment.graphopts
        self.logopts = environment.logopts
        self.commitlogopts = environment.commitlogopts
        self.showgraph = environment.refchange_showgraph
        self.showlog = environment.refchange_showlog

        self.header_template = REFCHANGE_HEADER_TEMPLATE
        self.intro_template = REFCHANGE_INTRO_TEMPLATE
        self.footer_template = FOOTER_TEMPLATE 
Example #3
Source File: tests.py    From pyas2 with GNU General Public License v2.0 6 votes vote down vote up
def testNoEncryptMessageNoMdn(self):
        """ Test Permutation 1: Sender sends un-encrypted data and does NOT request a receipt. """

        # Create the partner with appropriate settings for this case
        partner = models.Partner.objects.create(name='Client Partner',
                                                as2_name='as2server',
                                                target_url='http://localhost:8080/pyas2/as2receive',
                                                compress=False,
                                                mdn=False)

        # Build and send the message to server
        message_id = emailutils.make_msgid().strip('<>')
        in_message, response = self.buildSendMessage(message_id, partner)

        # Check if a 200 response was received
        self.assertEqual(response.status_code, 200)

        # Check if message was processed successfully
        out_message = models.Message.objects.get(message_id=message_id)
        self.assertEqual(out_message.status, 'S')

        # Check if input and output files are the same
        self.assertTrue(AS2SendReceiveTest.compareFiles(self.payload.file, out_message.payload.file)) 
Example #4
Source File: test_email.py    From ironpython3 with Apache License 2.0 6 votes vote down vote up
def test_make_msgid_collisions(self):
        # Test make_msgid uniqueness, even with multiple threads
        class MsgidsThread(Thread):
            def run(self):
                # generate msgids for 3 seconds
                self.msgids = []
                append = self.msgids.append
                make_msgid = utils.make_msgid
                try:
                    clock = time.monotonic
                except AttributeError:
                    clock = time.time
                tfin = clock() + 3.0
                while clock() < tfin:
                    append(make_msgid(domain='testdomain-string'))

        threads = [MsgidsThread() for i in range(5)]
        with start_threads(threads):
            pass
        all_ids = sum([t.msgids for t in threads], [])
        self.assertEqual(len(set(all_ids)), len(all_ids)) 
Example #5
Source File: mail_formater.py    From Moodle-Downloader-2 with GNU General Public License v3.0 6 votes vote down vote up
def _finish_with_main_wrapper(content: str, introduction: str) -> (str,
                                                                   {str: str}):
    """
    All emails use the main wrapper. This contains the normal html structure
    @return: A sendable mail object, with the content and the attachments
    """
    # cids link the attached media-files to be displayed inline
    header_cid = make_msgid()
    extender_cid = make_msgid()

    full_content = main_wrapper.substitute(
        content=content, introduction_text=introduction,
        header_cid=header_cid[1:-1], extender_cid=extender_cid[1:-1]
    )

    cids_and_filenames = {}
    cids_and_filenames.update({header_cid: 'header.png'})
    cids_and_filenames.update({extender_cid: 'header_extender.png'})

    return (full_content, cids_and_filenames) 
Example #6
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 #7
Source File: tests.py    From pyas2 with GNU General Public License v2.0 6 votes vote down vote up
def testSignMessageMdn(self):
        """ Test Permutation 8: Sender sends signed data and requests an unsigned receipt. """

        # Create the partner with appropriate settings for this case
        partner = models.Partner.objects.create(name='Client Partner',
                                                as2_name='as2server',
                                                target_url='http://localhost:8080/pyas2/as2receive',
                                                compress=False,
                                                signature='sha1',
                                                signature_key=self.server_crt,
                                                mdn=True)

        # Setup the message object and buid the message
        message_id = emailutils.make_msgid().strip('<>')
        in_message, response = self.buildSendMessage(message_id, partner)

        # Check if a 200 response was received
        self.assertEqual(response.status_code, 200)

        # Check if message was processed successfully
        out_message = models.Message.objects.get(message_id=message_id)
        # AS2SendReceiveTest.printLogs(out_message)
        self.assertEqual(out_message.status, 'S')

        # Process the MDN for the in message and check status
        AS2SendReceiveTest.buildMdn(in_message, response)
        # AS2SendReceiveTest.printLogs(in_message)
        self.assertEqual(in_message.status, 'S')

        # Check if input and output files are the same
        self.assertTrue(AS2SendReceiveTest.compareFiles(self.payload.file, out_message.payload.file)) 
Example #8
Source File: message.py    From fluentmail with MIT License 5 votes vote down vote up
def mime_message(self):
        msg = MIMEMultipart()
        msg['Subject'] = self.subject
        msg['From'] = sanitize_address(self.from_address)
        msg['Date'] = formatdate()
        msg['Message-ID'] = make_msgid()

        if self.to:
            msg['To'] = join_address_list(self.to)

        if self.cc:
            msg['Cc'] = join_address_list(self.cc)

        if self.bcc:
            msg['Bcc'] = join_address_list(self.bcc)

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

        encoding = self.encoding or 'utf-8'

        if self.body and self.html:
            alternative = MIMEMultipart('alternative')
            alternative.attach(MIMEText(self.body, 'plain', encoding))
            alternative.attach(MIMEText(self.html, 'html', encoding))
            msg.attach(alternative)
        elif self.body:
            msg.attach(MIMEText(self.body, 'plain', encoding))
        elif self.html:
            msg.attach(MIMEText(self.html, 'html', encoding))

        for attachment in self.attachments:
            msg.attach(attachment)

        return msg 
Example #9
Source File: util.py    From pixelated-user-agent with GNU Affero General Public License v3.0 5 votes vote down vote up
def load_mail_from_file(mail_file, enforceUniqueMessageId=False):
    mailset_dir = pkg_resources.resource_filename('test.unit.fixtures', 'mailset')
    mail_file = os.path.join(mailset_dir, 'new', mail_file)
    with open(mail_file) as f:
        mail = Parser().parse(f)

    if enforceUniqueMessageId:
        mail.add_header('Message-Id', make_msgid())

    return mail 
Example #10
Source File: headers.py    From mailthon with MIT License 5 votes vote down vote up
def message_id(string=None, idstring=None):
    """
    Generates a Message-ID header, by yielding a
    given *string* if specified, else an RFC
    compliant message-id generated by make_msgid
    and strengthened by an optional *idstring*.
    """
    yield 'Message-ID'
    yield string or make_msgid(idstring) 
Example #11
Source File: flask_mail.py    From flask-unchained with MIT License 5 votes vote down vote up
def __init__(self, subject='',
                 recipients=None,
                 body=None,
                 html=None,
                 alts=None,
                 sender=None,
                 cc=None,
                 bcc=None,
                 attachments=None,
                 reply_to=None,
                 date=None,
                 charset=None,
                 extra_headers=None,
                 mail_options=None,
                 rcpt_options=None,
                 subtype=None):

        sender = sender or current_app.extensions['mail'].default_sender

        if isinstance(sender, tuple):
            sender = "%s <%s>" % sender

        self.recipients = recipients or []
        self.subject = subject
        self.sender = sender
        self.reply_to = reply_to
        self.cc = cc or []
        self.bcc = bcc or []
        self.body = body
        self.alts = dict(alts or {})
        self.html = html
        self.date = date
        self.msgId = make_msgid()
        self.charset = charset
        self.extra_headers = extra_headers
        self.subtype = subtype
        self.mail_options = mail_options or []
        self.rcpt_options = rcpt_options or []
        self.attachments = attachments or [] 
Example #12
Source File: Sender.py    From m2em with MIT License 5 votes vote down vote up
def send_confirmation(self, usermail):
        """ Method to send a confirmation mail to the user """

        # Compile Email
        msg = MIMEMultipart()
        msg['Subject'] = 'Ebook Delivery of %s' % self.mangatitle
        msg['Date'] = formatdate(localtime=True)
        msg['From'] = self.emailadress
        msg['To'] = usermail
        msg['Message-ID'] = make_msgid()

        text = '%s has been delivered to your Kindle Email!' % self.mangatitle
        msg.attach(MIMEText(text))

        # Convert message to string
        sio = StringIO()
        gen = Generator(sio, mangle_from_=False)
        gen.flatten(msg)
        msg = sio.getvalue()

        try:
            server = smtplib.SMTP(self.smtpserver, self.serverport, )
            if self.starttls:
                server.starttls()
            server.ehlo()
            server.login(self.emailadress, self.password)
            server.sendmail(self.emailadress, usermail, msg)
            server.close()
            logging.debug("Sent confirmation email to %s ", usermail)
        except smtplib.SMTPException as fail:
            logging.debug("Could not send email! %s", fail) 
Example #13
Source File: test_email.py    From ironpython3 with Apache License 2.0 5 votes vote down vote up
def test_make_msgid_domain(self):
        self.assertEqual(
            email.utils.make_msgid(domain='testdomain-string')[-19:],
            '@testdomain-string>') 
Example #14
Source File: tests.py    From pyas2 with GNU General Public License v2.0 5 votes vote down vote up
def testCompressEncryptSignMessageSignMdn(self):
        """ Test Permutation 13: Sender sends compressed, encrypted and signed data and requests an signed receipt. """

        # Create the partner with appropriate settings for this case
        partner = models.Partner.objects.create(name='Client Partner',
                                                as2_name='as2server',
                                                target_url='http://localhost:8080/pyas2/as2receive',
                                                compress=True,
                                                encryption='des_ede3_cbc',
                                                encryption_key=self.server_crt,
                                                signature='sha1',
                                                signature_key=self.server_crt,
                                                mdn=True,
                                                mdn_sign='sha1')

        # Setup the message object and buid the message
        message_id = emailutils.make_msgid().strip('<>')
        in_message, response = self.buildSendMessage(message_id, partner)

        # Check if a 200 response was received
        self.assertEqual(response.status_code, 200)

        # Check if message was processed successfully
        out_message = models.Message.objects.get(message_id=message_id)
        # AS2SendReceiveTest.printLogs(out_message)
        self.assertEqual(out_message.status, 'S')

        # Process the MDN for the in message and check status
        AS2SendReceiveTest.buildMdn(in_message, response)
        # AS2SendReceiveTest.printLogs(in_message)
        self.assertEqual(in_message.status, 'S')

        # Check if input and output files are the same
        self.assertTrue(AS2SendReceiveTest.compareFiles(self.payload.file, out_message.payload.file)) 
Example #15
Source File: tests.py    From pyas2 with GNU General Public License v2.0 5 votes vote down vote up
def testEncryptSignMessageMdn(self):
        """ Test Permutation 11: Sender sends encrypted and signed data and requests an unsigned receipt. """

        # Create the partner with appropriate settings for this case
        partner = models.Partner.objects.create(name='Client Partner',
                                                as2_name='as2server',
                                                target_url='http://localhost:8080/pyas2/as2receive',
                                                compress=False,
                                                encryption='des_ede3_cbc',
                                                encryption_key=self.server_crt,
                                                signature='sha1',
                                                signature_key=self.server_crt,
                                                mdn=True)

        # Setup the message object and build the message
        message_id = emailutils.make_msgid().strip('<>')
        in_message, response = self.buildSendMessage(message_id, partner)

        # Check if a 200 response was received
        self.assertEqual(response.status_code, 200)

        # Check if message was processed successfully
        out_message = models.Message.objects.get(message_id=message_id)
        # AS2SendReceiveTest.printLogs(out_message)
        self.assertEqual(out_message.status, 'S')

        # Process the MDN for the in message and check status
        AS2SendReceiveTest.buildMdn(in_message, response)
        # AS2SendReceiveTest.printLogs(in_message)
        self.assertEqual(in_message.status, 'S')

        # Check if input and output files are the same
        self.assertTrue(AS2SendReceiveTest.compareFiles(self.payload.file, out_message.payload.file)) 
Example #16
Source File: tests.py    From pyas2 with GNU General Public License v2.0 5 votes vote down vote up
def testEncryptSignMessageNoMdn(self):
        """ Test Permutation 10: Sender sends encrypted and signed data and does NOT request a receipt. """

        # Create the partner with appropriate settings for this case
        partner = models.Partner.objects.create(name='Client Partner',
                                                as2_name='as2server',
                                                target_url='http://localhost:8080/pyas2/as2receive',
                                                compress=False,
                                                signature='sha1',
                                                signature_key=self.server_crt,
                                                encryption='des_ede3_cbc',
                                                encryption_key=self.server_crt,
                                                mdn=False)

        # Build and send the message to server
        message_id = emailutils.make_msgid().strip('<>')
        in_message, response = self.buildSendMessage(message_id, partner)

        # Check if a 200 response was received
        self.assertEqual(response.status_code, 200)

        # Check if message was processed successfully
        out_message = models.Message.objects.get(message_id=message_id)
        # AS2SendReceiveTest.printLogs(out_message)
        self.assertEqual(out_message.status, 'S')

        # Check if input and output files are the same
        self.assertTrue(AS2SendReceiveTest.compareFiles(self.payload.file, out_message.payload.file)) 
Example #17
Source File: tests.py    From pyas2 with GNU General Public License v2.0 5 votes vote down vote up
def testSignMessageSignMdn(self):
        """ Test Permutation 9: Sender sends signed data and requests an signed receipt. """

        # Create the partner with appropriate settings for this case
        partner = models.Partner.objects.create(name='Client Partner',
                                                as2_name='as2server',
                                                target_url='http://localhost:8080/pyas2/as2receive',
                                                compress=False,
                                                signature='sha1',
                                                signature_key=self.server_crt,
                                                mdn=True,
                                                mdn_sign='sha1')

        # Setup the message object and buid the message
        message_id = emailutils.make_msgid().strip('<>')
        in_message, response = self.buildSendMessage(message_id, partner)

        # Check if a 200 response was received
        self.assertEqual(response.status_code, 200)

        # Check if message was processed successfully
        out_message = models.Message.objects.get(message_id=message_id)
        # AS2SendReceiveTest.printLogs(out_message)
        self.assertEqual(out_message.status, 'S')

        # Process the MDN for the in message and check status
        AS2SendReceiveTest.buildMdn(in_message, response)
        # AS2SendReceiveTest.printLogs(in_message)
        self.assertEqual(in_message.status, 'S')

        # Check if input and output files are the same
        self.assertTrue(AS2SendReceiveTest.compareFiles(self.payload.file, out_message.payload.file)) 
Example #18
Source File: tests.py    From pyas2 with GNU General Public License v2.0 5 votes vote down vote up
def testSignMessageNoMdn(self):
        """ Test Permutation 7: Sender sends signed data and does NOT request a receipt. """

        # Create the partner with appropriate settings for this case
        partner = models.Partner.objects.create(name='Client Partner',
                                                as2_name='as2server',
                                                target_url='http://localhost:8080/pyas2/as2receive',
                                                compress=False,
                                                signature='sha1',
                                                signature_key=self.server_crt,
                                                mdn=False)

        # Build and send the message to server
        message_id = emailutils.make_msgid().strip('<>')
        in_message, response = self.buildSendMessage(message_id, partner)

        # Check if a 200 response was received
        self.assertEqual(response.status_code, 200)

        # Check if message was processed successfully
        out_message = models.Message.objects.get(message_id=message_id)
        # AS2SendReceiveTest.printLogs(out_message)
        self.assertEqual(out_message.status, 'S')

        # Check if input and output files are the same
        self.assertTrue(AS2SendReceiveTest.compareFiles(self.payload.file, out_message.payload.file)) 
Example #19
Source File: tests.py    From pyas2 with GNU General Public License v2.0 5 votes vote down vote up
def testEncryptMessageMdn(self):
        """ Test Permutation 5: Sender sends encrypted data and requests an unsigned receipt. """

        # Create the partner with appropriate settings for this case
        partner = models.Partner.objects.create(name='Client Partner',
                                                as2_name='as2server',
                                                target_url='http://localhost:8080/pyas2/as2receive',
                                                compress=False,
                                                encryption='des_ede3_cbc',
                                                encryption_key=self.server_crt,
                                                mdn=True)

        # Setup the message object and buid the message
        message_id = emailutils.make_msgid().strip('<>')
        in_message, response = self.buildSendMessage(message_id, partner)

        # Check if a 200 response was received
        self.assertEqual(response.status_code, 200)

        # Check if message was processed successfully
        out_message = models.Message.objects.get(message_id=message_id)
        # AS2SendReceiveTest.printLogs(out_message)
        self.assertEqual(out_message.status, 'S')

        # Process the MDN for the in message and check status
        AS2SendReceiveTest.buildMdn(in_message, response)
        # AS2SendReceiveTest.printLogs(in_message)
        self.assertEqual(in_message.status, 'S')

        # Check if input and output files are the same
        self.assertTrue(AS2SendReceiveTest.compareFiles(self.payload.file, out_message.payload.file)) 
Example #20
Source File: tests.py    From pyas2 with GNU General Public License v2.0 5 votes vote down vote up
def testEncryptMessageNoMdn(self):
        """ Test Permutation 4: Sender sends encrypted data and does NOT request a receipt. """

        # Create the partner with appropriate settings for this case
        partner = models.Partner.objects.create(name='Client Partner',
                                                as2_name='as2server',
                                                target_url='http://localhost:8080/pyas2/as2receive',
                                                compress=False,
                                                encryption='des_ede3_cbc',
                                                encryption_key=self.server_crt,
                                                mdn=False)

        # Build and send the message to server
        message_id = emailutils.make_msgid().strip('<>')
        in_message, response = self.buildSendMessage(message_id, partner)

        # Check if a 200 response was received
        self.assertEqual(response.status_code, 200)

        # Check if message was processed successfully
        out_message = models.Message.objects.get(message_id=message_id)
        self.assertEqual(out_message.status, 'S')

        # Check if input and output files are the same
        # AS2SendReceiveTest.printLogs(out_message)
        self.assertTrue(AS2SendReceiveTest.compareFiles(self.payload.file, out_message.payload.file)) 
Example #21
Source File: tests.py    From pyas2 with GNU General Public License v2.0 5 votes vote down vote up
def testNoEncryptMessageSignMdn(self):
        """ Test Permutation 3: Sender sends un-encrypted data and requests an signed receipt. """

        # Create the partner with appropriate settings for this case
        partner = models.Partner.objects.create(name='Client Partner',
                                                as2_name='as2server',
                                                target_url='http://localhost:8080/pyas2/as2receive',
                                                compress=False,
                                                mdn=True,
                                                mdn_mode='SYNC',
                                                mdn_sign='sha1',
                                                signature_key=self.server_crt)

        # Setup the message object and buid the message
        message_id = emailutils.make_msgid().strip('<>')
        in_message, response = self.buildSendMessage(message_id, partner)

        # Check if a 200 response was received
        self.assertEqual(response.status_code, 200)

        # Check if message was processed successfully
        out_message = models.Message.objects.get(message_id=message_id)
        # AS2SendReceiveTest.printLogs(out_message)
        self.assertEqual(out_message.status, 'S')

        # Process the MDN for the in message and check status
        AS2SendReceiveTest.buildMdn(in_message, response)
        # AS2SendReceiveTest.printLogs(in_message)
        self.assertEqual(in_message.status, 'S')

        # Check if input and output files are the same
        self.assertTrue(AS2SendReceiveTest.compareFiles(self.payload.file, out_message.payload.file)) 
Example #22
Source File: tests.py    From pyas2 with GNU General Public License v2.0 5 votes vote down vote up
def testNoEncryptMessageMdn(self):
        """ Test Permutation 2: Sender sends un-encrypted data and requests an unsigned receipt. """

        # Create the partner with appropriate settings for this case
        partner = models.Partner.objects.create(name='Client Partner',
                                                as2_name='as2server',
                                                target_url='http://localhost:8080/pyas2/as2receive',
                                                compress=False,
                                                mdn=True)

        # Setup the message object and buid the message
        message_id = emailutils.make_msgid().strip('<>')
        in_message, response = self.buildSendMessage(message_id, partner)

        # Check if a 200 response was received
        self.assertEqual(response.status_code, 200)

        # Check if message was processed successfully
        out_message = models.Message.objects.get(message_id=message_id)
        self.assertEqual(out_message.status, 'S')

        # Process the MDN for the in message and check status
        AS2SendReceiveTest.buildMdn(in_message, response)
        self.assertEqual(in_message.status, 'S')

        # Check if input and output files are the same
        self.assertTrue(AS2SendReceiveTest.compareFiles(self.payload.file, out_message.payload.file)) 
Example #23
Source File: threading.py    From isthislegit with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def __init__(self, message):
        self.message = message
        self.message_id = message.message_id or make_msgid()
        self.references = message.references
        #self.subject = message.subject
        #self.clean_subject = message.clean_subject 
Example #24
Source File: threading.py    From isthislegit with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def map_message(message, table):

    def container(message_id):
        return table.setdefault(message_id, Container())

    w = Wrapper(message)
    this = container(w.message_id)

    # process case when we have two messages
    # with the same id, we should put
    # our current message to another container
    # otherwise the message would be lost
    if this.message:
        fake_id = make_msgid()
        this = container(fake_id)
    this.message = w

    # link message parents together
    prev = None
    for parent_id in w.references:
        parent = container(parent_id)
        if prev and not parent.parent and not introduces_loop(prev, parent):
            prev.add_child(parent)
        prev = parent

    # process case where this message has parent
    # unlink the old parent in this case
    if this.parent:
        this.parent.remove_child(this)

    # link to the cool parent instead
    if prev and not introduces_loop(prev, this):
        prev.add_child(this) 
Example #25
Source File: wrappers.py    From isthislegit with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def generate(cls, domain=None):
        message_id = make_msgid().strip("<>")
        if domain:
            local = message_id.split('@')[0]
            message_id = "{0}@{1}".format(local, domain)
        return cls(message_id) 
Example #26
Source File: tests.py    From pyas2 with GNU General Public License v2.0 4 votes vote down vote up
def testEncryptSignMessageAsyncSignMdn(self):
        """ Test Permutation 14: Sender sends encrypted and signed data and requests an Asynchronous signed receipt. """

        # Create the partner with appropriate settings for this case
        partner = models.Partner.objects.create(name='Client Partner',
                                                as2_name='as2server',
                                                target_url='http://localhost:8080/pyas2/as2receive',
                                                compress=False,
                                                encryption='des_ede3_cbc',
                                                encryption_key=self.server_crt,
                                                signature='sha1',
                                                signature_key=self.server_crt,
                                                mdn=True,
                                                mdn_mode='ASYNC',
                                                mdn_sign='sha1')

        # Setup the message object and build the message, do not send it
        message_id = emailutils.make_msgid().strip('<>')
        in_message, response = self.buildSendMessage(message_id, partner)

        # Check if message was processed successfully
        out_message = models.Message.objects.get(message_id=message_id)
        # AS2SendReceiveTest.printLogs(in_message)
        self.assertEqual(out_message.status, 'S')

        # Check if input and output files are the same
        self.assertTrue(AS2SendReceiveTest.compareFiles(self.payload.file, out_message.payload.file))

        # Process the ASYNC MDN for the in message and check status
        message_headers = self.header_parser.parsestr(out_message.mdn.headers)
        http_headers = {}
        for header in message_headers.keys():
            key = 'HTTP_%s' % header.replace('-', '_').upper()
            http_headers[key] = message_headers[header]
        with open(out_message.mdn.file, 'rb') as mdn_file:
            mdn_content = mdn_file.read()

        # Switch the out and in messages, this is to prevent duplicate message from being picked
        out_message.delete()
        in_message.pk = message_id
        in_message.payload = None
        in_message.save()

        # Send the async mdn and check for its status
        content_type = http_headers.pop('HTTP_CONTENT_TYPE')
        response = self.client.post('/pyas2/as2receive',
                                    data=mdn_content,
                                    content_type=content_type,
                                    **http_headers)
        self.assertEqual(response.status_code, 200)

        in_message = models.Message.objects.get(message_id=message_id)
        # AS2SendReceiveTest.printLogs(in_message)
        self.assertEqual(in_message.status, 'S') 
Example #27
Source File: __init__.py    From ob2 with BSD 2-Clause "Simplified" License 4 votes vote down vote up
def create_email(_template_name, _to, _subject, _from=None, _attachments=[],
                 _message_id=None, **kwargs):
    """
    Prepares an email to be sent by the email queue background thread. Templates are taken from
    templates/*.html and templates/*.txt. Both a HTML and a plain text template is expected to be
    present. Parameters should be passed as keyword arguments to this function.

        _template_name
        _to
        _subject
        _from
        _attachments     -- Tuples of (type, file_path) where type should be "pdf" (only pdfs are
                            supported right now)
        _message_id      -- If this message is a REPLY, then specify the message ID(s) of the
                            previous messages in this chain.

    Returns an opaque object (spoiler: it's a tuple) which should be passed directly to
    mailer_queue.enqueue().

    """
    if not config.mailer_enabled:
        raise RuntimeError("Cannot create mail while mailer is disabled")
    if _from is None:
        _from = config.mailer_from
    msg = MIMEMultipart('alternative')
    msg['Subject'] = _subject
    msg['From'] = _from
    msg['To'] = _to
    msg['Message-Id'] = make_msgid()
    if _message_id:
        msg['References'] = _message_id
        msg['In-Reply-To'] = _message_id
    body_plain = render_template("%s.txt" % _template_name, **kwargs)
    body_html = render_template("%s.html" % _template_name, **kwargs)
    msg.attach(MIMEText(body_plain, 'plain', 'utf-8'))
    msg.attach(MIMEText(body_html, 'html', 'utf-8'))
    for attachment_type, attachment_path in _attachments:
        attachment_name = basename(attachment_path)
        with open(attachment_path, "rb") as attachment_file:
            attachment_bytes = attachment_file.read()
        if attachment_type == "pdf":
            attachment = MIMEApplication(attachment_bytes, _subtype="pdf")
            attachment.add_header("Content-Disposition", "attachment", filename=attachment_name)
            msg.attach(attachment)
        else:
            raise ValueError("Unsupported attachment type: %s" % attachment_type)
    return _from, _to, msg.as_string() 
Example #28
Source File: schedules.py    From incubator-superset with Apache License 2.0 4 votes vote down vote up
def _generate_report_content(
    delivery_type: EmailDeliveryType, screenshot: bytes, name: str, url: str
) -> ReportContent:
    data: Optional[Dict[str, Any]]

    # how to: https://api.slack.com/reference/surfaces/formatting
    slack_message = __(
        """
        *%(name)s*\n
        <%(url)s|Explore in Superset>
        """,
        name=name,
        url=url,
    )

    if delivery_type == EmailDeliveryType.attachment:
        images = None
        data = {"screenshot.png": screenshot}
        body = __(
            '<b><a href="%(url)s">Explore in Superset</a></b><p></p>',
            name=name,
            url=url,
        )
    elif delivery_type == EmailDeliveryType.inline:
        # Get the domain from the 'From' address ..
        # and make a message id without the < > in the ends
        domain = parseaddr(config["SMTP_MAIL_FROM"])[1].split("@")[1]
        msgid = make_msgid(domain)[1:-1]

        images = {msgid: screenshot}
        data = None
        body = __(
            """
            <b><a href="%(url)s">Explore in Superset</a></b><p></p>
            <img src="cid:%(msgid)s">
            """,
            name=name,
            url=url,
            msgid=msgid,
        )

    return ReportContent(body, data, images, slack_message, screenshot) 
Example #29
Source File: email_utils.py    From app with MIT License 4 votes vote down vote up
def send_email(to_email, subject, plaintext, html=None):
    if NOT_SEND_EMAIL:
        LOG.d(
            "send email with subject %s to %s, plaintext: %s",
            subject,
            to_email,
            plaintext,
        )
        return

    LOG.d("send email to %s, subject %s", to_email, subject)

    if POSTFIX_SUBMISSION_TLS:
        smtp = SMTP(POSTFIX_SERVER, 587)
        smtp.starttls()
    else:
        smtp = SMTP(POSTFIX_SERVER, POSTFIX_PORT or 25)

    msg = MIMEMultipart("alternative")
    msg.attach(MIMEText(plaintext, "text"))

    if not html:
        html = plaintext.replace("\n", "<br>")
    msg.attach(MIMEText(html, "html"))

    msg["Subject"] = subject
    msg["From"] = f"{SUPPORT_NAME} <{SUPPORT_EMAIL}>"
    msg["To"] = to_email

    msg_id_header = make_msgid()
    msg["Message-ID"] = msg_id_header

    date_header = formatdate()
    msg["Date"] = date_header

    # add DKIM
    email_domain = SUPPORT_EMAIL[SUPPORT_EMAIL.find("@") + 1 :]
    add_dkim_signature(msg, email_domain)

    msg_raw = msg.as_bytes()
    if SENDER:
        smtp.sendmail(SENDER, to_email, msg_raw)
    else:
        smtp.sendmail(SUPPORT_EMAIL, to_email, msg_raw)