0

I'm trying to get an automated email sent from Python 3.8 containing a QR code (PNG) to a user at the moment of registration (like a event ticket). I managed to send the registration data (full name, date, etc.) but the QR image generated by qrcode package won't show up.

I'm not an advanced programmer so I thought someone here could help me.

Thanks in regards and greetings from Chile!

import qrcode 
from io import BytesIO
from PIL import Image 
from phonenumber_field.modelfields import PhoneNumberField
from sorl.thumbnail import get_thumbnail
from qrVip.settings import EMAIL_HOST


class GrupoVip(models.Model):
    rut = models.CharField(max_length=13, blank=False, null=False,)
    nombreCompleto = models.CharField(blank=False, null=False,max_length=200)
    email = models.EmailField(blank=False, max_length=254)
    vip = models.BooleanField( null=False)
    telefono = PhoneNumberField()
    autorizado  = models.BooleanField( null=False)
    codigoQr = models.ImageField(blank=True,null=True, verbose_name="Imagen QR", upload_to='CodigoQrVip/')
    evento = models.ForeignKey(evento, verbose_name="Evento", on_delete=models.CASCADE)
    embajador = models.ForeignKey(User, verbose_name="Embajador", on_delete=models.CASCADE,null=True)

    def __str__(self):
        txt = "{0} | {1} "
        
        return txt.format(self.rut.title(),self.nombreCompleto.title())
    
    @property
    def qr_preview(self):
        if self.codigoQr:
            _img = get_thumbnail(self.codigoQr,
                                   '350x150',
                                   upscale=False,
                                   crop=False,
                                   quality=100)
            return format_html('<img src="{}" width="{}" height="{}">'.format(_img.url, _img.width, _img.height))
        return ""
    
    def save(self, *args, **kwargs):
        qr_image = qrcode.make(f'http://192.168.18.2:8000/admin/adminVip/grupovip/?q={self.rut}&evento__id__exact={self.evento}')
        qr_offset = Image.new('RGB',(1000,1000),'white')
        qr_offset.paste(qr_image)
        files_name = f'{self.id}/{self.rut}/{self.nombreCompleto}-qr.png'
        stream = BytesIO()
        qr_offset.save(stream, 'PNG')
        self.codigoQr.save(files_name, File(stream), save=False)
        qr_offset.close()

        ##########################################################################
        # send_mail('Terminamos el Proyecto BB',
        #         f'Aqui desde mi casita mandandote este mensaje bbsote {self.codigoQr}',
        #         EMAIL_HOST_USER,
        #         [self.email],
        #         fail_silently=False,
        #     )
       
       ########################################################

        # subject = 'Django sending email'
        # body_html = '''
        # <html>
        #     <body>
                
        #         <img src="cid:image" />
        #     </body>
        # </html>
        # '''

        # msg = EmailMultiAlternatives(
        #     subject,
        #     body_html,
        #     from_email=EMAIL_HOST_USER,
        #     to=[self.email]
        # )
        
        # img_dir = '/media/'
        # image = f'CodigoQrVip/None/{self.rut}/{self.nombreCompleto.replace(" ","_")}-qr.png'
        # file_path = os.path.join(img_dir, image)
        # with open(file_path,'r') as f:
        #     img = MIMEImage(f.read())
        #     img.add_header('Content-ID', '<{name}>'.format(name=image))
        #     img.add_header('Content-Disposition', 'inline', filename=image)
        # msg.attach(img)
        ###################################################################
        html_content = render_to_string("emailQrListo.html",{'title':'test email','grupovip':GrupoVip.objects.all()} )
        text_content = strip_tags(html_content)

        env_email = EmailMultiAlternatives(
            #subject
            "testing",
            #contenido
            text_content,
            #from
            EMAIL_HOST_USER,
            #rec list 
            [self.email]
        )
        env_email.attach_alternative(html_content, "image/html")
        env_email.send()
        super().save(*args, **kwargs)

EDIT: I'm trying to renderize that image from an html template. Here's the code:

<!DOCTYPE html> {% load static %}

<html lang="en">
  <head>
    <title>{{title}}</title>
  </head>

  <body>

    <div class='container'>
        <h2>LISTA MURCANO</h2>
        <img src="cid:{{grupovip.codigoQr}}">

  </body>
</html>
  • 3
    I don't see where you are inserting or attaching the image. An image can either be done as an attachment with the `` syntax, or as an inline image by base64-encoding the bytes. – Tim Roberts Aug 17 '22 at 19:39
  • Thanks for your response. I'm trying to renderize that image from an html template. I'll put the code in the post. – Cristóbal S. Cigarroa C. Aug 17 '22 at 20:04
  • Yes, @TimRoberts is right...simple solution is converting the image to a data URI. I haven't tested this link but it will render in your email as there is no external data point to load: https://dopiaza.org/tools/datauri/index.php do something similar. – ViaTech Aug 17 '22 at 20:11
  • We got it! Thanks for your responses! – Cristóbal S. Cigarroa C. Aug 18 '22 at 16:21
  • @CristóbalS.CigarroaC. could you post the solution to answer your own question? – Craig P Mar 30 '23 at 00:33

0 Answers0