Hi list, I'm new around though I've been developing Django sites since the 
early 1.0 releases

I've been looking around for problems regarding email sending to BCC 
addresses but can't find anything that explains what I'm seeing.

I have a ModelForm that renders a pretty simple contact form, and on POST 
the instance of the model gets saved. In that method, I've implemented a 
simple email sending step and then it continues normally. Code is on bottom.
I've tried this with both EmailMultiAlternatives and EmailMessage, and with 
the IMAP and Console email backends, and on my local machine and on remote 
servers (webfaction).
The emails always go to the address in the "To" field, but the "BCC" ones, 
no matter if it's only one and the same than "To" or if they are a few 
different emails never receive anything.
On both the IMAP and the Console backends I get output similar to this:

---------- MESSAGE FOLLOWS ----------
Content-Type: multipart/alternative;
 boundary="===============1548201696055964499=="
MIME-Version: 1.0
Subject: Nuevo mensaje de test12 recibido en example.com
From: direcc...@example.com
To: tes...@test.es
Date: Thu, 05 Jul 2012 10:06:59 -0000
Message-ID: <20120705100659.9464.36431@i5-750>
X-Peer: 127.0.0.1
--===============1548201696055964499==
Content-Type: text/plain; charset="utf-8"
MIME-Version: 1.0
Content-Transfer-Encoding: 8bit
Hola test12, acabamos de recibir tu mensaje y nos pondremos en contacto 
contigo lo antes posible.
ab7 Cosmética
--===============1548201696055964499==
Content-Type: text/html; charset="utf-8"
MIME-Version: 1.0
Content-Transfer-Encoding: 8bit
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8" /> 
<meta http-equiv="content-language" content="es" />
</head>
<body>
<p>Hola test12, acabamos de recibir tu mensaje y nos pondremos en contacto 
contigo lo antes posible.</p>
<p><img src="http://example.com/media/configuracion/ab7_logo.png"; alt="ab7 
Cosmética" />ab7 Cosmética<br/></p>
</body>
--===============1548201696055964499==--
------------ END MESSAGE ------------


Notice that, if you look at the headers, there is no sight of "BCC" fields 
or addresses. I've looked at the variables that contains the BCC addresses 
and they look right, something like [u'f...@mail.com', u'b...@mail.com'].
Also, if I check msg.recipients() I get a full list of every addresses, 
both To and BCC, what anyone would expect.
I've changed the bcc parameter to cc on the construction of the message 
instance and it appears on the headers of the message and gets delivered to 
the emails.

So, any idea of what may be happening? I'm pretty lost right now and don't 
know what else try to fix this :-/

Original code follows:

# -*- coding: utf-8 -*-
'''
    Javier Romero
    Desarrollado por Barrabarra
    web: http://barrabarra.es
    Fecha: 2012
'''
from django.conf import settings
from django.contrib.sites.models import Site
from django.contrib.sites.managers import CurrentSiteManager
from django.core.mail import EmailMessage, EmailMultiAlternatives
from django.db import models
from django.db.models.signals import post_save
from django.template.loader import render_to_string
from django.utils.translation import ugettext_lazy as _
from catalog.models import Product
from configuracion.models import Configuracion
from sorl.thumbnail import ImageField

