我正在使用django发送大量电子邮件的服务。 我有这种方法,可以很好地与芹菜一起使用
@shared_task(bind=True)
def send_mails(self,saved_id):
text = BroadCast.objects.get(id=saved_id)
attendees = EventAttendee.objects.filter(event__id=text.id)
message = text.body
subject = text.subject
document = text.attachment
recipient_list=[]
for attend in attendees:
text_content = render_to_string(template_text, {'name': attend.client_name, 'message':message})
html_content = render_to_string(template_html, {'name': attend.client_name,'message':message})
mail.send(
[attend.client_email],
email_from,
subject=subject,
html_message=html_content,
attachments = {str(document):document}
)
我的挑战是,例如如果我有1000名与会者,我将不得不打开1000个连接,我认为这是非常糟糕的。
如何重新构造它,以便仅打开一个连接并能够发送1000封电子邮件。
答案 0 :(得分:2)
django.core.mail.send_mass_mail()用于处理大量电子邮件。
由于要发送html,因此需要额外的步骤,请考虑以下stackoverflow answer中的以下代码:
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)
答案 1 :(得分:0)