2011-09-28 8 views
10

Provo a creare un'applicazione di newsletter e desidero inviare 50 e-mail con una connessione. send_mass_mail() sembra perfetto ma non riesco a capire come lo chiamo in combinazione con EmailMultiAlternatives.send_mass_emails con EmailMultiAlternatives

Questo è il mio codice che invia una sola e-mail con un collegamento:

html_content = render_to_string('newsletter.html', {'newsletter': n,})    
text_content = "..."      
msg = EmailMultiAlternatives("subject", text_content, "[email protected]", ["[email protected]"])          
msg.attach_alternative(html_content, "text/html")                                            
msg.send() 

un esempio di lavoro con il codice di cui sopra e send_mass_mail sarebbe grande, grazie!

risposta

12

Non è possibile utilizzare direttamente send_mass_mail() con EmailMultiAlternatives. Tuttavia, in base a the Django documentation, send_mass_mail() è semplicemente un wrapper che utilizza la classe EmailMessage. EmailMultiAlternatives è una sottoclasse di EmailMessage. EmailMessage ha un parametro 'connessione' che consente di specificare una singola connessione da utilizzare quando si invia il messaggio a tutti i destinatari, ovvero la stessa funzionalità fornita da send_mass_mail(). È possibile utilizzare la funzione get_connection() per ottenere una connessione SMTP come definito da SMTP settings in settings.py.

Credo che il seguente codice (non testato) dovrebbe funzionare:

from django.core.mail import get_connection, EmailMultiAlternatives 

connection = get_connection() # uses SMTP server specified in settings.py 
connection.open() # If you don't open the connection manually, Django will automatically open, then tear down the connection in msg.send() 

html_content = render_to_string('newsletter.html', {'newsletter': n,})    
text_content = "..."      
msg = EmailMultiAlternatives("subject", text_content, "[email protected]", ["[email protected]", "[email protected]", "[email protected]"], connection=connection)          
msg.attach_alternative(html_content, "text/html")                                            
msg.send() 

connection.close() # Cleanup 
+0

Grazie per la risposta, ma ogni utente può vedere tutti gli altri utenti nel campo "A". Voglio un solo destinatario per posta. – gustavgans

+1

Utilizzare 'bcc' ad esempio: msg = EmailMultiAlternatives ("oggetto", text_content, "da @ bla", ["a @ bla"], bcc = ["to2 @ bla", "to3 @ bla"], connessione = connessione) – msanders

+0

ok che funziona, grazie mille. – gustavgans

20

Cioè send_mass_mail() riscritto da usare EmailMultiAlternatives:

from django.core.mail import get_connection, EmailMultiAlternatives 

def send_mass_html_mail(datatuple, fail_silently=False, user=None, password=None, 
         connection=None): 
    """ 
    Given a datatuple of (subject, text_content, html_content, from_email, 
    recipient_list), sends each message to each recipient list. Returns the 
    number of emails sent. 

    If from_email is None, the DEFAULT_FROM_EMAIL setting is used. 
    If auth_user and auth_password are set, they're used to log in. 
    If auth_user is None, the EMAIL_HOST_USER setting is used. 
    If auth_password is None, the EMAIL_HOST_PASSWORD setting is used. 

    """ 
    connection = connection or get_connection(
     username=user, password=password, fail_silently=fail_silently) 
    messages = [] 
    for subject, text, html, from_email, recipient in datatuple: 
     message = EmailMultiAlternatives(subject, text, from_email, recipient) 
     message.attach_alternative(html, 'text/html') 
     messages.append(message) 
    return connection.send_messages(messages) 
+0

Come usare questo? Ho aggiunto questa funzione in script mypy ma non riesco a trovare get_connection. – Stillmatic1985

+1

Hey @ Stillmatic1985, ho appena aggiunto la riga di importazione nel codice sopra – semente

2

ho seguito un approccio misto, l'invio agli utenti di entrambi testo normale e messaggi html e messaggi personalizzati per ogni utente.

Ho iniziato dalla sezione Sending multiple emails della documentazione di Django.

from django.conf import settings 
from django.contrib.auth.models import User 
from django.core import mail 
from django.core.mail.message import EmailMultiAlternatives 
from django.template.loader import get_template 
from django.template import Context 

... 

connection = mail.get_connection() 
connection.open() 
messages = list() 

for u in users: 
    c = Context({ 'first_name': u.first_name, 'reseller': self,}) 
    subject, from_email, to = 'new reseller', settings.SERVER_EMAIL, u.email 
    text_content = plaintext.render(c) 
    html_content = htmly.render(c) 
    msg = EmailMultiAlternatives(subject, text_content, from_email, [to]) 
    msg.attach_alternative(html_content, "text/html") 
    messages.append(msg) 

connection.send_messages(messages) 
connection.close() 
+1

Django 1.10 - Non è necessario aprire e chiudere la connessione manualmente. Da Django [docs] (https://docs.djangoproject.com/en/1.10/topics/email/#topics-sending-multiple-emails) 'connection.send_messages (messages)' ----- 'send_messages () apre una connessione sul back-end, invia l'elenco dei messaggi e quindi chiude nuovamente la connessione –

2

questo è come fare l'operazione (codice testato):

from html2text import html2text 

from django.utils.translation import ugettext as _ 
from django.core.mail import EmailMultiAlternatives, get_connection 


def create_message(subject, message_plain, message_html, email_from, email_to, 
        custom_headers=None, attachments=None): 
    """Build a multipart message containing a multipart alternative for text (plain, HTML) plus 
    all the attached files. 
    """ 
    if not message_plain and not message_html: 
     raise ValueError(_('Either message_plain or message_html should be not None')) 

    if not message_plain: 
     message_plain = html2text(message_html) 

    return {'subject': subject, 'body': message_plain, 'from_email': email_from, 'to': email_to, 
      'attachments': attachments or(), 'headers': custom_headers or {}} 


def send_mass_html_mail(datatuple): 
    """send mass EmailMultiAlternatives emails 
    see: http://stackoverflow.com/questions/7583801/send-mass-emails-with-emailmultialternatives 
    datatuple = ((subject, msg_plain, msg_html, email_from, email_to, custom_headers, attachments),) 
    """ 
    connection = get_connection() 
    messages = [] 
    for subject, message_plain, message_html, email_from, email_to, custom_headers, attachments in datatuple: 
     msg = EmailMultiAlternatives(
      **create_message(subject, message_plain, message_html, email_from, email_to, custom_headers, attachments)) 
     if message_html: 
      msg.attach_alternative(message_html, 'text/html') 
     messages.append(msg) 

    return connection.send_messages(messages) 
0

Ecco una versione succinta:

from django.core.mail import get_connection, EmailMultiAlternatives 

def send_mass_html_mail(subject, message, html_message, from_email, recipient_list): 
    emails = [] 
    for recipient in recipient_list: 
     email = EmailMultiAlternatives(subject, message, from_email, [recipient]) 
     email.attach_alternative(html_message, 'text/html') 
     emails.append(email) 
    return get_connection().send_messages(emails) 
Problemi correlati