class ContactConfig(models.Model):
    """
    Contact main configuration, contains title and description for both 
form and sent pages
    """
    contacto_titulo     = models.CharField(verbose_name=_(u'Título de la 
página de contacto'), max_length=120)
    contacto_texto      = models.TextField(verbose_name=_(u'Contenido'), 
blank=True,)
    contacto_analytics  = models.TextField(verbose_name=_(u'Analytics de la 
página de contacto'), blank=True,)
    contacto_imagen     = ImageField(_(u'Imagen de la página de contacto'), 
blank=True, upload_to='contacto')
    
    exito_titulo        = models.CharField(verbose_name=_(u'Título de la 
página de formulario enviado'), max_length=120)
    exito_texto         = models.TextField(verbose_name=_(u'Contenido'), 
blank=True,)
    exito_analytics     = models.TextField(verbose_name=_(u'Analytics de la 
página de formulario enviado'), blank=True,)
    exito_imagen        = ImageField(_(u'Imagen de la página de formulario 
enviado'), blank=True, upload_to='contacto')
    
    analytics_contacto  = models.TextField(verbose_name=_(u'Analytics del 
botón de formulario de contacto completo'), blank=True,)
    analytics_contactame = models.TextField(verbose_name=_(u'Analytics del 
botón de formulario de contacto rápido'), blank=True,)
    
    creado_el           = models.DateTimeField(_(u'Creado el'), 
editable=False, auto_now_add=True)
    actualizado_el      = models.DateTimeField(_(u'Actualizado el'), 
editable=False, auto_now=True)
    
    class Meta:
        verbose_name = _(u'Configuración de contacto')
        verbose_name_plural = _(u'Configuración de contacto')

class NotificationEmail(models.Model):
    """
    Email addresses to be notified when contact forms are sent,
    editable on admin instead of putting them on the settings file
    """
    
    configuracion       = models.ForeignKey(ContactConfig, 
verbose_name=_(u'Configuración de contacto'))
    email               = models.EmailField(verbose_name=_(u'Correo 
Electrónico'))
    
    def __unicode__(self):
        return self.email

class Message(models.Model):
    # contact info
    fecha       = models.DateTimeField(auto_now_add=True)
    ip          = models.IPAddressField(_(u'IP'))
    
    nombre      = models.CharField(_(u'Nombre'), max_length=150)
    email       = models.EmailField(_(u'Email'), max_length=150)
    telefono    = models.CharField(_(u'Teléfono'), max_length=9, null = 
True, blank = True)
    mensaje     = models.TextField(_(u'Mensaje'), max_length=256, null = 
True, blank = True)
    condiciones = models.BooleanField(_(u'Condiciones aceptadas'), 
default=False)
       
    class Meta:
        ordering = ['-fecha',]
        verbose_name = _(u'Mensaje recibido')
        verbose_name_plural = _(u'Mensajes recibidos') 

    def save(self, *args, **kwargs):
        current_site    = Site.objects.get_current()
        config          = ContactConfig.objects.get(id=1)
        subject         = 
render_to_string('contact/emails/contact-subject.txt', {'message': self, 
'site_name': current_site.name})
        text_content    = 
render_to_string('contact/emails/contact-body-text.txt', {'message': self, 
'current_site': current_site })
        html_content    = 
render_to_string('contact/emails/contact-body-html.html', {'message': 
self,'current_site': current_site })
        sender          = 'direccion@%s' % current_site.domain
        recipients      = [self.email,]
        cco             = [n.email for n in 
config.notificationemail_set.all()]
    
        # If we try with EmailMessage it also fails, nothing is received on 
the cco addresses
        #msg = EmailMessage(subject, text_content, from_email=sender, 
to=recipients, bcc=cco)
        msg = EmailMultiAlternatives(subject, text_content, 
from_email=sender, to=recipients, cc=cco)
        msg.attach_alternative(html_content, "text/html")
        msg.send()
        super(Message, self).save(*args, **kwargs) # Call the "real" save() 
method.

 

    def __unicode__(self):
        return _(u'Mensaje de %(name)s el %(date)s') % {'name': 
self.nombre, 'date': self.fecha}

class Response(models.Model):
    fecha       = models.DateTimeField(auto_now_add=True)
    nombre      = models.CharField(_(u'Nombre'), max_length=150)
    email       = models.EmailField(_(u'Email'), max_length=150)
    asunto      = models.CharField(_(u'Asunto'), max_length=150)
    mensaje     = models.TextField(_(u'Mensaje'), max_length=256, null = 
True, blank = True)  
    adjunto     = models.FileField(_(u'Adjunto'), 
upload_to='contact/response', blank=True, null=True)
    def __unicode__(self):
        return _(u'Mensaje para %(name)s (%(email)s)') % {'name': 
self.nombre, 'email': self.email}
    
    # Enviar el email tras guardar el fichero
    def save(self, *args, **kwargs):
        super(Response, self).save(*args, **kwargs) # Call the "real" 
save() method.
        #if self.pk == None:
        current_site    = Site.objects.get_current()
        config          = ContactConfig.objects.get(id=1)
        subject         = 
render_to_string('contact/emails/response-subject.txt', {'response': self, 
'site_name': current_site.name})
        text_content    = 
render_to_string('contact/emails/response-body-text.txt', {'response': 
self, 'current_site': current_site })
        html_content    = 
render_to_string('contact/emails/response-body-html.html', {'response': 
self,'current_site': current_site })
        
        sender      = 'direccion@%s' % current_site.domain
        recipients  = [self.email,]
        cco         = [n.email for n in config.notificationemail_set.all()]
        
        # Also happens here :(

        msg = EmailMultiAlternatives(subject, text_content, 
from_email=sender, to=recipients, bcc=cco)
        msg.attach_alternative(html_content, "text/html")
        if self.adjunto:
            msg.attach_file("%s/%s" % (settings.MEDIA_ROOT, 
self.adjunto.name))
        msg.send()

    class Meta:
        verbose_name = _(u'Mensaje enviado')
        verbose_name_plural = _(u'Mensajes enviados')


-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To view this discussion on the web visit 
https://groups.google.com/d/msg/django-users/-/s-1d1GPItHAJ.
To post to this group, send email to django-users@googlegroups.com.
To unsubscribe from this group, send email to 
django-users+unsubscr...@googlegroups.com.
For more options, visit this group at 
http://groups.google.com/group/django-users?hl=en.

Reply via email to