使用python发送outlook约会提醒邮件

今天突然有一个自动发送会议邀请邮件的需求,因为需要用到发送outlook的约会提醒,所以到网络上找了一些资料。有用微软的outlook API实现的,但是这个有一个问题,就是必须在本地安装有outlook并且具有一个available的账户被登录。如果因为这个而向公司申请一个单独的邮件账号比较麻烦也不是很现实。于是找到了另一个python的第三方库,利用smtp实现。
icalendar.rar,附件是附带的第三方库,下载安装即可
利用python发送提醒的代码如下:

import email.MIMEText
 
import email.MIMEBase
 
from email.MIMEMultipart import MIMEMultipart
 
import smtplib
 
import datetime
 
import icalendar
 
      
 
def sendAppointment(self, subj, description):
 
      reminderHours = 1
 
      startHour = 7
 
      start = datetime.datetime.combine(self.date, datetime.time(startHour, 0, 0))
 
      cal = icalendar.Calendar()
 
      cal.add('prodid', '-//My calendar application//example.com//')
 
      cal.add('version', '2.0')
 
      cal.add('method', "REQUEST")
 
      event = icalendar.Event()
 
      event.add('attendee', self.getEmail())
 
      event.add('organizer', "me@example.com")
 
      event.add('status', "confirmed")
 
      event.add('category', "Event")
 
      event.add('summary', subj)
 
      event.add('description', description)
 
      event.add('location', "Room 101")
 
      event.add('dtstart', start)
 
      event.add('dtend', datetime.datetime.combine(self.date, datetime.time(startHour + 1, 0, 0)))
 
      event.add('dtstamp', datetime.datetime.combine(self.date, datetime.time(6, 0, 0)))
 
      event['uid'] = getUniqueId() # Generate some unique ID
 
      event.add('priority', 5)
 
      event.add('sequence', 1)
 
      event.add('created', datetime.datetime.now())
 
      
 
      alarm = icalendar.Alarm()
 
      alarm.add("action", "DISPLAY")
 
      alarm.add('description', "Reminder")
 
      #alarm.add("trigger", datetime.timedelta(hours=-reminderHours))
 
      # The only way to convince Outlook to do it correctly
 
      alarm.add("TRIGGER;RELATED=START", "-PT{0}H".format(reminderHours))
 
      event.add_component(alarm)
 
      cal.add_component(event)
 
      
 
      msg = MIMEMultipart("alternative")
 
      
 
      msg["Subject"] = subj
 
      msg["From"] = "{0}@example.com".format(self.creator)
 
      msg["To"] = self.getEmail()
 
      msg["Content-class"] = "urn:content-classes:calendarmessage"
 
      
 
      msg.attach(email.MIMEText.MIMEText(description))
 
      
 
      filename = "invite.ics"
 
      part = email.MIMEBase.MIMEBase('text', "calendar", method="REQUEST", name=filename)
 
      part.set_payload( cal.to_ical() )
 
      email.Encoders.encode_base64(part)
 
      part.add_header('Content-Description', filename)
 
      part.add_header("Content-class", "urn:content-classes:calendarmessage")
 
      part.add_header("Filename", filename)
 
      part.add_header("Path", filename)
 
      msg.attach(part)
 
      
 
      s = smtplib.SMTP('localhost')
 
      s.sendmail(msg["From"], [msg["To"]], msg.as_string())
 
      s.quit()
posted @ 2013-04-25 12:15  重庆Debug  阅读(2919)  评论(0编辑  收藏  举报