问题
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)
回答1:
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.
来源:https://stackoverflow.com/questions/4397938/attaching-an-ical-file-to-a-django-email