Issues with sending emails through Outlook using the Win32 library in Django

60 Views Asked by At

I'm using Win32 for sending emails on my website.

In general, the emails are sent and reach the recipient, but the problem is that the recipient does not change.

Initially, when I started this project, I used a single test email to use in different scenarios. This email was "[email protected]". Later, I added another email for another user named User 2 with their own email "[email protected]".

The problem is that the recipient does not change. I specifically select that my recipient is "[email protected]", but I always receive all emails at "[email protected]".

outlook = win32.Dispatch('Outlook.Application')
mail = outlook.CreateItem(0)
mail.SentOnBehalfOfName = '[email protected]'
mail.To = email
mail.Subject = 'NUEVA SOLICITUD DE PRUEBAS DE LABORATORIO'
mail.BodyFormat = 2
html_body = f"""
    <html>
    <body style="font-family: 'Arial', sans-serif; background-color: #f4f4f4; margin: 0; padding: 0;">
        <div style="max-width: 600px; margin: 20px auto; background-color: #ffffff; padding: 20px; border-radius: 5px; box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);">
        <h1 style="color: #333; margin-bottom: 10px;">Nueva solicitud de pruebas de laboratorio de {full_name}</h1>
        <p style="color: #555; margin-bottom: 20px;">El usuario {full_name} ha creado una nueva solicitud de pruebas de laboratorio para el cliente {customer} con una fecha requerida para el {require_date}. A continuación, se detallan más información y enlaces:</p>

        <ul style="list-style-type: none; padding: 0;">
            <li><strong>Cliente:</strong> {customer}</li>
            <li><strong>Usuario:</strong> {full_name}</li>
            <li><strong>Fecha requerida:</strong> {require_date}</li>
            <li><strong>Enlace al sitio:</strong> <a href="{dynamic_link}" style="color: #007BFF; text-decoration: none;">Ir al Sitio</a></li>
        </ul>

        <div style="margin-top: 20px; border-top: 1px solid #ddd; padding-top: 20px;">
            <p style="color: #888; font-size: 14px;">Este correo electrónico fue generado automáticamente. Por favor, no responda a este correo.</p>
        </div>
        </div>
    </body>
    </html>
    """
mail.HTMLBody = html_body

mail.Send()
           
# Forzar la sincronización para enviar el correo inmediatamente
outlook_namespace = outlook.GetNamespace("MAPI")
sync_objects = outlook_namespace.SyncObjects
for sync_object in sync_objects:
    sync_object.Start()

The code I use to assign the recipient is as follows, considering that I have previously verified that the email is correctly written in the database.

engineer_instance = get_object_or_404(Engineers, role='admin')
            engineer_serializer = EnginnerAdminSerializer(engineer_instance)
            email = engineer_serializer.data['email']
0

There are 0 best solutions below