0

I want to create email via EmailMultiAlternatives but I have image data as base64 - from POST data. And I want to send it as attachment via email.

For now I have (view):

    ctx = { 'username': request.user.username, 'img': request.POST['image'] }

    subject, from_email, to = 'Hello', 'mailfrom@server', 'mailto@server'
    text_content = 'text only'
    html_content = render_to_string('visemail.html', ctx)
    msg = EmailMultiAlternatives(subject, text_content, from_email, [to])
    msg.attach_alternative(html_content, "text/html")
    msg.send()

template:

<img src="{{ img }}" />

But I get email with text:

<img src="data:image/jpeg;base64,/9j/4AAQSkZJRgABAQAAAQABAAD/2wBDAAMCAgICAgMCAgIDAwMDBAYEBAQEBAgGBgUGCQgKCgkICQkKDA8MCgsOCwkJDRENDg8QEBEQCgwSExIQEw8QEBD/2wBDAQMDAwQDBAgEBAgQCwkLEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEB....

I do not see the picture in content. So I want to send this image as attachment maybe.

How to do this?

Nips
  • 13,162
  • 23
  • 65
  • 103

3 Answers3

1

Ok, I add:

    img_data = request.POST['image']

    img = MIMEImage(img_data[img_data.find(",")+1:].decode('base64'), 'jpeg')
    img.add_header('Content-Id', '<file>')
    img.add_header("Content-Disposition", "inline", filename="file.jpg")
    msg.attach(img)

and it works for me.

Nips
  • 13,162
  • 23
  • 65
  • 103
0

You could convert first your base64 img to PNG, and then send it as an attached file.

im_png = Image.open(BytesIO(base64.b64decode(img)))
im_png.save('image.png', 'PNG')
Diego
  • 11
  • 2
-1

for python 3.6 I did:

import base64

...

    img = MIMEImage(base64.b64decode(img_data[img_data.find(",")+1:].encode('ascii')), 'jpeg')

...