Attaching an ical file to a django email

。_饼干妹妹 提交于 2019-12-05 02:05:31

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!