2011-09-28 15 views
10

Tôi cố gắng xây dựng một ứng dụng bản tin và muốn gửi 50 email với một kết nối. send_mass_mail() trông hoàn hảo nhưng tôi không thể tìm ra cách tôi gọi điều này kết hợp với EmailMultiAlternatives.send_mass_emails với EmailMultiAlternatives

Đây là mã của tôi mà chỉ gửi một email với một kết nối:

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() 

một ví dụ làm việc với các mã trên và send_mass_mail sẽ là tuyệt vời, cảm ơn!

Trả lời

12

Không thể trực tiếp sử dụng send_mass_mail() với EmailMultiAlternatives. Tuy nhiên, theo the Django documentation, send_mass_mail() chỉ đơn giản là một trình bao bọc sử dụng lớp EmailMessage. EmailMultiAlternatives là một lớp con của EmailMessage. EmailMessage có tham số 'kết nối' cho phép bạn chỉ định một kết nối duy nhất để sử dụng khi gửi thư tới tất cả người nhận - tức là chức năng tương tự như được cung cấp bởi send_mass_mail(). Bạn có thể sử dụng chức năng get_connection() để nhận kết nối SMTP như được xác định bởi SMTP settings trong settings.py.

Tôi tin rằng sau (chưa được kiểm tra) mã nên làm việc:

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

Cám ơn câu trả lời của bạn, nhưng mỗi người dùng có thể xem tất cả các người dùng khác trong trường "TO". Tôi chỉ muốn một người nhận mỗi thư. – gustavgans

+1

Sử dụng 'bcc' ví dụ: msg = EmailMultiAlternatives ("subject", text_content, "từ @ bla", ["đến @ bla"], bcc = ["to2 @ bla", "to3 @ bla"], kết nối = kết nối) – msanders

+0

ok hoạt động, cảm ơn rất nhiều. – gustavgans

20

Đó là send_mass_mail() viết lại để sử dụng 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

Cách sử dụng? Tôi đã thêm Funtion này trong tập lệnh mypy nhưng không thể tìm thấy get_connection. – Stillmatic1985

+1

Hey @ Stillmatic1985, tôi vừa thêm dòng nhập trong mã ở trên – semente

2

Tôi đi theo một cách tiếp cận hỗn hợp, gửi cho người dùng cả hai văn bản đơn giản và tin nhắn html và cá nhân hóa tin nhắn cho mọi người dùng.

Tôi bắt đầu từ phần Sending multiple emails tài liệu od 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 - Không cần mở và đóng kết nối theo cách thủ công. Từ Django [tài liệu] (https://docs.djangoproject.com/en/1.10/topics/email/#topics-sending-multiple-emails) 'connection.send_messages (thư)' ----- 'send_messages () mở một kết nối trên backend, gửi danh sách các tin nhắn, và sau đó đóng lại kết nối. –

2

Đây là cách tôi làm nhiệm vụ (kiểm tra mã):

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

Dưới đây là một phiên bản ngắn gọn:

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) 
Các vấn đề liên quan