def attach_image(msg, url, file_path, selector, dimensions="1024x1024"):
    if "selectedTab=map" in url:
        wait = 8000
        dimensions = "1000x600"
    elif "selectedTab=chart" in url:
        wait = 1000
        dimensions = "800x600"
    elif "selectedTab" in url:
        wait = 500
        dimensions = "800x600"
    else:
        wait = 1000
    cmd = '{cmd} "{host}{url}" {file_path} "{selector}" {dimensions} {wait}'
    cmd = cmd.format(
        cmd=GRAB_CMD,
        host=settings.GRAB_HOST,
        url=url,
        file_path=file_path,
        selector=selector,
        dimensions=dimensions,
        wait=wait,
    )
    result = subprocess.check_output(cmd, shell=True)
    logger.debug("Command %s completed with output %s" % (cmd, result.strip()))
    if os.path.getsize(file_path) == 0:
        msg = "File at %s empty (generated from url %s)" % (file_path, url)
        raise BadAlertImageError(msg)
    return attach_inline_image_file(msg, file_path, subtype="png")
Exemple #2
0
    def test_embedded_images(self):
        image_filename = SAMPLE_IMAGE_FILENAME
        image_path = sample_image_path(image_filename)
        image_data = sample_image_content(image_filename)

        cid = attach_inline_image_file(self.message,
                                       image_path,
                                       domain="example.com")
        html_content = '<p>This has an <img src="cid:%s" alt="inline" /> image.</p>' % cid
        self.message.attach_alternative(html_content, "text/html")

        self.message.send()
        sent_message = self.get_sent_message()

        self.assertEqual(sent_message.html, html_content)

        inlines = sent_message.inline_attachments
        self.assertEqual(len(inlines), 1)
        self.assertEqual(inlines[cid].get_content_type(), "image/png")
        self.assertEqual(inlines[cid].get_filename(), image_filename)
        self.assertEqual(inlines[cid].get_content_bytes(), image_data)

        # Make sure neither the html nor the inline image is treated as an attachment:
        params = self.get_send_params()
        raw_mime = params['RawMessage']['Data']
        self.assertNotIn(b'\nContent-Disposition: attachment', raw_mime)
Exemple #3
0
def send_mail(template_html_name=None,
              template_text_name=None,
              context=None,
              subject=None,
              from_email=None,
              to=None):
    # Plain text part
    text_content = render_to_string(template_text_name, context=context)

    if from_email is None:
        from_email = settings.PORTAILVA_APP['site']['email_noreply']

    msg = EmailMultiAlternatives(subject=subject,
                                 body=text_content,
                                 from_email=from_email,
                                 to=[to])

    # Making context
    logo_cid = attach_inline_image_file(
        msg,
        os.path.join(settings.BASE_DIR,
                     settings.STATIC_ROOT + "/img/logo_mail.png"))
    context.update({'logo_cid': logo_cid, 'app': settings.PORTAILVA_APP})

    # HTML part
    html_content = render_to_string(template_html_name, context=context)

    msg.attach_alternative(html_content, "text/html")
    msg.send()
def attach_image(msg, url, file_path, selector, dimensions='1024x1024'):
    if 'selectedTab=map' in url:
        wait = 8000
        dimensions = '1000x600'
    elif 'selectedTab=chart' in url:
        wait = 1000
        dimensions = '800x600'
    elif 'selectedTab' in url:
        wait = 500
        dimensions = '800x600'
    else:
        wait = 500
    cmd = '{cmd} "{host}{url}" {file_path} "{selector}" {dimensions} {wait}'
    cmd = (
        cmd.format(
            cmd=GRAB_CMD,
            host=settings.GRAB_HOST,
            url=url,
            file_path=file_path,
            selector=selector,
            dimensions=dimensions,
            wait=wait
        )
    )
    result = subprocess.check_output(cmd, shell=True)
    logger.debug("Command %s completed with output %s" % (cmd, result.strip()))
    return attach_inline_image_file(
        msg, file_path, subtype='png')
    def test_embedded_images(self):
        image_filename = SAMPLE_IMAGE_FILENAME
        image_path = sample_image_path(image_filename)

        cid = attach_inline_image_file(self.message, image_path)  # Read from a png file
        html_content = '<p>This has an <img src="cid:%s" alt="inline" /> image.</p>' % cid
        self.message.attach_alternative(html_content, "text/html")

        with self.assertRaisesMessage(AnymailUnsupportedFeature, 'inline attachments'):
            self.message.send()
