def GenericMail(self, toadd, msgtxt, subj='PySCeS generated email'): """ GenericMail( toadd, msgtxt, subj='PySCeS generated email') Generate and send a text (non-mime) email message Arguments: ========= toadd: recipient address msgtxt: the message body as a string subj [default='PySCeS generated email']: message subject line """ assert type(msgtxt) == str, '\nMessage text must be a string' assert self.__smtp_active, 'SMTP Server not active\n' msgtxt = self.msgintro + msgtxt msgtxt += self.signature outer = MIMEText(msgtxt) outer['Subject'] = subj outer['To'] = toadd outer['From'] = self.fromhead outer['Date'] = email.Utils.formatdate(localtime='true') outer.epilogue = ' ' if self.CheckGo(): try: self.__SMTPserver.sendmail(self.fromhead,toadd,outer.as_string()) except SMTPServerDisconnected, e: print e self.SMTPOpen() self.__SMTPserver.sendmail(self.fromhead,toadd,outer.as_string()) sleep(0.2)
def GenericMail(self, toadd, msgtxt, subj='PySCeS generated email'): """ GenericMail( toadd, msgtxt, subj='PySCeS generated email') Generate and send a text (non-mime) email message Arguments: ========= toadd: recipient address msgtxt: the message body as a string subj [default='PySCeS generated email']: message subject line """ assert type(msgtxt) == str, '\nMessage text must be a string' assert self.__smtp_active, 'SMTP Server not active\n' msgtxt = self.msgintro + msgtxt msgtxt += self.signature outer = MIMEText(msgtxt) outer['Subject'] = subj outer['To'] = toadd outer['From'] = self.fromhead outer['Date'] = email.Utils.formatdate(localtime='true') outer.epilogue = ' ' if self.CheckGo(): try: self.__SMTPserver.sendmail(self.fromhead, toadd, outer.as_string()) except SMTPServerDisconnected, e: print e self.SMTPOpen() self.__SMTPserver.sendmail(self.fromhead, toadd, outer.as_string()) sleep(0.2)
def send(self): """ de: Sendet die Email an den Empfaenger. Wird das Email nur an einen Empfaenger gesendet, dann wird bei Erfolg <True> zurueck gegeben. Wird das Email an mehrere Empfaenger gesendet und wurde an mindestens einen der Empfaenger erfolgreich ausgeliefert, dann wird ebenfalls <True> zurueck gegeben. Wird das Email nur an einen Empfaenger gesendet, dann wird bei Misserfolg <False> zurueck gegeben. Wird das Email an mehrere Empfaenger gesendet und wurde an keinen der Empfaenger erfolgreich ausgeliefert, dann wird <False> zurueck gegeben. """ # # pruefen ob alle notwendigen Informationen angegeben wurden # if len(self.from_address.strip()) == 0: raise NoFromAddress_Exception if self.recipients.count() == 0: if ( (self.cc_recipients.count() == 0) and (self.bcc_recipients.count() == 0) ): raise NoToAddress_Exception if len(self.subject.strip()) == 0: raise NoSubject_Exception # # Email zusammensetzen # if self.attachments.count() == 0: # Nur Text msg = MIMEText( _text = self.message, _subtype = self.content_subtype, _charset = self.content_charset ) else: # Multipart msg = MIMEMultipart() if self.message: att = MIMEText( _text = self.message, _subtype = self.content_subtype, _charset = self.content_charset ) msg.attach(att) # Empfänger, CC, BCC, Absender, User-Agent, Antwort-an # und Betreff hinzufügen from_str = formataddr((self.from_caption, self.from_address)) msg["From"] = from_str if self.reply_to_address: reply_to_str = formataddr((self.reply_to_caption, self.reply_to_address)) msg["Reply-To"] = reply_to_str if self.recipients.count() > 0: msg["To"] = ", ".join(self.recipients.get_list()) if self.cc_recipients.count() > 0: msg["Cc"] = ", ".join(self.cc_recipients.get_list()) msg["Date"] = formatdate(time.time()) msg["User-Agent"] = self.user_agent try: msg["Subject"] = Header( self.subject, self.header_charset ) except(UnicodeDecodeError): msg["Subject"] = Header( self.subject, self.content_charset ) msg.preamble = "You will not see this in a MIME-aware mail reader.\n" msg.epilogue = "" # Falls MULTIPART --> zusammensetzen if self.attachments.count() > 0: for filename in self.attachments.get_list(): # Pruefen ob Datei existiert if not os.path.isfile(filename): raise AttachmentNotFound_Exception, filename # Datentyp herausfinden ctype, encoding = mimetypes.guess_type(filename) if ctype is None or encoding is not None: ctype = 'application/octet-stream' maintype, subtype = ctype.split('/', 1) if maintype == 'text': fp = file(filename) # Note: we should handle calculating the charset att = MIMEText(fp.read(), _subtype=subtype) fp.close() elif maintype == 'image': fp = file(filename, 'rb') att = MIMEImage(fp.read(), _subtype=subtype) fp.close() elif maintype == 'audio': fp = file(filename, 'rb') att = MIMEAudio(fp.read(), _subtype=subtype) fp.close() else: fp = file(filename, 'rb') att = MIMEBase(maintype, subtype) att.set_payload(fp.read()) fp.close() # Encode the payload using Base64 Encoders.encode_base64(att) # Set the filename parameter att.add_header( 'Content-Disposition', 'attachment', filename = os.path.split(filename)[1].strip() ) msg.attach(att) # # Am SMTP-Server anmelden und evt. authentifizieren # smtp = smtplib.SMTP() if self.smtp_server: smtp.connect(self.smtp_server) else: smtp.connect() if self.smtp_user: smtp.login(user = self.smtp_user, password = self.smtp_password) # # Email versenden # self.statusdict = smtp.sendmail( from_str, ( self.recipients.get_list() + self.cc_recipients.get_list() + self.bcc_recipients.get_list() ), msg.as_string() ) smtp.close() # Rueckmeldung return True
def send(self): """ Send the mail. Returns True if successfully sent to at least one recipient. """ # validation if len(self.from_address.strip()) == 0: raise NoFromAddress_Exception if self.recipients.count() == 0: if ( (self.cc_recipients.count() == 0) and (self.bcc_recipients.count() == 0) ): raise NoToAddress_Exception if len(self.subject.strip()) == 0: raise NoSubject_Exception # assemble if self.attachments.count() == 0: msg = MIMEText( _text = self.message, _subtype = self.content_subtype, _charset = self.content_charset ) else: msg = MIMEMultipart() if self.message: att = MIMEText( _text = self.message, _subtype = self.content_subtype, _charset = self.content_charset ) msg.attach(att) # add headers from_str = formataddr((self.from_caption, self.from_address)) msg["From"] = from_str if self.reply_to_address: reply_to_str = formataddr((self.reply_to_caption, self.reply_to_address)) msg["Reply-To"] = reply_to_str if self.recipients.count() > 0: msg["To"] = ", ".join(self.recipients.get_list()) if self.cc_recipients.count() > 0: msg["Cc"] = ", ".join(self.cc_recipients.get_list()) msg["Date"] = formatdate(time.time()) msg["User-Agent"] = self.user_agent try: msg["Subject"] = Header( self.subject, self.header_charset ) except(UnicodeDecodeError): msg["Subject"] = Header( self.subject, self.content_charset ) msg.preamble = "You will not see this in a MIME-aware mail reader.\n" msg.epilogue = "" # assemble multipart if self.attachments.count() > 0: for typ, info in self.attachments.get_list(): if typ == 'file': filename = info if not os.path.isfile(filename): raise AttachmentNotFound_Exception, filename mimetype, encoding = mimetypes.guess_type(filename) if mimetype is None or encoding is not None: mimetype = 'application/octet-stream' if mimetype.startswith('text/'): fp = file(filename) else: fp = file(filename, 'rb') text = fp.read() fp.close() else: filename, text, mimetype = info maintype, subtype = mimetype.split('/', 1) if maintype == 'text': # Note: we should handle calculating the charset att = MIMEText(text, _subtype=subtype) elif maintype == 'image': att = MIMEImage(text, _subtype=subtype) elif maintype == 'audio': att = MIMEAudio(text, _subtype=subtype) else: att = MIMEBase(maintype, subtype) att.set_payload(text) # Encode the payload using Base64 Encoders.encode_base64(att) # Set the filename parameter att.add_header( 'Content-Disposition', 'attachment', filename = os.path.basename(filename).strip() ) msg.attach(att) # connect to server smtp = smtplib.SMTP() if self.smtp_server: smtp.connect(self.smtp_server) else: smtp.connect() # TLS? if self.use_tls: smtp.ehlo() smtp.starttls() smtp.ehlo() # authenticate if self.smtp_user: smtp.login(user = self.smtp_user, password = self.smtp_password) # send self.statusdict = smtp.sendmail( from_str, ( self.recipients.get_list() + self.cc_recipients.get_list() + self.bcc_recipients.get_list() ), msg.as_string() ) smtp.close() return True
def transport(self, data): if type(data) != type(''): # @todo Add warning that stream is being ignored # @todo Assuming that not string means stream. a = array.array('c') stream_data = data.read(1024) while stream_data: a.fromstring(stream_data) stream_data = data.read(1024) data = a.tostring() headers = {} splitdata = data.split('\r\n\r\n') if len(splitdata) > 1: headerdata = splitdata[0] data = string.join(splitdata[1:], '\r\n\r\n') for header in headerdata.split('\r\n'): splitheader = header.split(':') name = splitheader[0].strip() value = string.join(splitheader[1:], ':').strip() headers[name] = value if self.subtype: text_subtype = self.subtype else: text_subtype = 'plain' if text_subtype == 'plain': default_extension = 'txt' else: default_extension = text_subtype if text_subtype != 'xml' and data[:16].strip()[:5] == '<?xml': msglog.log('broadway', msglog.types.WARN, 'Transporter overriding configured subtype to "xml".') text_subtype='xml' default_extension = 'xml' msg = MIMEText(data, _subtype=text_subtype) subject = headers.get('Subject') if subject is None or subject == 'None' or subject == '': subject = self.subject #CSCtg54105 else: if self.subject is not None and self.subject != 'None' and self.subject != '': subject = self.subject + ': ' + subject if subject: msg.add_header('Thread-Topic', subject) msg.add_header('Subject', subject) msg.add_header('From', self.sender) msg.add_header('To', COMMASPACE.join(self._recipients)) date = headers.get('Date', formatdate(time.time(), True)) msg.add_header('Date', date) message_id = make_msgid() if self.as_attachment: # @fixme: Make configurable default_filename = "%s.%s" % ( message_id[1:-1].split("@")[0], default_extension ) msg.add_header('Content-Disposition', 'attachment', filename=default_filename) msg.set_param('name', default_filename) # @fixme: Make configurable msg.add_header('Content-Class', 'urn:content-classes:message') # @fixme: Make configurable msg.add_header('X-Mailer', 'Mediator SMTP Transport') msg.add_header('Message-ID', message_id) # @fixme: Make configurable msg.add_header('Importance', 'normal') # @fixme: Make configurable msg.add_header('Priority', 'normal') msg.preamble = '' # To guarantee the message ends with a newline msg.epilogue = '' smtp = self.SMTP() if self.debug: smtp.set_debuglevel(self.debug) smtp.connect(self.host,self.port,self.timeout) if self.custom_domain: if not (200 <= smtp.ehlo(self.custom_domain)[0] <= 299): (code, resp) = smtp.helo(self.custom_domain) if not (200 <= code <= 299): raise smtp.SMTPHeloError(code, resp) if self.authenticate: try: smtp.login(self.username,self.password) except smtplib.SMTPAuthenticationError: msglog.log('broadway',msglog.types.WARN, 'SMTP Authentication failed.' + ' Invalid username/password.') raise failures = smtp.sendmail(self.sender,self._recipients, msg.as_string()) for recipient in failures.keys(): msglog.log('broadway',msglog.types.WARN, 'Error sending mail to %s -> %s' % (recipient,failures[recipient])) smtp.close()
def transport(self, data): if type(data) != type(''): # @todo Add warning that stream is being ignored # @todo Assuming that not string means stream. a = array.array('c') stream_data = data.read(1024) while stream_data: a.fromstring(stream_data) stream_data = data.read(1024) data = a.tostring() headers = {} splitdata = data.split('\r\n\r\n') if len(splitdata) > 1: headerdata = splitdata[0] data = string.join(splitdata[1:], '\r\n\r\n') for header in headerdata.split('\r\n'): splitheader = header.split(':') name = splitheader[0].strip() value = string.join(splitheader[1:], ':').strip() headers[name] = value if self.subtype: text_subtype = self.subtype else: text_subtype = 'plain' if text_subtype == 'plain': default_extension = 'txt' else: default_extension = text_subtype if text_subtype != 'xml' and data[:16].strip()[:5] == '<?xml': msglog.log('broadway', msglog.types.WARN, 'Transporter overriding configured subtype to "xml".') text_subtype = 'xml' default_extension = 'xml' msg = MIMEText(data, _subtype=text_subtype) subject = headers.get('Subject') if subject is None or subject == 'None' or subject == '': subject = self.subject #CSCtg54105 else: if self.subject is not None and self.subject != 'None' and self.subject != '': subject = self.subject + ': ' + subject if subject: msg.add_header('Thread-Topic', subject) msg.add_header('Subject', subject) msg.add_header('From', self.sender) msg.add_header('To', COMMASPACE.join(self._recipients)) date = headers.get('Date', formatdate(time.time(), True)) msg.add_header('Date', date) message_id = make_msgid() if self.as_attachment: # @fixme: Make configurable default_filename = "%s.%s" % (message_id[1:-1].split("@")[0], default_extension) msg.add_header('Content-Disposition', 'attachment', filename=default_filename) msg.set_param('name', default_filename) # @fixme: Make configurable msg.add_header('Content-Class', 'urn:content-classes:message') # @fixme: Make configurable msg.add_header('X-Mailer', 'Mediator SMTP Transport') msg.add_header('Message-ID', message_id) # @fixme: Make configurable msg.add_header('Importance', 'normal') # @fixme: Make configurable msg.add_header('Priority', 'normal') msg.preamble = '' # To guarantee the message ends with a newline msg.epilogue = '' smtp = self.SMTP() if self.debug: smtp.set_debuglevel(self.debug) smtp.connect(self.host, self.port, self.timeout) if self.custom_domain: if not (200 <= smtp.ehlo(self.custom_domain)[0] <= 299): (code, resp) = smtp.helo(self.custom_domain) if not (200 <= code <= 299): raise smtp.SMTPHeloError(code, resp) if self.authenticate: try: smtp.login(self.username, self.password) except smtplib.SMTPAuthenticationError: msglog.log( 'broadway', msglog.types.WARN, 'SMTP Authentication failed.' + ' Invalid username/password.') raise failures = smtp.sendmail(self.sender, self._recipients, msg.as_string()) for recipient in failures.keys(): msglog.log( 'broadway', msglog.types.WARN, 'Error sending mail to %s -> %s' % (recipient, failures[recipient])) smtp.close()
def send(self): """ Send the mail. Returns True if successfully sent to at least one recipient. """ # validation if len(self.from_address.strip()) == 0: raise NoFromAddress_Exception if self.recipients.count() == 0: if ((self.cc_recipients.count() == 0) and (self.bcc_recipients.count() == 0)): raise NoToAddress_Exception if len(self.subject.strip()) == 0: raise NoSubject_Exception # assemble if self.attachments.count() == 0: msg = MIMEText(_text=self.message, _subtype=self.content_subtype, _charset=self.content_charset) else: msg = MIMEMultipart() if self.message: att = MIMEText(_text=self.message, _subtype=self.content_subtype, _charset=self.content_charset) msg.attach(att) # add headers from_str = formataddr((self.from_caption, self.from_address)) msg["From"] = from_str if self.reply_to_address: reply_to_str = formataddr( (self.reply_to_caption, self.reply_to_address)) msg["Reply-To"] = reply_to_str if self.recipients.count() > 0: msg["To"] = ", ".join(self.recipients.get_list()) if self.cc_recipients.count() > 0: msg["Cc"] = ", ".join(self.cc_recipients.get_list()) msg["Date"] = formatdate(time.time()) msg["User-Agent"] = self.user_agent try: msg["Subject"] = Header(self.subject, self.header_charset) except (UnicodeDecodeError): msg["Subject"] = Header(self.subject, self.content_charset) msg.preamble = "You will not see this in a MIME-aware mail reader.\n" msg.epilogue = "" # assemble multipart if self.attachments.count() > 0: for typ, info in self.attachments.get_list(): if typ == 'file': filename = info if not os.path.isfile(filename): raise AttachmentNotFound_Exception, filename mimetype, encoding = mimetypes.guess_type(filename) if mimetype is None or encoding is not None: mimetype = 'application/octet-stream' if mimetype.startswith('text/'): fp = file(filename) else: fp = file(filename, 'rb') text = fp.read() fp.close() else: filename, text, mimetype = info maintype, subtype = mimetype.split('/', 1) if maintype == 'text': # Note: we should handle calculating the charset att = MIMEText(text, _subtype=subtype) elif maintype == 'image': att = MIMEImage(text, _subtype=subtype) elif maintype == 'audio': att = MIMEAudio(text, _subtype=subtype) else: att = MIMEBase(maintype, subtype) att.set_payload(text) # Encode the payload using Base64 Encoders.encode_base64(att) # Set the filename parameter att.add_header('Content-Disposition', 'attachment', filename=os.path.basename(filename).strip()) msg.attach(att) # connect to server smtp = smtplib.SMTP() if self.smtp_server: smtp.connect(self.smtp_server) else: smtp.connect() # TLS? if self.use_tls: smtp.ehlo() smtp.starttls() smtp.ehlo() # authenticate if self.smtp_user: smtp.login(user=self.smtp_user, password=self.smtp_password) # send self.statusdict = smtp.sendmail( from_str, (self.recipients.get_list() + self.cc_recipients.get_list() + self.bcc_recipients.get_list()), msg.as_string()) smtp.close() return True