pythondjangowinapiwin32com

How do I add styles to html_body in Django with win32?


I am trying to send emails through Django using the win32 library, but the HTML styles are not being applied. The styles in the head work sporadically, and the styles in the body also work sporadically

    pythoncom.CoInitialize()
   
    dynamic_link='prueba'

    try:
        # Obtén todos los ingenieros con sus nombres concatenados
        outlook = win32.Dispatch('Outlook.Application')
        mail = outlook.CreateItem(0)

        # Configurar el remitente
        mail.SentOnBehalfOfName = 'example@outlook.com'

        mail.To = adminEmail
        mail.Subject = 'NUEVA SOLICITUD DE PRUEBAS DE LABORATORIO'
        html_body = f"""
            <html>
            <head>
                <style>
                    body {{
                        font-family: Arial, sans-serif;
                        padding: 20px;
                    }}
                    h1, p {{
                        color: #333;
                    }}
                    .background-red {{
                        background-color: red;
                    }}
                    #button {{
                        display: inline-block;
                        padding: 10px 20px;
                        background-color: #4CAF50;
                        color: #fff;
                        text-decoration: none;
                        border-radius: 5px;
                    }}
                </style>
            </head>
            <body class="background-red">
                <h1>Solicitud de pruebas de laboratorio</h1>
                <p>Nueva solicitud pruebas de laboratorio del usuario {FullName}</p>

                <div style="width: 130px; height:130px; background-color:white;">
                    <p>El usuario {FullName} ha creado una nueva solicitud de pruebas de laboratorio para el cliente {customer} con una fecha requerida para el {require_date}</p>
                </div>
                <a href="{dynamic_link}" id="button">Ir a la página</a>
            </body>
            </html>
            """
        mail.HTMLBody = html_body
        mail.Send()
        return Response({"message": "Correo enviado correctamente"}, status=status.HTTP_200_OK)
    except Exception as e:
         print(f"Error: {e}")

    finally:
        # Liberar recursos
        pythoncom.CoUninitialize()

Solution

  • Email templates can be quite tricky to handle due to the varying ways in which different platforms or email applications render them. The issue you're having is a very common issue in HTML email templates where styles defined in the tag are not consistently applied. Many email clients, including Outlook, have limited or inconsistent support for styles defined in the <head> or within <style> tags.

    The most reliable approach for styling HTML emails will be to to use inline CSS where possible or use images if custom buttons or some modern style necessary for a particular section.

    Inline styles have the highest priority and are generally well-supported across most email clients. By using inline CSS, you can significantly increase the likelihood that your email will render as intended across various platforms. You can check which HTML tags and CSS style is supported by visiting "The Ultimate Guide to CSS for Email clients"

    In your case you can modify the html_body like this where I applied all necessary CSS as inline style (change as necessery):

    html_body = f"""
        <html>
        <body style="font-family: Arial, sans-serif; padding: 20px; background-color: red;">
            <h1 style="color: #333;">Solicitud de pruebas de laboratorio</h1>
            <p style="color: #333;">Nueva solicitud pruebas de laboratorio del usuario {FullName}</p>
    
            <div style="width: 130px; height: 130px; background-color: white; color: #333;">
                <p>El usuario {FullName} ha creado una nueva solicitud de pruebas de laboratorio para el cliente {customer} con una fecha requerida para el {require_date}</p>
            </div>
            <a href="{dynamic_link}" style="display: inline-block; padding: 10px 20px; background-color: #4CAF50; color: #fff; text-decoration: none; border-radius: 5px;">Ir a la página</a>
        </body>
        </html>
    """