Exemple #6
0
 def get_inline_images(self):
     """Process inline images"""
     inline_images = {}
     for cid, path in self.cids.items():
         inline_images[cid] = attach_inline_image_file(self.email,
                                                       os.path.join(
                                                           self.img_dir,
                                                           path),
                                                       domain='etalia.org')
     return inline_images
def attach_image(msg, url, file_path, selector, dimensions="1024x1024"):
    if "selectedTab=map" in url:
        wait = 8000
        dimensions = "1000x600"
    elif "selectedTab=chart" in url:
        wait = 1000
        dimensions = "800x600"
    elif "selectedTab" in url:
        wait = 500
        dimensions = "800x600"
    else:
        wait = 1000
    cmd = '{cmd} "{host}{url}" {file_path} "{selector}" {dimensions} {wait}'
    cmd = cmd.format(
        cmd=GRAB_CMD,
        host=settings.GRAB_HOST,
        url=url,
        file_path=file_path,
        selector=selector,
        dimensions=dimensions,
        wait=wait,
    )
    response = subprocess.run(
        cmd,
        shell=True,
        stdout=subprocess.PIPE,
        stderr=subprocess.PIPE,
        universal_newlines=True,
        # Fix for PhantomJS under new versions of Debian/Ubuntu
        # See https://github.com/ariya/phantomjs/issues/15449
        env=dict(os.environ, OPENSSL_CONF="/etc/ssl"),
    )
    if response.returncode > 0:
        raise BadAlertImageError(
            f"phantomjs command failed with code {response.returncode}\n\n"
            f"cmd:\n{cmd}\n\n"
            f"stdout:\n{response.stdout}\n\n"
            f"stderr:\n{response.stderr}")
    else:
        logger.debug("Command %s completed with output %s" %
                     (cmd, response.stdout.strip()))
    if os.path.getsize(file_path) == 0:
        msg = "File at %s empty (generated from url %s)" % (file_path, url)
        raise BadAlertImageError(msg)
    return attach_inline_image_file(msg, file_path, subtype="png")
    def test_embedded_images(self):
        image_filename = SAMPLE_IMAGE_FILENAME
        image_path = sample_image_path(image_filename)
        image_data = sample_image_content(image_filename)

        cid = attach_inline_image_file(self.message, image_path)  # Read from a png file
        html_content = '<p>This has an <img src="cid:%s" alt="inline" /> image.</p>' % cid
        self.message.attach_alternative(html_content, "text/html")

        self.message.send()
        data = self.get_api_call_data()
        self.assertEqual(data['html'], html_content)

        files = self.get_api_call_files()
        self.assertEqual(files, {
            'files[%s]' % image_filename: (image_filename, image_data, "image/png"),
        })
        self.assertEqual(data['content[%s]' % image_filename], cid)
    def test_embedded_images(self):
        image_filename = SAMPLE_IMAGE_FILENAME
        image_path = sample_image_path(image_filename)
        image_data = sample_image_content(image_filename)

        cid = attach_inline_image_file(self.message, image_path)  # Read from a png file
        html_content = '<p>This has an <img src="cid:%s" alt="inline" /> image.</p>' % cid
        self.message.attach_alternative(html_content, "text/html")

        self.message.send()
        data = self.get_api_call_json()
        self.assertEqual(data['Html-part'], html_content)

        attachments = data['Inline_attachments']
        self.assertEqual(len(attachments), 1)
        self.assertEqual(attachments[0]['Filename'], cid)
        self.assertEqual(attachments[0]['Content-type'], 'image/png')
        self.assertEqual(decode_att(attachments[0]["content"]), image_data)
    def test_embedded_images(self):
        image_filename = SAMPLE_IMAGE_FILENAME
        image_path = sample_image_path(image_filename)
        image_data = sample_image_content(image_filename)

        cid = attach_inline_image_file(self.message, image_path)  # Read from a png file
        html_content = '<p>This has an <img src="cid:%s" alt="inline" /> image.</p>' % cid
        self.message.attach_alternative(html_content, "text/html")

        self.message.send()
        data = self.get_api_call_data()
        self.assertEqual(data['html'], html_content)

        files = self.get_api_call_files()
        self.assertEqual(files, {
            'files[%s]' % image_filename: (image_filename, image_data, "image/png"),
        })
        self.assertEqual(data['content[%s]' % image_filename], cid)
