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

Pho*_*beB 8 django django-email

有很多关于如何将文件附加到电子邮件的示例,但我找不到有关如何附加 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
Run Code Online (Sandbox Code Playgroud)

但这不起作用:

   myicalfile = ical()
   message.attach(myicalfile)
Run Code Online (Sandbox Code Playgroud)

edg*_*ars 4

在 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
Run Code Online (Sandbox Code Playgroud)

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