def attach(self, filename, mime=None, charset=None, content=None): base = os.path.basename(filename) if content is None: fd = open(filename) content = fd.read() fd.close() if not isinstance(content, types.StringType): raise TypeError("don't know how to handle content: %s" % type(content)) part = MIMEBase("application", "octet-stream") part.set_payload(content) Encoders.encode_base64(part) part.add_header("Content-Disposition", "attachment; filename=\"%s\"" % base) if mime is not None: part.set_type(mime) if charset is not None: part.set_charset(charset) if self.msg is None: self.msg = MIMEMultipart() self.msg.attach(self.message) self.msg.attach(part)
def attach(self, filename, mime=None, charset=None, content=None): """Attach files to this message. Example:: msg.attach("me.png", mime="image/png") It also supports fake attachments:: msg.attach("fake.txt", mime="text/plain", content="gotcha") """ base = os.path.basename(filename) if content is None: fd = open(filename) content = fd.read() fd.close() elif not isinstance(content, types.StringType): raise TypeError("Don't know how to attach content: %s" % repr(content)) part = MIMEBase("application", "octet-stream") part.set_payload(content) Encoders.encode_base64(part) part.add_header("Content-Disposition", "attachment", filename=base) if mime is not None: part.set_type(mime) if charset is not None: part.set_charset(charset) if self.msg is None: self.msg = MIMEMultipart() self.msg.attach(self.message) self.msg.attach(part)
def to_message(self): from email.MIMEMultipart import MIMEMultipart from email.MIMEBase import MIMEBase from email.MIMEText import MIMEText from email.Utils import COMMASPACE, formatdate from email import Encoders msg = MIMEMultipart() organizer = self.get_organizer() email = organizer.email() name = organizer.name() if not name: msg['From'] = email else: msg['From'] = '"%s" <%s>' % (name, email) msg['To'] = ', '.join([x.__str__() for x in self.get_attendees()]) msg['Date'] = formatdate(localtime=True) msg.add_header('X-Kolab-Type', 'application/x-vnd.kolab.event') text = utils.multiline_message(""" This is a Kolab Groupware object. To view this object you will need an email client that understands the Kolab Groupware format. For a list of such email clients please visit http://www.kolab.org/ """) msg.attach( MIMEText(text) ) part = MIMEBase('application', "calendar+xml") part.set_charset('UTF-8') msg["Subject"] = self.get_uid() part.set_payload(str(self)) part.add_header('Content-Disposition', 'attachment; filename="kolab.xml"') part.replace_header('Content-Transfer-Encoding', '8bit') msg.attach(part) return msg
def to_message_itip(self, from_address, method="REQUEST", participant_status="ACCEPTED"): from email.MIMEMultipart import MIMEMultipart from email.MIMEBase import MIMEBase from email.MIMEText import MIMEText from email.Utils import COMMASPACE, formatdate from email import Encoders msg = MIMEMultipart() msg_from = None if method == "REPLY": # TODO: Make user friendly name <email> msg['To'] = self.get_organizer().email() attendees = self.get_attendees() # TODO: There's an exception here for delegation (partstat DELEGATED) for attendee in attendees: if attendee.get_email() == from_address: # Only the attendee is supposed to be listed in a reply attendee.set_participant_status(participant_status) self._attendees = [attendee] self.event.setAttendees(self._attendees) name = attendee.get_name() email = attendee.get_email() if not name: msg_from = email else: msg_from = '"%s" <%s>' % (name, email) if msg_from == None: organizer = self.get_organizer() email = organizer.email() name = organizer.name() if email == from_address: if not name: msg_from = email else: msg_from = '"%s" <%s>' % (name, email) elif method == "REQUEST": organizer = self.get_organizer() email = organizer.get_email() name = organizer.get_name() if not name: msg_from = email else: msg_from = '"%s" <%s>' % (name, email) if msg_from == None: if from_address == None: log.error(_("No sender specified")) else: msg_from = from_address msg['From'] = msg_from msg['Date'] = formatdate(localtime=True) # TODO: Should allow for localization text = utils.multiline_message(""" This is a response to one of your event requests. """) msg.attach( MIMEText(text) ) part = MIMEBase('text', "calendar") part.set_charset('UTF-8') # TODO: Should allow for localization msg["Subject"] = "Meeting Request %s" % (participant_status) part.set_payload(self.as_string_itip(method=method)) part.add_header('Content-Disposition', 'attachment; filename="event.ics"') part.replace_header('Content-Transfer-Encoding', '8bit') msg.attach(part) return msg
def main(): email_sender = smtplib.SMTP('localhost') today = datetime.now() tomorrow = datetime.now() + timedelta(days=1) try: results = urllib.urlopen(QUERY).read() except: raise results = json.loads(results) try: data = results['ask']['results']['items'] except KeyError: raise ValueError("Bad API data") for item in data: try: displaytitle = item['properties']['displaytitle'] except: #no title continue try: start_date = datetime.strptime(item['properties']['start_date'], "%Y-%m-%d %H:%M:%S" ) except ValueError: # cannot parse date, move to next time continue try: end_date = datetime.strptime(item['properties']['end_date'], "%Y-%m-%d %H:%M:%S" ) except ValueError: # cannot parse end date, make it equal to start_date + 1 end_date = start_date + timedelta(hour=1) when = None if sameday(today, start_date): when = u"Σήμερα" elif sameday(tomorrow, start_date): when = u"Αύριο" if when: # shorten url # url-quote wiki page title so we # generate correct links uri = item['uri'][43:].encode("utf-8") url = tinyurl.create(item['uri'][:43] + urllib.quote(uri) ).next() url = url.encode("utf-8") title = unescape(item['title']) tweet_message = u"%s στις %02d.%02d: %s %s" %\ (when, start_date.hour, start_date.minute, truncate(title, 140), url ) tweet_message = tweet_message.encode("utf-8") email_message = u"%s στις %02d.%02d: %s" %\ (when, start_date.hour, start_date.minute, title ) email_message = email_message.encode("utf-8") if TWEET: squawk(USERNAME, PASSWORD, tweet_message) if MAIL: msg = MIMEMultipart() msg.set_charset('utf-8') msg['Approved'] = MAIL_KEY msg['From'] = MAIL_FROM msg['To'] = MAIL_TO msg['Subject'] = '[hsgr-ann] %s' % email_message BODY = string.join( (email_message, u"\r\nΠερισσότερα: ".encode("utf-8") + url, "\r\n--\r\nHackerspace Little Event Bot", ), "\r\n" ) t = MIMEText(BODY) t.set_charset('utf-8') msg.attach(t) # attach ICS part = MIMEBase('text', "calendar") part.set_payload(string.join( ( "BEGIN:VCALENDAR", "VERSION:2.0", "PRODID:-//hsgr/handcal//NONSGML v1.0//EN", "BEGIN:VEVENT", "UID:%s@hsgr" % displaytitle.encode('utf-8').replace(' ', '_'), "DTSTAMP;TZID=Europe/Athens:%04d%02d%02dT%02d%02d00" % ( start_date.year, start_date.month, start_date.day, start_date.hour, start_date.minute), "ORGANIZER;CN=Hackerspace:MAILTO:[email protected]", "DTSTART;TZID=Europe/Athens:%04d%02d%02dT%02d%02d00" % ( start_date.year, start_date.month, start_date.day, start_date.hour, start_date.minute), "DTEND;TZID=Europe/Athens:%04d%02d%02dT%02d%02d00" % ( end_date.year, end_date.month, end_date.day, end_date.hour, end_date.minute), "SUMMARY:%s" % email_message, "END:VEVENT", "END:VCALENDAR" ), "\r\n") ) part.add_header('Content-Disposition', 'attachment; filename="event.ics"') part.set_charset('utf-8') msg.attach(part) email_sender.sendmail(MAIL_FROM, MAIL_TO, msg.as_string())
def to_message(self, creator=None): from email.MIMEMultipart import MIMEMultipart from email.MIMEBase import MIMEBase from email.MIMEText import MIMEText from email.Utils import COMMASPACE, formatdate msg = MIMEMultipart() organizer = self.get_organizer() email = organizer.email() name = organizer.name() if creator: msg['From'] = creator elif not name: msg['From'] = email else: msg['From'] = '"%s" <%s>' % (name, email) msg['To'] = ', '.join([x.__str__() for x in self.get_attendees()]) msg['Date'] = formatdate(localtime=True) msg.add_header('X-Kolab-MIME-Version', '3.0') msg.add_header('X-Kolab-Type', 'application/x-vnd.kolab.' + self.type) text = utils.multiline_message(""" This is a Kolab Groupware object. To view this object you will need an email client that understands the Kolab Groupware format. For a list of such email clients please visit http://www.kolab.org/ """) msg.attach( MIMEText(text) ) part = MIMEBase('application', "calendar+xml") part.set_charset('UTF-8') msg["Subject"] = self.get_uid() # extract attachment data into separate MIME parts vattach = self.event.attachments() i = 0 for attach in vattach: if attach.uri(): continue mimetype = attach.mimetype() (primary, seconday) = mimetype.split('/') name = attach.label() if not name: name = 'unknown.x' (basename, suffix) = path.splitext(name) t = datetime.datetime.now() cid = "%s.%s.%s%s" % (basename, time.mktime(t.timetuple()), t.microsecond + len(self._attachment_parts), suffix) p = MIMEBase(primary, seconday) p.add_header('Content-Disposition', 'attachment', filename=name) p.add_header('Content-Transfer-Encoding', 'base64') p.add_header('Content-ID', '<' + cid + '>') p.set_payload(base64.b64encode(attach.data())) self._attachment_parts.append(p) # modify attachment object attach.setData('', mimetype) attach.setUri('cid:' + cid, mimetype) vattach[i] = attach i += 1 self.event.setAttachments(vattach) part.set_payload(str(self)) part.add_header('Content-Disposition', 'attachment; filename="kolab.xml"') part.replace_header('Content-Transfer-Encoding', '8bit') msg.attach(part) # append attachment parts for p in self._attachment_parts: msg.attach(p) return msg