开发者

Attaching an ical file to a django email

开发者 https://www.devze.com 2023-01-30 05:59 出处:网络
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.

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'
    ret开发者_StackOverflow社区urn response

But this is not working:

   myicalfile = ical()
   message.attach(myicalfile)


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消