有很多关于如何将文件附加到电子邮件的示例,但我找不到如何附加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)
最佳答案 在def(()的末尾尝试这段代码:
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
当然,应将导入代码移动到文件顶部以符合编码标准.