Exemple #11
0
    def test_embedded_images(self):
        image_filename = SAMPLE_IMAGE_FILENAME
        image_path = sample_image_path(image_filename)
        image_data = sample_image_content(image_filename)

        cid = attach_inline_image_file(self.message, image_path)  # Read from a png file
        html_content = '<p>This has an <img src="cid:%s" alt="inline" /> image.</p>' % cid
        self.message.attach_alternative(html_content, "text/html")

        self.message.send()
        data = self.get_api_call_json()
        self.assertEqual(data['Html-part'], html_content)

        attachments = data['Inline_attachments']
        self.assertEqual(len(attachments), 1)
        self.assertEqual(attachments[0]['Filename'], cid)
        self.assertEqual(attachments[0]['Content-type'], 'image/png')
        self.assertEqual(decode_att(attachments[0]["content"]), image_data)
Exemple #12
0
    def test_embedded_images(self):
        image_filename = SAMPLE_IMAGE_FILENAME
        image_path = sample_image_path(image_filename)
        image_data = sample_image_content(image_filename)

        cid = attach_inline_image_file(self.message, image_path)
        html_content = '<p>This has an <img src="cid:%s" alt="inline" /> image.</p>' % cid
        self.message.attach_alternative(html_content, "text/html")

        self.message.send()
        params = self.get_send_params()
        self.assertEqual(params['html'], html_content)

        self.assertEqual(len(params['inline_images']), 1)
        self.assertEqual(params['inline_images'][0]["type"], "image/png")
        self.assertEqual(params['inline_images'][0]["name"], cid)
        self.assertEqual(decode_att(params['inline_images'][0]["data"]), image_data)
        # Make sure neither the html nor the inline image is treated as an attachment:
        self.assertNotIn('attachments', params)
Exemple #13
0
    def test_embedded_images(self):
        image_filename = SAMPLE_IMAGE_FILENAME
        image_path = sample_image_path(image_filename)
        image_data = sample_image_content(image_filename)

        cid = attach_inline_image_file(self.message, image_path)  # Read from a png file
        html_content = '<p>This has an <img src="cid:%s" alt="inline" /> image.</p>' % cid
        self.message.attach_alternative(html_content, "text/html")

        self.message.send()
        data = self.get_api_call_json()

        self.assertEqual(data['attachments'][0], {
            'filename': image_filename,
            'content': b64encode(image_data).decode('ascii'),
            'type': "image/png",  # type inferred from filename
            'disposition': "inline",
            'content_id': cid,
        })
    def test_embedded_images(self):
        image_filename = SAMPLE_IMAGE_FILENAME
        image_path = sample_image_path(image_filename)
        image_data = sample_image_content(image_filename)

        cid = attach_inline_image_file(self.message, image_path)
        html_content = '<p>This has an <img src="cid:%s" alt="inline" /> image.</p>' % cid
        self.message.attach_alternative(html_content, "text/html")

        self.message.send()
        params = self.get_send_params()
        self.assertEqual(params['html'], html_content)

        self.assertEqual(len(params['inline_images']), 1)
        self.assertEqual(params['inline_images'][0]["type"], "image/png")
        self.assertEqual(params['inline_images'][0]["name"], cid)
        self.assertEqual(decode_att(params['inline_images'][0]["data"]), image_data)
        # Make sure neither the html nor the inline image is treated as an attachment:
        self.assertNotIn('attachments', params)
