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

8

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

从文档中可以看到:附件“这些可以是email.MIMEBase.MIMEBase实例,或者是(文件名,内容,MIME类型)三元组。”

因此,我在函数中成功地生成了一个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)

我的icalfile变量是如何创建的?它真的是一个email.MIMEBase.MIMEBase实例吗? - edgars
我需要进行编辑以使得我的icalfile来源更加清晰,它不是一个电子邮件的MIMEBase,因为我不确定如何创建一个! - PhoebeB
你尝试过使用“HttpResponse(icalstream, content_type='text/calendar')”而不是“mimetype”吗? - Henning Lee
1个回答

4

在 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

当然,为符合编码标准,导入代码应该放在文件顶部。

我该如何将此发送到特定的电子邮件地址? - Wagh

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接