在 Django 中发送带有相同附件的批量电子邮件
我想向我的网站上要参加会议的成员(即客人)发送电子邮件,每个电子邮件都带有(相同的)PDF 附件。我使用 Django 的内置批量电子邮件功能(在 connection.send_messages(messages)
中)来完成此操作。目前我正在这样做:
guests = Guest.objects.all()
connection = mail.get_connection()
connection.open()
messages = []
for guest in guests:
msg = EmailMultiAlternatives(title, text_content, from_address, [guest.email], connection=connection)
msg.attach_alternative(html_content, 'text/html')
pdf_data = open(os.path.join(settings.MEDIA_ROOT, 'uploads/flyer.pdf'))
msg.attach('Invitation Card.pdf', pdf_data.read(), 'application/pdf')
pdf_data.close()
messages.append(msg)
connection.send_messages(messages)
connection.close()
现在,当我这样做时,将为每封电子邮件加载相同的 PDF 文件,单独附加,然后为每封电子邮件单独发送,就好像它是不同的 PDF 一样。如果文件大小为 10MB,那么这 10MB 将会为每位访客上传到我的邮件服务器,而该文件可能只上传一次。
所以问题是:是否可以一次将文件附加到所有电子邮件,从而也只上传一次?或者我只是做错了?
更新:
如果我将附加行更改为以下内容:
msg.attach_file(os.path.join(settings.MEDIA_ROOT, 'uploads/flyer.pdf'))
这会解决我的问题吗?
I want to send emails to members of my site who are to attend a meeting (ie. guests), each with (the same) PDF attachment. I'm doing this with Django's built-in bulk email functionality, in connection.send_messages(messages)
. At the moment I'm doing this:
guests = Guest.objects.all()
connection = mail.get_connection()
connection.open()
messages = []
for guest in guests:
msg = EmailMultiAlternatives(title, text_content, from_address, [guest.email], connection=connection)
msg.attach_alternative(html_content, 'text/html')
pdf_data = open(os.path.join(settings.MEDIA_ROOT, 'uploads/flyer.pdf'))
msg.attach('Invitation Card.pdf', pdf_data.read(), 'application/pdf')
pdf_data.close()
messages.append(msg)
connection.send_messages(messages)
connection.close()
Now, when I do it like this, the same PDF file will be loaded for every email, attached separately, and then sent separately for each email, as if it were different PDFs. If the file is 10MB, that 10MB will be uploaded to my mail server for every single guest, where it could have been only once.
So the question is: Is it possible to attach a file to all emails at once, thereby also only uploading it once? Or am I just plain doing it wrong?
UPDATE:
If I change the attach line to the following:
msg.attach_file(os.path.join(settings.MEDIA_ROOT, 'uploads/flyer.pdf'))
would that solve my problem?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
查看 django/core/mail/message.py 发现
attach_file
只是一个方便的函数,在调用attach
之前为您打开文件:您可以避免打开附件并阅读如果您子类化
EmailMultiAlternatives
并重写attach
方法,它会一遍又一遍地进入内存。您应该考虑使用作业/任务队列来实现此目的,例如 celery。Looking at django/core/mail/message.py reveals
attach_file
is merely a convenience function that opens the file for you before callingattach
:You could avoid opening the attachment and reading it into memory over and over again if you subclass
EmailMultiAlternatives
and override theattach
method. You should look into using a job/task queue for this like celery.