Exemple #15
0
    def post(self, request):
        image = request.data.pop('workout_image')
        to_email = request.data.pop('to')
        serialized = WorkoutSerializer(data=request.data)

        exercises = {}

        if serialized.is_valid():
            payload = {
                'date_for_completion': serialized.data['date_for_completion'],
                'target_muscle': serialized.data['target_muscle'],
                'title': serialized.data['title'],
                'training_type': serialized.data['training_type'],
                'exercises': serialized.data['exercises']
            }

            text_email = get_template('workoutemail.txt')

            d = Context({'payload': payload, 'username': request.user})
            text_content = text_email.render(d)

            message = EmailMultiAlternatives(
                "Workout For The Day",
                text_content,
                from_email=email_config['DEFAULT_FROM_EMAIL'],
                to=[to_email])
            workout_image = self.set_image(payload['target_muscle'])
            cid = attach_inline_image_file(message, workout_image)
            html_email = render_to_string("workoutemail.html", {
                'payload': payload,
                'username': request.user,
                'cid': cid
            })

            message.attach_alternative(html_email, 'text/html')

            message.send()

            return Response(serialized.data, status=status.HTTP_200_OK)
        else:
            return Response(serialized._errors,
                            status=status.HTTP_400_BAD_REQUEST)
    def test_embedded_images(self):
        image_filename = SAMPLE_IMAGE_FILENAME
        image_path = sample_image_path(image_filename)
        image_data = sample_image_content(image_filename)

        cid = attach_inline_image_file(self.message, image_path)
        html_content = '<p>This has an <img src="cid:%s" alt="inline" /> image.</p>' % cid
        self.message.attach_alternative(html_content, "text/html")

        self.message.send()
        data = self.get_api_call_data()
        self.assertEqual(data['html'], html_content)

        files = self.get_api_call_files()
        inlines = [value for (field, value) in files if field == 'inline']
        self.assertEqual(len(inlines), 1)
        self.assertEqual(inlines[0], (cid, image_data, "image/png"))  # filename is cid; type is guessed
        # Make sure neither the html nor the inline image is treated as an attachment:
        attachments = [value for (field, value) in files if field == 'attachment']
        self.assertEqual(len(attachments), 0)
    def test_embedded_images(self):
        image_filename = SAMPLE_IMAGE_FILENAME
        image_path = sample_image_path(image_filename)
        image_data = sample_image_content(image_filename)

        cid = attach_inline_image_file(self.message, image_path)
        html_content = '<p>This has an <img src="cid:%s" alt="inline" /> image.</p>' % cid
        self.message.attach_alternative(html_content, "text/html")

        self.message.send()
        data = self.get_api_call_data()
        self.assertEqual(data['html'], html_content)

        files = self.get_api_call_files()
        inlines = [value for (field, value) in files if field == 'inline']
        self.assertEqual(len(inlines), 1)
        self.assertEqual(inlines[0], (cid, image_data, "image/png"))  # filename is cid; type is guessed
        # Make sure neither the html nor the inline image is treated as an attachment:
        attachments = [value for (field, value) in files if field == 'attachment']
        self.assertEqual(len(attachments), 0)
Exemple #18
0
def attach_image(msg, url, file_path, selector, dimensions='1024x1024'):
    if 'selectedTab=map' in url:
        wait = 8000
        dimensions = '1000x600'
    elif 'selectedTab=chart' in url:
        wait = 1000
        dimensions = '800x600'
    elif 'selectedTab' in url:
        wait = 500
        dimensions = '800x600'
    else:
        wait = 1000
    cmd = '{cmd} "{host}{url}" {file_path} "{selector}" {dimensions} {wait}'
    cmd = (cmd.format(cmd=GRAB_CMD,
                      host=settings.GRAB_HOST,
                      url=url,
                      file_path=file_path,
                      selector=selector,
                      dimensions=dimensions,
                      wait=wait))
    result = subprocess.check_output(cmd, shell=True)
    logger.debug("Command %s completed with output %s" % (cmd, result.strip()))
    return attach_inline_image_file(msg, file_path, subtype='png')
import send_mail
sendmail("hi whats up!", "mail send from mailgun ",
          "Anymail Sender <*****@*****.**>", ["*****@*****.**"])

from Sparkpost.core.mail
import EmailMultiAlternatives
from anymail.message
import attach_inline_image_file

msg = EmailMultiAlternatives(
    subject=" activated your account",
    body="Click to activate your account: http://example.com/activate",
    from_email="Example <*****@*****.**>",
    to=["New User <*****@*****.**>", "*****@*****.**"],
    reply_to=["Helpdesk <*****@*****.**>"])

# Include an inline image in the html:
logo_cid = attach_inline_image_file(msg, "/path/to/logo.jpg")
html = """<img alt="Logo" src="cid:{logo_cid}">
          <p>Please <a href="http://example.com/activate">activate</a>
          your account</p>""".format(logo_cid=logo_cid)
msg.attach_alternative(html, "text/html")

# Optional Anymail extensions:
msg.metadata = {"user_id": "8675309", "experiment_variation": 1}
msg.tags = ["activation", "onboarding"]
msg.track_clicks = True

# Send it:
msg.send()