def set_payload(self, val, charset=None): self.modified = True try: val.seek(0) val = val.read() except: pass Message.set_payload(self,val,charset) self.submsg = None
def __init__(self,fp=None,seekable=1): Message.__init__(self) self.submsg = None self.modified = False ## @var headerchange # Provide a headerchange event for integration with Milter. # The headerchange attribute can be assigned a function to be called when # changing headers. The signature is: # headerchange(msg,name,value) -> None self.headerchange = None
def executeAction(self, events): """ Sends an email with the given events. """ msg = Message.Message() msg['From'] = self.from_ msg['To'] = self.to msg['Subject'] = self.subject text = self.text + '\n' for event in events: text += str(event) + '\n' msg.set_payload(text) try: server = smtplib.SMTP(self.config.smtpserver) except (socket.gaierror, socket.error) as e: self.logger.logWarn("MailAction plugin: error when connecting to SMTP server (%s): %s"\ % (self.config.smtpserver, str(e))) return try: server.sendmail(self.from_, [self.to], msg.as_string()) except (smtplib.SMTPRecipientsRefused, smtplib.SMTPHeloError, smtplib.SMTPSenderRefused, smtplib.SMTPDataError) as e: self.logger.logWarn("MailAction plugin: error when sending mail (From: %s, To: %s): %s"\ % (self.from_, self.to, str(e))) server.quit()
def build_email_msg(email_): email_message = Message.Message() email_message.add_header('To', email_.to_) email_message.add_header('From', email_.from_) email_message.add_header('Subject', email_.subject) email_message.set_payload(email_.body) return email_message.as_string()
def report_traceback( self ): """ If a support email address is configured, send it an email with the current traceback. """ support_email = self.__settings[u"luminotes.support_email"] if not support_email: return False import smtplib import traceback from email import Message message = Message.Message() message[ u"From" ] = support_email message[ u"To" ] = support_email message[ u"Subject" ] = u"Luminotes traceback" message.set_payload( u"requested URL: %s\n" % cherrypy.request.browser_url + u"user id: %s\n" % cherrypy.session.get( "user_id" ) + u"username: %s\n\n" % cherrypy.session.get( "username" ) + traceback.format_exc() ) # send the message out through localhost's smtp server server = smtplib.SMTP() server.connect() server.sendmail( message[ u"From" ], [ support_email ], message.as_string() ) server.quit() return True
def test_send_message(self): message = Message.Message() message["To"] = "you" message["Cc"] = "them" message["From"] = "me" message["Subject"] = "hello" message.set_payload("Hello everybody!") smtp_info = { 'server': 'stmp.foo.com', 'port': 25, 'user': '******', 'password': '******' } mail.send(from_address="me", to_addresses="you", cc_addresses="them", subject="hello", body="Hello everybody!", smtp_info=smtp_info) self.assertEquals("me", test_data.mail_from_address) self.assertEquals(["you", "them"], test_data.mail_to_address) self.assertEquals(message.as_string(), test_data.mail_message)
def form_to_mime(form, extra_tokens, attachments): """Encode submission form bits as a MIME message. form - a dictionary of key/value pairs representing the form's contents extra_tokens - a sequence of synthetic tokens generated by the caller. For example, if you include a honeypot hidden field in your form, you might generate a synthetic token which tells if it was filled in or not. You might also generate tokens which indicate how long a submitting username has existed or how many successful posts that username has submitted. attachments - list of dictionaries describing an attachment. The 'payload' key is required. If there is no 'content-type' key 'application/octet-stream' is assumed. If 'content-transfer-encoding' is given it will be added to the headers of the attachment. Note that the keys are case-sensitive and must be lower case. """ msg = Message.Message() msg.set_type("multipart/digest") msg.add_header("Subject", "Form submission") msg.add_header("From", "SpamBayes XMLRPC Plugin <webmaster@localhost>") main = Message.Message() main.set_type("text/plain") main.set_payload("\n".join(["%s:%s" % (k, v) for (k, v) in form.items()])) msg.attach(main) # Always add the extra tokens payload so we can reliably reverse the # conversion. extra = Message.Message() extra.set_type("text/plain") extra.set_payload("\n".join(extra_tokens)) msg.attach(extra) # Any further payloads are for the attachments. for content in attachments: mime_type = content.get("content-type") or "application/octet-stream" attachment = Message.Message() if "content-transfer-encoding" in content: attachment.add_header("Content-Transfer-Encoding", content["content-transfer-encoding"]) attachment.set_type(mime_type) attachment.set_payload(content["payload"]) msg.attach(attachment) return msg
def __init__(self, recip, sender, subject=None, text=None, lang=None): Message.__init__(self) charset = None if lang is not None: charset = Charset(Utils.GetCharSet(lang)) if text is not None: self.set_payload(text, charset) if subject is None: subject = '(no subject)' self['Subject'] = Header(subject, charset, header_name='Subject', errors='replace') self['From'] = sender if isinstance(recip, ListType): self['To'] = COMMASPACE.join(recip) self.recips = recip else: self['To'] = recip self.recips = [recip]
def _make_message(self, line): data = gocept.imapapi.parser.fetch(line) # XXX debug #6830 import pprint __traceback_info__ = pprint.pformat(data) return Message(self._key(data['UID']), self.container, data['ENVELOPE'], data['FLAGS'])
def sendLog(fileName, summaryName=""): msg = Message.Message() msg["To"] = SMTP_DEST msg["From"] = SMTP_USER msg["Subject"] = 'RDKitBuild: Nightly Build Results for %s' % time.strftime( "%d/%m/%Y") msg["Date"] = Utils.formatdate(localtime=1) msg["Message-ID"] = Utils.make_msgid() msg["Mime-version"] = "1.0" msg["Content-type"] = "Multipart/mixed" msg.preamble = "Mime message\n" msg.epilogue = "" subMsg = Message.Message() subMsg["Content-type"] = "text/plain" subMsg["Content-transfer-encoding"] = "7bit" summaryText = "Automatically generated email" if summaryName: try: summaryData = open(summaryName, 'r').read() except IOError: summaryText += "\n Could not open summary file" else: summaryText += "\n\n TEST SUMMARY\n" + summaryData subMsg.set_payload(summaryText) msg.attach(subMsg) subMsg = Message.Message() subMsg.add_header("Content-type", "application/x-gzip", name=os.path.basename(fileName)) subMsg.add_header("Content-transfer-encoding", "base64") body = cStringIO.StringIO() base64.encode(open(fileName, 'rb'), body) subMsg.set_payload(body.getvalue()) msg.attach(subMsg) smtp = smtplib.SMTP(SMTP_HOSTNAME) smtp.sendmail(msg['From'], [msg['To']], msg.as_string()) smtp.quit()
def test_send_message(self): message = Message.Message() message["To"] = "you" message["Cc"] = "them" message["From"] = "me" message["Subject"] = "hello" message.set_payload("Hello everybody!") mail.send("me", "you", "them", "hello", "Hello everybody!") self.assertEquals("me", test_data.mail_from_address) self.assertEquals(["you", "them"], test_data.mail_to_address) self.assertEquals(message.as_string(), test_data.mail_message)
def sendMessage(config): # Make a message msg = Message.Message() msgid = Utils.make_msgid() # remember the msgid so we can find it later config.msgid = msgid msg['To'] = config.toAddress msg['From'] = config.fromAddress msg['Message-ID'] = msgid msg['X-Zenoss-Time-Sent'] = str(config.sent) msg['Subject'] = 'Zenoss Round-Trip Mail Message' msg.set_payload(config.messageBody) log.debug("Message id %s's length is %s bytes" % (msgid, len(msg.as_string()))) msgIO = StringIO(msg.as_string()) result = defer.Deferred() # figure out how we should connect connect = reactor.connectTCP port = 25 kwargs = {} args = () if ssl and config.smtpAuth == 'SSL': port = 465 connect = reactor.connectSSL kwargs.update(dict(requireTransportSecurity=False)) args = (ssl.ClientContextFactory(), ) elif ssl and config.smtpAuth == 'TLS': pass else: kwargs.update(dict(requireTransportSecurity=False)) if config.smtpUsername: log.debug("ESMTP login as %s/%s" % (config.smtpUsername, "*" * len(config.smtpPassword))) factory = ESMTPSenderFactory(config.smtpUsername, config.smtpPassword, config.fromAddress, (config.toAddress, ), msgIO, result, **kwargs) else: factory = SMTPSenderFactory(config.fromAddress, (config.toAddress, ), msgIO, result) def clientConnectionFailed(self, why): result.errback(why) factory.clientConnectionFailed = clientConnectionFailed # initiate the message send log.debug("Sending message to %s:%s with args: %s" % (config.smtpHost, config.smtpPort or port, args)) connect(config.smtpHost, config.smtpPort or port, factory, *args) return result
def kindToMessageObject(mailMessage): """ This method converts a email message string to a Chandler C{Mail.MailMessage} object @param messageObject: A C{email.Message} object representation of a mail message @type messageObject: C{email.Message} @return: C{Message.Message} """ assert isinstance(mailMessage, Mail.MailMessageMixin), \ "mailMessage must be an instance of Kind Mail.MailMessage" messageObject = Message.Message() """Create a messageId if none exists""" if not utils.hasValue(mailMessage.messageId): mailMessage.messageId = utils.createMessageID() """Create a dateSent if none exists""" if not utils.hasValue(mailMessage.dateSentString): mailMessage.dateSent = datetime.now() mailMessage.dateSentString = utils.dateTimeToRFC2882Date(mailMessage.dateSent) populateHeader(messageObject, 'Message-ID', mailMessage.messageId) populateHeader(messageObject, 'Date', mailMessage.dateSentString) populateEmailAddresses(mailMessage, messageObject) populateStaticHeaders(messageObject) populateChandlerHeaders(mailMessage, messageObject) populateHeaders(mailMessage, messageObject) populateHeader(messageObject, 'Subject', mailMessage.subject) try: payload = mailMessage.body #XXX: Temp hack this should be fixed in GUI level # investigate with Andi and Bryan if payload.encoding is None: payload.encoding = constants.DEFAULT_CHARSET payloadUStr = utils.textToUnicode(payload) except AttributeError: payloadUStr = u"" messageObject.set_payload(payloadUStr) return messageObject
def _sendMail(self, result): body = "\r\n".join(self._body) m = Message.Message() m.set_payload(body) m['Subject'] = self._subject m['From'] = self._from m['To'] = self._to s = m.as_string() if self._debug: self.printMsg("Message:\n %s" % s) return sendmail(self._host, self._from, self._to, s).addCallback( self._messageSent).addErrback(self._sendError)
def fetch(cache_dir, url): logger.info("fetching url %s from cache %s", url, cache_dir) try: digest = hashlib.sha256(url.encode('utf-8')).digest() filepath = os.path.join( cache_dir, "f" + base64.urlsafe_b64encode(digest).decode('utf-8')) except: digest = hashlib.sha256(url).digest() filepath = os.path.join(cache_dir, "f" + base64.urlsafe_b64encode(digest)) fp = Path(filepath) if not fp.is_file(): raise Exception("No such file: " + fp) try: with open(filepath, 'r', encoding='utf-8-sig', newline='') as f: file_content = f.read() if '\r\n\r\n\r\n' in file_content: splitter = '\r\n\r\n\r\n' else: splitter = '\n\n\n' cached = file_content.split(splitter, 1) if len(cached) == 2: headers, content = cached try: content = content.encode('utf-8') except: # already encoded as bytes pass headers = Message(headers) if not content: raise Exception("empty content") return FetchResult(headers, content, url, filepath) else: raise Exception("splitting headers and content failed") except IOError: raise Exception("fetch() failed")
def send(self, message, page=None, name=None, email=None, honeypot=None): # Detect if a spambot has just filled all form fields. if honeypot is not None: self.redirect(self.url('feedback-accepted-honeypot')) return page = page or u"" name = name or u"UNKNOWN" email = email or u"EMPTY-EMAIL" message_body = self.mail_template % dict( message=message, page=page, name=name, email=email, root=self.application_url(), ) message = email_message.Message() message.set_payload(message_body.encode('utf-8')) subject_header = email_header.Header( (u'Assembly Archive feedback about "%s"' % page).encode('utf-8'), 'utf-8') message['Subject'] = subject_header message['To'] = self.target_address from_header = email_header.Header( (u'%s <%s>' % (name, email)).encode('utf-8'), 'utf-8') message['From'] = from_header email_encoders.encode_quopri(message) message.set_charset('utf-8') message_str = message.as_string() smtp = smtplib.SMTP(self.smtp_host) smtp.sendmail(self.target_address, [self.target_address], message_str) self.flash(u'Your feedback was accepted.') self.redirect(self.url('feedback-accepted'))
def previewQuickParse(msg, isObject=False): # Returns a tuple: # 0: headers dict decoded and converted to unicode # 1: body of the message ready for assigning to the # ContentItem.body attribute or None # 2: eim attachment decode and strip of carriage returns # or None # 3: ics attachment decode and strip of carriage returns # or None headers = body = eimml = ics = None if not isObject: msgObj = email.message_from_string(msg) else: msgObj = msg headers = Message.Message() for key, val in msgObj.items(): headers[getUnicodeValue(key)] = decodeHeader(val) att = getChandlerAttachments(msgObj) if att["eimml"]: eimml = att['eimml'][0] else: bodyBuffer = {'plain': [], 'html': []} __parsePart(None, msgObj, None, bodyBuffer, None, None) body = buildBody(bodyBuffer) if att['ics']: ics = att['ics'][0] return (headers, body, eimml, ics)
def get_payload(self,i=None,decode=False): msg = self.submsg if isinstance(msg,Message) and msg.ismodified(): self.set_payload([msg]) return Message.get_payload(self,i,decode)
def kindToMessageObject(mailStamp): """ This method converts an item stamped as MailStamp to an email message string a Chandler C{MailMessage} object @param mailMessage: A Chandler C{MailMessage} @type mailMessage: C{MailMessage} @return: C{Message.Message} """ view = mailStamp.itsItem.itsView mailStampOccurrence, mailStampMaster = getRecurrenceMailStamps(mailStamp) isEvent = has_stamp(mailStampOccurrence, EventStamp) isTask = has_stamp(mailStampOccurrence, TaskStamp) messageObject = Message.Message() # Create a messageId if none exists mId = getattr(mailStampMaster, "messageId", None) if not mId: mId = createMessageID() populateHeader(messageObject, 'Message-ID', mId) populateEmailAddresses(mailStampMaster, messageObject) populateStaticHeaders(messageObject) if hasattr(mailStampMaster, "dateSentString"): date = mailStampMaster.dateSentString else: date = datetimeToRFC2822Date(datetime.now(view.tzinfo.default)) messageObject["Date"] = date inReplyTo = getattr(mailStampMaster, "inReplyTo", None) subject = mailStampOccurrence.subject if subject is not None: # Fixes bug 10254 where the title of a Item # that contained a new line was breaking the # the rfc2822 formatting of the outgoing message. subject = subject.replace("\n", "") if inReplyTo: messageObject["In-Reply-To"] = inReplyTo if mailStampMaster.referencesMID: messageObject["References"] = " ".join(mailStampMaster.referencesMID) populateHeader(messageObject, 'Subject', subject, encode=True) try: payload = getMessageBody(mailStampOccurrence) except AttributeError: payload = u"" if not payload: # bug 12262, Outlook doesn't like multipart/alternative if there's # no payload, so add a few carriage returns to empty bodies payload += "\r\n\r\n" if isTask or isEvent and payload and \ not payload.endswith(u"\r\n\r\n"): # Chandler outgoing Tasks and Events contain # an ics attachment. # Many mail readers add attachment icons # at the end of the message body. # This can be distracting and visually # ugly. Appending two line breaks to the # payload provides better alignment in # mail readers such as Apple Mail and # Thunderbird. payload += u"\r\n\r\n" messageObject.set_type("multipart/mixed") # Create a multipart/alernative MIME Part # that will contain the Chandler eimml and # the body of the message as alternative # parts. Doing this prevents users from seeing # the Chandler eimml which is machine readable # xml code and is not displayable to the user. alternative = MIMEMultipart("alternative") # Serialize and attach the eimml can raise ConflictsPending eimml = outbound(getPeers(mailStampMaster), mailStampMaster.itsItem, OUTBOUND_FILTERS) eimmlPayload = MIMEBase64Encode(eimml, 'text', 'eimml') # Since alternative parts are in order from least # renderable to most renderable add the eimml payload # first. alternative.attach(eimmlPayload) # Attach the body text mt = MIMEBase64Encode(payload.encode('utf-8')) # Add the email body text to the alternative part alternative.attach(mt) # Add the alternative part to the mail multipart/mixed # main content type. messageObject.attach(alternative) #XXX There is no attachement support in 1.0 #hasAttachments = mailStamp.getNumberOfAttachments() > 0 if isEvent or isTask: # Format this message as an ICalendar object from osaf.sharing import (serialize, VObjectSerializer, SharingTranslator, remindersFilter) items = [mailStampMaster.itsItem] for mod in EventStamp(mailStampMaster).modifications or []: if not checkTriageOnly(mod): items.append(mod) calendar = serialize(mailStamp.itsItem.itsView, items, SharingTranslator, VObjectSerializer, filter=remindersFilter) # don't use method REQUEST because it will cause Apple iCal to treat # the ics attachment as iMIP calendar.add('method').value = "PUBLISH" ics = calendar.serialize() # returns a UTF-8 encoded str # Attach the ICalendar object icsPayload = MIMEBase64Encode(ics, 'text', 'calendar', method='PUBLISH') # L10N: The filename of Events and Tasks emailed from Chandler fname = Header.Header(_(u"ChandlerItem.ics")).encode() icsPayload.add_header("Content-Disposition", "attachment", filename=fname) messageObject.attach(icsPayload) #XXX: There is no attachment support in 1.0 via # the MailStamp.mimeContent. Commenting out this code # for now. # #if hasAttachments: # attachments = mailStamp.getAttachments() # # for attachment in attachments: # if has_stamp(attachment, MailStamp): # # The attachment is another MailMessage # try: # rfc2822 = binaryToData(MailStamp(attachment).rfc2822Message) # except AttributeError: # rfc2822 = kindToMessageText(attachment, False) # # message = email.message_from_string(rfc2822) # rfc2822Payload = MIMEMessage(message) # messageObject.attach(rfc2822Payload) # # else: # if isinstance(attachment, MIMEText) and \ # attachment.mimeType == u"text/calendar": # icsPayload = MIMENonMultipart('text', 'calendar', \ # method='REQUEST', _charset="utf-8") # # fname = Header.Header(attachment.filename).encode() # icsPayload.add_header("Content-Disposition", "attachment", filename=fname) # icsPayload.set_payload(attachment.data.encode('utf-8')) # messageObject.attach(icsPayload) return messageObject
def __init__(self): Message.__init__(self)
def mkmsg(self,type,_payload='',**kwargs): msg = Message() msg.add_header('_type',type) if _payload is not None: _payload=str(_payload) msg.set_payload(_payload) msg.add_header('_size',str(len(_payload))) else: msg.add_header('_size',str(0)) for (var,val) in kwargs.items(): if var.startswith("_"): raise Error822("parameter names can't start with '_'") msg.setheader(var,val) if self.authkey: msg.hmacset(self.authkey) return msg
def mkmsg(self, type, _payload='', **kwargs): msg = Message() msg.add_header('_type', type) if _payload is not None: _payload = str(_payload) msg.set_payload(_payload) msg.add_header('_size', str(len(_payload))) else: msg.add_header('_size', str(0)) for (var, val) in kwargs.items(): if var.startswith("_"): raise Error822("parameter names can't start with '_'") msg.setheader(var, val) if self.authkey: msg.hmacset(self.authkey) return msg
def get_param(self, param, failobj=None, header='content-type', unquote=True): val = Message.get_param(self,param,failobj,header,unquote) if val != failobj and param == 'boundary' and unquote: # unquote boundaries an extra time, test case testDefang5 return _unquotevalue(val) return val
def __setitem__(self, name, value): rc = Message.__setitem__(self,name,value) self.modified = True if self.headerchange: self.headerchange(self,name,str(value)) return rc
def __delitem__(self, name): if self.headerchange: self.headerchange(self,name,None) rc = Message.__delitem__(self,name) self.modified = True return rc