将 ical 文件附加到 django 电子邮件

发布于 2024-10-06 15:47:03 字数 942 浏览 1 评论 0原文

有很多关于如何将文件附加到电子邮件的示例,但我找不到如何附加 MIMEBase 实例的示例。

来自文档:附件“这些可以是 email.MIMEBase.MIMEBase 实例,或(文件名、内容、mimetype)三元组。”

所以我在函数中生成一个 iCal 文件就很好了:

def ical()
    cal = vobject.iCalendar()
    cal.add('method').value = 'PUBLISH'  # IE/Outlook needs this

    vevent = cal.add('vevent')
    vevent.add('dtstart').value = self.course.startdate
    vevent.add('dtend').value = self.course.startdate
    vevent.add('summary').value='get details template here or just post url'
    vevent.add('uid').value=str(self.id)
    vevent.add('dtstamp').value = self.created

    icalstream = cal.serialize()
    response = HttpResponse(icalstream, mimetype='text/calendar')
    response['Filename'] = 'shifts.ics'  # IE needs this
    response['Content-Disposition'] = 'attachment; filename=shifts.ics'
    return response

但这不起作用:

   myicalfile = ical()
   message.attach(myicalfile)

There are plenty of examples of how to attach a file to an email, but I can't find an example of how to attach a MIMEBase instance.

From the docs: attachments "These can be either email.MIMEBase.MIMEBase instances, or (filename, content, mimetype) triples."

So I'm generating an iCal file in a function just fine:

def ical()
    cal = vobject.iCalendar()
    cal.add('method').value = 'PUBLISH'  # IE/Outlook needs this

    vevent = cal.add('vevent')
    vevent.add('dtstart').value = self.course.startdate
    vevent.add('dtend').value = self.course.startdate
    vevent.add('summary').value='get details template here or just post url'
    vevent.add('uid').value=str(self.id)
    vevent.add('dtstamp').value = self.created

    icalstream = cal.serialize()
    response = HttpResponse(icalstream, mimetype='text/calendar')
    response['Filename'] = 'shifts.ics'  # IE needs this
    response['Content-Disposition'] = 'attachment; filename=shifts.ics'
    return response

But this is not working:

   myicalfile = ical()
   message.attach(myicalfile)

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

陌伤浅笑 2024-10-13 15:47:03

在 def ical() 的末尾尝试此代码:

from email.mime.text import MIMEText
part = MIMEText(icalstream,'calendar')
part.add_header('Filename','shifts.ics') 
part.add_header('Content-Disposition','attachment; filename=shifts.ics') 
return part

当然,导入代码应移至文件顶部以符合编码标准。

Try this code at the end of def ical():

from email.mime.text import MIMEText
part = MIMEText(icalstream,'calendar')
part.add_header('Filename','shifts.ics') 
part.add_header('Content-Disposition','attachment; filename=shifts.ics') 
return part

Of course, the import code should be moved at the top of file to conform with coding standards.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文