Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Attaching an ical file to a django email

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)
like image 987
PhoebeB Avatar asked Dec 09 '10 11:12

PhoebeB


1 Answers

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.

like image 57
edgars Avatar answered Oct 12 '22 12:10

edgars