def xmlrpc_resetpassword_confirm(self, token, mac): def badconfirmlinkmsg(): return self.Fault('Your confirm link was invalid; contact acctserv@hcs '\ 'further assistance.') token = (token or '').strip() mac = (mac or '').strip() cryptor = AES.new(self.secret_cipher, AES.MODE_ECB) try: plaintext = cryptor.decrypt(base64.urlsafe_b64decode(token)) mac = base64.urlsafe_b64decode(mac) except ValueError: # if the code is a not a multiple of 16 bytes long raise badconfirmlinkmsg() except TypeError: # invalid padding raise badconfirmlinkmsg() if self.computeMAC(plaintext) != mac: raise badconfirmlinkmsg() # A proper listvars is of the form # [ listname, padding ] listvars = plaintext.split("\x00") if len(listvars) == 2: listname = listvars[0] # reset password; else return error p = subprocess.Popen(('/usr/lib/mailman/bin/change_pw', '-l', listname), stdout=subprocess.PIPE, stderr=subprocess.PIPE) retcode = p.wait() admins = ', '.join(self.get_admins(listname)) if retcode is 0: # return success message output = p.stdout.read() mail('*****@*****.**', self.log_password_success_message % { 'date' : Utils.formatdate(localtime = True), 'messageid' : Utils.make_msgid(), 'listname': listname, 'listadmin': admins}) return listname else: # non-standard problem -- e-mail systems/acctserv output = p.stdout.read() outerr = p.stderr.read() mail('*****@*****.**', self.unknown_mailman_password_error % { 'date' : Utils.formatdate(localtime = True), 'messageid' : Utils.make_msgid(), 'listname' : listname, 'listadmin' : admins, 'output' : output, 'outerr' : outerr }) # return unknown error raise self.Fault('Internal error. The systems team has been notified '\ 'and will be getting back to you.') else: # User submitted bad hash raise badconfirmlinkmsg()
def send_email(config, to_addr, message): msg = MIMEMultipart() msg["Subject"] = config.subject msg["From"] = config.from_addr msg["To"] = to_addr msg["Date"] = Utils.formatdate(localtime = 1) msg["Message-ID"] = Utils.make_msgid() body = MIMEText(message, "html", _charset="utf-8") msg.attach(body) smtp = smtplib.SMTP() #smtp.set_debuglevel(1) smtp.connect(config.smtp_server) ehlo_host = config.from_addr.split("@")[1] smtp.ehlo(ehlo_host) if config.starttls: try: smtp.starttls() smtp.ehlo() except: pass if config.require_auth: try: smtp.login(config.smtp_username, config.smtp_password) except: pass smtp.sendmail(msg["From"], msg["To"], msg.as_string()) smtp.quit() return
def mail_headers(self, group, params): from email import Utils subject = self._rfc2047_encode(self.make_subject(group, params)) from_hdr = self._rfc2047_encode(self.from_addr) to_hdr = self._rfc2047_encode(', '.join(self.to_addrs)) hdrs = 'From: %s\n' \ 'To: %s\n' \ 'Subject: %s\n' \ 'Date: %s\n' \ 'Message-ID: %s\n' \ 'MIME-Version: 1.0\n' \ 'Content-Type: text/plain; charset=UTF-8\n' \ 'Content-Transfer-Encoding: 8bit\n' \ 'X-Svn-Commit-Project: %s\n' \ 'X-Svn-Commit-Author: %s\n' \ 'X-Svn-Commit-Revision: %d\n' \ 'X-Svn-Commit-Repository: %s\n' \ % (from_hdr, to_hdr, subject, Utils.formatdate(), Utils.make_msgid(), group, self.repos.author or 'no_author', self.repos.rev, os.path.basename(self.repos.repos_dir)) if self.reply_to: hdrs = '%sReply-To: %s\n' % (hdrs, self.reply_to) return hdrs + '\n'
def send_mail(send_to, subject, content): mail_user = "******" #mail_password = "******" mail_password = "******" # mail_host = "smtp.exmail.qq.com" # mail_host = "smtp.ym.163.com" mail_host = "smtp.mxhichina.com" state = '' msg = '' subject = subject.decode('utf-8') content = content.decode('utf-8') message = MIMEText(content, _subtype='plain', _charset='utf-8') message['Subject'] = subject message['From'] = u'系统监控<' + mail_user + ">" message['To'] = send_to message['Date'] = Utils.formatdate(localtime=1) message['Message-ID'] = Utils.make_msgid() message = message.as_string() try: # s = smtplib.SMTP_SSL(mail_host, 465) # s = smtplib.SMTP_SSL(mail_host, 994) s = smtplib.SMTP_SSL(mail_host, 465) s.login(mail_user, mail_password) is_out_one_minute(mail_log_path, max_mail_count, send_to + " " + subject) s.sendmail(mail_user, send_to, message) s.close() state = True msg = "MAIL TO %s,subject is %s" % (send_to, subject) except Exception, e: state = False msg = "MAIL TO %s,error is %s" % (send_to, str(e))
def __make_header(self): # Header # self.message['Message-Id'] = Header(self.__make_msgid(), self.character) self.message['Message-Id'] = Header(Utils.make_msgid(), self.character) if self.reply_to: self.message['Reply-to'] = Header(self.reply_to, self.character) self.message['Subject'] = Header(self.subject, self.character) self.message['From'] = Header(self.mail_from, self.character) self.message['To'] = Header(self.mail_to, self.character) self.message["Date"] = Utils.formatdate(localtime=True) # self.message['List-Unsubscribe'] = "<mailto:[email protected]?subject=unsubscribe>, <https://www.bestedm.org/>" # self.message['List-Unsubscribe'] = "<mailto:[email protected]>, <https://www.bestedm.org/>" # self.message['List-Unsubscribe'] = "<mailto:[email protected]>" # self.message['List-Unsubscribe'] = "<mailto:[email protected]>, <https://www.bestedm.org/>" # self.message['List-Unsubscribe'] = "https://www.bestedm.org/, mailto:[email protected]" self.message['List-Unsubscribe'] = "<http://www.bestedm.org/login?next=/>, <mailto:[email protected]?subject=unsubscribe>" # self.message['List-Unsubscribe'] = Header("<http://www.bestedm.org/login?next=/>, <mailto:[email protected]?subject=unsubscribe>", None) # "List-Unsubscribe": "<mailto:[email protected]>, <http://www.unsubscribe.example.com/>" # self.message['List-ID'] = "8234ed62d6a7fa87721ff1d8amc list <8234ed62d6a7fa87721ff1d8a.24393.list-id.mcsv.net>" # self.message['List-Unsubscribe-Post'] = "List-Unsubscribe=One-Click" #Header("<https://www.bestedm.org>, <mailto:{}>".format(self.mail_from), self.character) # self.message['List-Help'] = Header("http://email.gaodun.com/x/plugin/?pName=list_help&MIDRID=S7Y1_p9ra2pubvy.yNbQ2Njc2OJ.jq2pmakxAAA78&Z=1224136778", self.character) # self.message['List-Owner'] = Header(self.mail_to, self.character) if self.is_need_receipt: self.message['Disposition-Notification-To'] = Header(self.mail_from, self.character) if self.edm_check_result: self.message['Edm-Check-Result'] = Header(self.edm_check_result, self.character)
def getmsg(self, filename): ''' 构建邮件数据对象 ''' msg = MIMEMultipart('tiancheng testing report email') msg['From'] = self.from_addr msg['To'] = 'Recver <' + self.from_addr + '>' msg['Subject'] = u'来自天秤持续集成测试报告' msg['Date'] = Utils.formatdate(localtime = 1) msg['Message-ID'] = Utils.make_msgid() #邮件内容 messagetext = u'''Dear All, Annex Libra continuous integration test report, please use the browser to open to view, thank you! ''' parttext = MIMEText(messagetext) msg.attach(parttext) #文件附件 filepart = MIMEApplication(open(filename,'rb').read()) filepart.add_header('Content-Disposition', 'attachment', filename=filename.split("/")[-1]) msg.attach(filepart) self.msg = msg return True
def send_html_email(Subject, content, receiver): if settings.EMAIL_SWITCH: html = open( settings.TEMPLATES[0]['DIRS'][0] + '\\basedatas\\email.html', 'r') data = html.read() html.close() data = data.replace('CONTENT', content) sender = '*****@*****.**' themsg = MIMEMultipart() themsg['Subject'] = Subject themsg['To'] = receiver themsg['From'] = 'map2family' themsg['Date'] = Utils.formatdate(localtime=1) themsg['Message-ID'] = Utils.make_msgid() msgAlternative = MIMEMultipart('alternative') themsg.attach(msgAlternative) content = content + '<br/>www.map2family.com' msgText = MIMEText(content, 'html', 'utf-8') msgAlternative.attach(msgText) themsgtest = themsg.as_string() # send the message server = smtplib.SMTP() server.connect(settings.SMTP_SERVER) server.login(settings.SMTP_SERVER_USER, settings.SMTP_SERVER_PWD) server.sendmail(sender, receiver, themsgtest) server.quit() #SMTP.quit()
def send_mail(sender, receiver, subject, content, ctype="html", pics=(), smtpserver='mail.51ping.com', username="******", password="******"): """subject and body are unicode objects""" if ctype == "html": msg = MIMEText(content, 'html', 'utf-8') else: msg = MIMEText(content, 'plain', 'utf-8') if len(pics) != 0: msgRoot = MIMEMultipart('related') msgText = MIMEText(content, 'html', 'utf-8') msgRoot.attach(msgText) i = 1 for pic in pics: fp = open(pic, "rb") image = MIMEImage(fp.read()) fp.close() image.add_header('Content-ID', '<img%02d>' % i) msgRoot.attach(image) i += 1 msg = msgRoot msg['Subject'] = Header(subject, 'utf-8') msg['From'] = sender msg['To'] = ';'.join(receiver) msg['Message-ID'] = Utils.make_msgid() msg['date'] = time.strftime('%a, %d %b %Y %H:%M:%S %z') smtp = smtplib.SMTP() smtp.connect(smtpserver, 25) smtp.login(username, password) smtp.sendmail(sender, receiver, msg.as_string()) smtp.quit()
def getmsg(self, filename): ''' 构建邮件数据对象 ''' msg = MIMEMultipart('tiancheng testing report email') msg['From'] = self.from_addr msg['To'] = 'Recver <' + self.from_addr + '>' msg['Subject'] = u'来自天秤持续集成测试报告' msg['Date'] = Utils.formatdate(localtime=1) msg['Message-ID'] = Utils.make_msgid() #邮件内容 messagetext = u'''Dear All, Annex Libra continuous integration test report, please use the browser to open to view, thank you! ''' parttext = MIMEText(messagetext) msg.attach(parttext) #文件附件 filepart = MIMEApplication(open(filename, 'rb').read()) filepart.add_header('Content-Disposition', 'attachment', filename=filename.split("/")[-1]) msg.attach(filepart) self.msg = msg return True
def generate(alternative=False, subject=None, plain=None, html=None, sender_address=None, sender_name=None): alternative = alternative or not html is None if alternative: message = MIMEMultipart('alternative') message.attach(MIMEText('', 'plain')) message.attach(MIMEText('', 'html')) else: message = MIMEText('', 'plain') message['Date'] = Utils.formatdate(localtime=1) message['Message-ID'] = Utils.make_msgid() facade = EmailFacade(message=message) if subject: facade.subject = subject if plain: facade.text = plain if html: facade.html = html if sender_address: facade.from_address.address = sender_address if sender_name: facade.from_address.name = sender_name return facade
def generate_head(self): for k in self.headdict.keys(): v = self.headdict[k] newk = '-'.join(map(string.capitalize, k.lower().split('-'))) if newk == 'Subject': self.msg[newk] = email.Header.Header(v, "UTF-8") elif newk == 'From': if type(v) == types.ListType: self.msg[newk] = '"%s" <%s>' % (email.Header.Header(v[0], 'utf-8'), v[1]) else: self.msg[newk] = v elif newk == 'To': s = [] for x in v: if type(x) == types.ListType: s.append('"%s" <%s>' % (email.Header.Header(x[0], 'utf-8'), x[1])) else: s.append(x) self.msg[newk] = '\r\n\t'.join(s) else: self.msg[newk] = v self.msg['Date'] = Utils.formatdate(localtime = 1) self.msg['Message-Id'] = Utils.make_msgid()
def compose(self, to_addrs=[], from_addr='', subject='', message='', cc_addrs=[], bcc_addrs=[], content_type='text/plain', attachments=[]): self.subject = subject self.to_addrs = to_addrs self.from_addr = from_addr if not attachments and content_type == 'text/plain': msg = MIMEText(message) else: msg = MIMEMultipart() # should be refactored msg['To'] = ','.join(to_addrs) msg['From'] = from_addr if cc_addrs: msg['Cc'] = ','.join(cc_addrs) msg['Subject'] = subject msg['Date'] = Utils.formatdate(localtime=1) msg['Message-ID'] = Utils.make_msgid() if content_type != 'text/plain': body = MIMEMultipart('alternative') body.attach(genpart(message, content_type)) msg.attach(body) for a in attachments: msg.attach(attachment(a)) self.msg = msg.as_string()
def sendmail(to,subject,content): msg = MIMEText(content) lable_pwd="cmstop666" msg['from'] = '*****@*****.**' msg['to'] = to msg['subject'] = subject msg['date'] = Utils.formatdate(localtime=1) msg['message-id'] = Utils.make_msgid() try: smtpObj = smtplib.SMTP() smtpObj.connect("smtp.sina.com:25") try: smtpObj.login("smtp.163.com",lable_pwd) me = "*****@*****.**" smtpObj.sendmail(me,to,msg.as_string()) print ("Congratulations !Your mail have been sended Success !") except smtplib.SMTPAuthenticationError.smtplib.SMTPException: print ("Login failed ,Please check the username/password.") finally: try: smtpObj.close() except smtplib.SMTPException: pass except smtplib.SMTPException.e: print ("Error: unable to send email %s" % e)
def create_data(self): self.msg = MIMEText('this is a test email,please ingored it.') self.msg['Subject'] = 'python smtplib' self.msg['To'] = ','.join(self.toaddr) self.msg['From'] = self.fromaddr self.msg['Reply_To'] = self.fromaddr self.msg['Message_ID'] = Utils.make_msgid().replace("@", "__Rex@")
def creerMail(mail, informations): # fonction permettant de créer le mail # on défini les headers de notre mail print "Création du mail" mail['From'] = informations['fromaddr'] mail['To'] = informations['toaddr'] mail['Subject'] = informations['sujet'] mail['Date'] = informations['date'] mail['Message-ID'] = Utils.make_msgid()
def notify(self, message = '', data = None, listener = None): if not data: data = {} # Extract all the settings from settings from_address = self.conf('from') to_address = self.conf('to') ssl = self.conf('ssl') smtp_server = self.conf('smtp_server') smtp_user = self.conf('smtp_user') smtp_pass = self.conf('smtp_pass') smtp_port = self.conf('smtp_port') starttls = self.conf('starttls') # Make the basic message message = MIMEText(toUnicode(message), _charset = Env.get('encoding')) message['Subject'] = self.default_title message['From'] = from_address message['To'] = to_address message['Date'] = Utils.formatdate(localtime = 1) message['Message-ID'] = Utils.make_msgid() try: # Open the SMTP connection, via SSL if requested log.debug("Connecting to host %s on port %s" % (smtp_server, smtp_port)) log.debug("SMTP over SSL %s", ("enabled" if ssl == 1 else "disabled")) mailserver = smtplib.SMTP_SSL(smtp_server) if ssl == 1 else smtplib.SMTP(smtp_server) if (starttls): log.debug("Using StartTLS to initiate the connection with the SMTP server") mailserver.starttls() # Say hello to the server mailserver.ehlo() # Check too see if an login attempt should be attempted if len(smtp_user) > 0: log.debug("Logging on to SMTP server using username \'%s\'%s", (smtp_user, " and a password" if len(smtp_pass) > 0 else "")) mailserver.login(smtp_user, smtp_pass) # Send the e-mail log.debug("Sending the email") mailserver.sendmail(from_address, splitString(to_address), message.as_string()) # Close the SMTP connection mailserver.quit() log.info('Email notification sent') return True except: log.error('E-mail failed: %s', traceback.format_exc()) return False
def create_mail(self): msg = MIMEMultipart() msg['To'] = self.mail_to msg['From'] = "<%s>%s" % (Header(self.mail_from_name, "UTF-8"), self.mail_from) msg['Subject'] = Header(self.mail_subject, "UTF-8") msg['Date'] = Utils.formatdate(localtime=1) msg['Message-ID'] = Utils.make_msgid() body = MIMEMultipart('alternative') body.attach(self.getpart(self.message, self.contenttype)) msg.attach(body) self.msg = msg.as_string()
def clear_attachment(msg_part): try: del msg_part['content-type'] del msg_part['content-disposition'] del msg_part['content-transfer-encoding'] del msg_part['content-id'] msg_part.add_header('Content-Type', 'text/html', charset='UTF-8') msg_part.add_header('Content-Disposition', 'inline') msg_part.add_header('Content-ID', Utils.make_msgid()) msg_part.set_payload('\n', charset='UTF-8') except Exception as e: handle_error('clear_attachment', str(e))
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 CreateEmailTo(sender_name, sender_email, recipient, subject, body): mail = MIMEMultipart('alternative') mail['From'] = emailutils.formataddr((sender_name, sender_email)) mail['To'] = recipient mail['Subject'] = Header(subject.encode('utf-8'), 'utf-8') mail['Message-Id'] = emailutils.make_msgid() mail['Date'] = emailutils.formatdate(localtime=True) mail.set_param('charset', 'utf-8') if isinstance(body, unicode): mail.attach(MIMEText(body.encode('utf-8'), 'plain', 'utf-8')) else: mail.attach(MIMEText(body)) return mail
def compose_mail(self): """ Purpose: Compose the complete mail, including header and body Returns: The body as an MIMEText object """ message_id = Utils.make_msgid() body = MIMEText(self.__message) body['Subject'] = '%s test mail from %s[%s]' % (self.__test, __file__, self.__local_hostname) body['Date'] = Utils.formatdate(localtime=1) body['From'] = self.__mail_from body['To'] = self.__rcpt_to body['Message-ID'] = message_id return body
def SendHtmlEmail(sender, receiver, subject, content, ctype="html", pics=[], smtpserver='mail.51ping.com', username=None, password=None): #def SendHtmlEmail(sender, receiver, subject, content, ctype="html", pics=[], smtpserver='smtp.gmail.com', username="******", password="******"): """subject and body are unicode objects""" if (ctype == "html"): msg = MIMEText(content, 'html', 'utf-8') else: msg = MIMEText(content, 'plain', 'utf-8') if (len(pics) != 0): msgRoot = MIMEMultipart('related') msgText = MIMEText(content, 'html', 'utf-8') msgRoot.attach(msgText) i = 1 for pic in pics: fp = open(pic, "rb") image = MIMEImage(fp.read()) fp.close() image.add_header('Content-ID', '<img%02d>' % i) msgRoot.attach(image) i += 1 msg = msgRoot msg['Subject'] = Header(subject, 'utf-8') msg['From'] = sender msg['To'] = ','.join(receiver) msg['Message-ID'] = Utils.make_msgid() msg['date'] = time.strftime('%a, %d %b %Y %H:%M:%S %z') #print receiver smtp = smtplib.SMTP() #smtp.set_debuglevel(1) smtp.connect(smtpserver, 25) #smtp.starttls() if username: smtp.login(username, password) #print msg.as_string() smtp.sendmail(sender, receiver, msg.as_string()) #smtp.sendmail(sender, receiver, 'Date: Wed, 6 Nov 2013 06:37:46 +0000\n' + msg.as_string()) print "send email " + subject + "succesfull. ^-^" smtp.quit()
def main(): parser = argparse.ArgumentParser(description='SendMail Python v.02') parser.add_argument('--sender',help='Select the Sender', required=False) parser.add_argument('--to',help='Select the Recipient', required=True) #parser.add_argument('--replyTo',help='Reply-To Recipient ', required=False) parser.add_argument('--server',help='Host Server', required=True) parser.add_argument('--port',help='Server Port', required=True) parser.add_argument('--ssl',help='SSL ON/OFF', required=False) parser.add_argument('--auth',help='Authentication username:password', required=False) args = parser.parse_args() if args.sender: fromaddr = args.sender else: fromaddr = '*****@*****.**' subject = "SendMail Test " + strftime("%Y-%m-%d %H:%M:%S") content = "Hello World! \n This is an automated test.\n\n" + strftime("%Y-%m-%d %H:%M:%S") msg = MIMEText(content) msg['From'] = fromaddr msg['To'] = args.to msg['Subject'] = subject msg['Message-ID'] = Utils.make_msgid() # msg.add_header('Reply-To', args.replyTo) NOT WORKING try: if args.ssl == 'on': server = smtplib.SMTP_SSL(args.server, args.port) server.set_debuglevel(True) server.ehlo() else: server = smtplib.SMTP(args.server, args.port) server.set_debuglevel(True) server.ehlo() server.starttls() if args.auth: username = args.auth.split(':')[0] password = args.auth.split(':')[1] server.ehlo() server.login(username, password) server.sendmail(msg['From'], [msg['To']], msg.as_string()) server.quit() print msg except SMTPException: print "Error: unable to send email"
def compose_mail(self): """ Purpose: Compose the complete mail, including header and body Returns: The body as an MIMEText object """ message_id = Utils.make_msgid() body = MIMEText(self.__message) body['Subject'] = '%s test mail from %s[%s]' % (self.__test, __file__, self.__local_hostname) body['Date'] = Utils.formatdate(localtime=1) body['From'] = self.__mail_from body['To'] = self.__rcpt_to body['Message-ID'] = message_id return body
def xmlrpc_resetpassword(self, listname): def page(message): return self.page(message, listname, password, listadmin, confirmation) listname = (listname or '').strip() cryptor = AES.new(self.secret_cipher, AES.MODE_ECB) # check values are good; else return error if not listname: raise self.Fault('Please fill in all fields.') if not re.search('^[0-9a-zA-Z\-_]+$',listname): raise self.Fault('Listname contains funny characters. Try again.') # check if it exists as a list; if so, return error if not self.islist(listname): raise self.Fault('Sorry - list does not exist.') # AES has a block size of 16 bytes. By convention, pad the message at the # end with 16 - (len(message) % 16) bytes of value 16 - (len(message) % 16). # When the decrypted bytes are interpreted at the end, these pad bytes will # show up in the last part of the split list, and will be discarded. For # this reason, make sure the message ends with a null character by including # an empty string in the list to join. message = '\x00'.join([listname, '']) pad_size = 16 - (len(message) % 16) message += ''.join([chr(pad_size) for x in xrange(0, pad_size)]) token = cryptor.encrypt(message) confirmurl = "https://www.hcs.harvard.edu/reset-list-password?%s" % \ urllib.urlencode( { 't' : base64.urlsafe_b64encode(token), 'm' : base64.urlsafe_b64encode(self.computeMAC(message)) }) admins = self.get_admins(listname) # Send confirmation e-mail. mail(admins, self.confirm_password_message % { 'date' : Utils.formatdate(localtime = True), 'messageid' : Utils.make_msgid(), 'listname' : listname, 'recipients': ', '.join(admins), 'confirmurl' : confirmurl }) return True
def __make_header(self): # Header # self.message['Message-Id'] = Header(self.__make_msgid(), self.character) self.message['Message-Id'] = Header(Utils.make_msgid(), self.character) if self.reply_to: self.message['Reply-to'] = Header(self.reply_to, self.character) self.message['Subject'] = Header(self.subject, self.character) self.message['From'] = Header(self.mail_from, self.character) self.message['To'] = Header(self.mail_to, self.character) self.message["Date"] = Utils.formatdate(localtime=True) # self.message['List-Unsubscribe'] = "<mailto:[email protected]>" if self.is_need_receipt: self.message['Disposition-Notification-To'] = Header(self.mail_from, self.character) if self.edm_check_result: self.message['Edm-Check-Result'] = Header(self.edm_check_result, self.character)
def sendEmail(): try: print('input the message what U want to say: ') mess = sys.stdin.readline().rstrip() msg = MIMEText(mess) msg['To'] = '*****@*****.**' msg['From'] = '*****@*****.**' msg['Date'] = Utils.formatdate(localtime=1) msg['Message-ID'] = Utils.make_msgid() print msg.as_string() log = open('log', 'w') log.write(msg.as_string()) except: traceback.print_exc() sys.exit(1)
def __make_header(self): # Header from email import utils # self.message['Message-Id'] = Header(self._makeMsgId(), self.character) self.message['Message-Id'] = Header(Utils.make_msgid(), self.character) if self.reply_to: self.message['Reply-to'] = Header(self.reply_to, self.character) self.message['Subject'] = Header(self.subject, self.character) self.message['From'] = Header(self.mail_from, self.character) self.message['To'] = Header(self.mail_to, self.character) self.message["Date"] = Utils.formatdate(localtime=True) if self.is_need_receipt: self.message['Disposition-Notification-To'] = Header( self.mail_from, self.character) if self.edm_check_result: self.message['Edm-Check-Result'] = Header(self.edm_check_result, self.character)
def send_email(sender, receiver, subject, content, ctype="html", smtpserver='mail.51ping.com', username=None, password=None): for i in range(3): try: server = smtplib.SMTP() server.connect(smtpserver) msg = MIMEText(message,_subtype=ctype,_charset='utf-8') msg['Subject'] = subject msg['From'] = sender msg['To'] = receiver msg['Message-ID'] = Utils.make_msgid() msg['date']=time.strftime('%a, %d %b %Y %H:%M:%S %z') now = time.strftime('%Y-%m-%d %H:%M:%S',time.localtime(time.time())) print '%s ----' % now server.sendmail(sender, receiver.split(','), msg.as_string()) server.close() return 'Send Email to %s SUCCESS!' % receiver except Exception,e: continue
def msginfo(self, msg, subject, filename): # message = """Hello, ALL #This is test message. #--Anonymous""" message = msg msg = MIMEMultipart() msg['To'] = self.to_addr msg['From'] = 'sa <' + self.from_addr + '>' msg['Date'] = Utils.formatdate(localtime=1) msg['Message-ID'] = Utils.make_msgid() if subject: msg['Subject'] = subject if message: body = MIMEText(message, _subtype='plain') msg.attach(body) #for filename in sys.argv[1:]: if filename: msg.attach(self.attachment(filename)) return msg.as_string()
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 msginfo(self,msg,subject,filename): # message = """Hello, ALL #This is test message. #--Anonymous""" message=msg msg=MIMEMultipart() msg['To'] = self.to_addr msg['From'] = 'sa <'+self.from_addr+'>' msg['Date'] = Utils.formatdate(localtime=1) msg['Message-ID'] = Utils.make_msgid() if subject: msg['Subject'] = subject if message: body=MIMEText(message,_subtype='plain') msg.attach(body) #for filename in sys.argv[1:]: if filename: msg.attach(self.attachment(filename)) return msg.as_string()
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 send_text_email(self,Subject,content,receiver,user_email): sender = '*****@*****.**' themsg = MIMEMultipart() themsg['Subject'] = Subject themsg['To'] = receiver themsg['From'] = 'map2family' themsg['Date'] = Utils.formatdate(localtime = 1) themsg['Message-ID'] = Utils.make_msgid() msgAlternative = MIMEMultipart('alternative') themsg.attach(msgAlternative) content = '---此邮件由map2family代'+user_email+'发送。<br/>' + content + '<br/>-----www.map2family.com' msgText = MIMEText(content,'html', 'utf-8') msgAlternative.attach(msgText) themsgtest = themsg.as_string() # send the message server = smtplib.SMTP() server.connect(SMTP_SERVER) server.login(SMTP_SERVER_USER, SMTP_SERVER_PWD) server.sendmail(sender, receiver, themsgtest) server.quit()#SMTP.quit()
def send_text_email(self,Subject,content,receiver): if settings.EMAIL_SWITCH: sender = settings.SMTP_SERVER_USER themsg = MIMEMultipart() themsg['Subject'] = Subject themsg['To'] = receiver themsg['From'] = 'AD Jason' themsg['Date'] = Utils.formatdate(localtime = 1) themsg['Message-ID'] = Utils.make_msgid() msgAlternative = MIMEMultipart('alternative') themsg.attach(msgAlternative) content = content + '<br/>www.adjason.com' msgText = MIMEText(content,'html', 'utf-8') msgAlternative.attach(msgText) themsgtest = themsg.as_string() # send the message server = smtplib.SMTP() server.connect(settings.SMTP_SERVER) server.login(settings.SMTP_SERVER_USER, settings.SMTP_SERVER_PWD) server.sendmail(sender, receiver, themsgtest) server.quit()#SMTP.quit()
def send_text_email(self, Subject, content, receiver): if settings.EMAIL_SWITCH: sender = '*****@*****.**' themsg = MIMEMultipart() themsg['Subject'] = Subject themsg['To'] = receiver themsg['From'] = u'吃典网' themsg['Date'] = Utils.formatdate(localtime=1) themsg['Message-ID'] = Utils.make_msgid() msgAlternative = MIMEMultipart('alternative') themsg.attach(msgAlternative) content = content + '<br/>www.lechier.com' msgText = MIMEText(content, 'html', 'utf-8') msgAlternative.attach(msgText) themsgtest = themsg.as_string() # send the message server = smtplib.SMTP() server.connect(settings.SMTP_SERVER) server.login(settings.SMTP_SERVER_USER, settings.SMTP_SERVER_PWD) server.sendmail(sender, receiver, themsgtest) server.quit() #SMTP.quit()
def send_mail(sender, receiver, subject, content, ctype="html", pics=()): """subject and body are unicode objects""" if not sender: sender = current_app.config.get("DEFAULT_MAIL_SENDER") smtp_server = current_app.config.get("MAIL_SERVER") if ctype == "html": msg = MIMEText(content, 'html', 'utf-8') else: msg = MIMEText(content, 'plain', 'utf-8') if len(pics) != 0: msg_root = MIMEMultipart('related') msg_text = MIMEText(content, 'html', 'utf-8') msg_root.attach(msg_text) i = 1 for pic in pics: fp = open(pic, "rb") image = MIMEImage(fp.read()) fp.close() image.add_header('Content-ID', '<img%02d>' % i) msg_root.attach(image) i += 1 msg = msg_root msg['Subject'] = Header(subject, 'utf-8') msg['From'] = sender msg['To'] = ';'.join(receiver) msg['Message-ID'] = Utils.make_msgid() msg['date'] = time.strftime('%a, %d %b %Y %H:%M:%S %z') smtp = smtplib.SMTP() smtp.connect(smtp_server, 25) username, password = current_app.config.get( "MAIL_USERNAME"), current_app.config.get("MAIL_PASSWORD") if username and password: smtp.login(username, password) smtp.sendmail(sender, receiver, msg.as_string()) smtp.quit()
def notifyAfterRegister(self, newSubscriber): """ Make and send the activation mail """ charset = self.ploneCharset() subject = config.DEFAULT_ACTIVATION_SUBJECT subject = safe_unicode(subject) subject = str(Header.Header(subject, 'utf8')) newId = newSubscriber.getId() newKey = newSubscriber.getActiveKey() active_url = self.absolute_url() active_url += '/%s?active=%s' % (newId, newKey) emailaddress = newSubscriber.getEmail() emailfromaddress = config.DEFAULT_EMAILFROMADDRESS bodyText = config.DEFAULT_ACTIVATION_TEMPLATE % { 'email' : emailaddress, 'url' : active_url } bodyText = safe_unicode(bodyText).encode(charset) mailMsg = Message.Message() mailMsg["To"] = newSubscriber.getEmail() mailMsg["From"] = emailfromaddress mailMsg["Subject"] = subject mailMsg["Date"] = Utils.formatdate(localtime=1) mailMsg["Message-ID"] = Utils.make_msgid() mailMsg["Mime-version"] = "1.0" mailMsg["Content-type"]="text/plain" mailMsg.set_payload(bodyText, charset) mailMsg.epilogue="\n" try: self.sendmail( emailfromaddress, (emailaddress,), mailMsg, subject=subject ) except Exception, e: print '>>> notifyAfterRegister: ', str(e) return False
def sendmail(update_infos, email=USERMAIL): '''send notification mail''' sender= '*****@*****.**' message='This Mangas have been updated, please check them soon ! : \n\n' for info in update_infos: message+="Name: %s\tlast_chapter: %s\tpath: %s\n"%(info[0],info[1],info[2]) msg = MIMEText(message) msg["Subject"] = "Manga updates notification" msg["Message-id"] = eUtils.make_msgid() msg["From"] = sender msg["To"] = email try: host = "smtp.gmail.com" server = smtplib.SMTP(host) server.sendmail(sender, email, msg.as_string()) server.quit() except Exception as e: print "Notification not send!\nMail only work with gmail account" print e
#!/usr/bin/env python from email.MIMEText import MIMEText from email import Utils message = 'lll' msg = MIMEText(message) msg['To'] = '*****@*****.**' msg['From'] = 'Test Sender <*****@*****.** >' msg['Subject'] = 'c9' msg['Date'] = Utils.formatdate(localtime=1) msg['Message-ID'] = Utils.make_msgid() print msg.as_string()
def sendNotify(self, notifyEvent=None, notifyObj=None): """ sending the real notification to the user """ print "NotifierEmail::sendNotify(%s, %s)" % (notifyEvent, notifyObj) pau_utility = getUtility(IAuthentication) en_utility = getUtility(IMailDelivery, 'ikEmailNotifierQueue') toList = [] toShortList = [] if pau_utility and pau_utility.has_key('principals'): principals = pau_utility['principals'] for (name, obj) in principals.items(): #print "v" * 60 #print "principal_name: %s" % name principal_id = principals.prefix + name #print "principal_id: %s" % principal_id notifDict = getNotifierDict4User(principal_id) #returns: #{'timezone': None, #'email': None, #'notifierChannels': None, #'notifierLevel': None, #'shortEmail': None, #'shortNotifierChannels': None, #'shortNotifierLevel': None, #'shortEmail': None, #} #print "notifDict: %s" % notifDict #print "notifyEvent.channels", notifyEvent.channels #print "notifyEvent.level", notifyEvent.level # long email #print "email: %s" % notifDict['email'] if notifDict['email'] is not None \ and len(notifDict['email']) > 0 \ and notifyEvent is not None \ and notifyEvent.channels is not None \ and notifyEvent.level is not None \ and notifDict['notifierChannels'] is not None \ and (notifyEvent.level >= notifDict['notifierLevel']) \ and (len(set(notifDict['notifierChannels'])\ .intersection(notifyEvent.channels)) > 0): toList.append(notifDict['email']) # short email #print "shortEmail: %s" % notifDict['shortEmail'] if notifDict['shortEmail'] is not None \ and len(notifDict['shortEmail']) > 0: toShortList.append(notifDict['shortEmail']) if notifDict['shortEmail'] is not None \ and len(notifDict['shortEmail']) > 0 \ and notifyEvent is not None \ and notifyEvent.channels is not None \ and notifyEvent.level is not None \ and notifDict['shortNotifierChannels'] is not None \ and (notifyEvent.level >= notifDict['shortNotifierLevel']) \ and (len(set(notifDict['shortNotifierChannels'])\ .intersection(notifyEvent.channels)) > 0): toShortList.append(notifDict['shortEmail']) #print "^" * 60 #if en_utility: #en_utility.send("aaa", [email], "ccc_msg") #email = pr_anno_utility.getAnnotationsById(principal_id).data['org.ict_ok.admin_utils.usermanagement']['email'] #print "email: %s" % email #dddd2 = AdmUtilUserManagement(obj) #print "dddd2: %s" % dddd2 #print "dddd2.email: %s" % dddd2.email print "toList: ", toList print "toShortList: ", toShortList if en_utility: if len(toList) > 0: filename = datetime.now().strftime('ictrpt_%Y%m%d%H%M%S.pdf') f_handle, f_name = tempfile.mkstemp(filename) #authorStr = self.request.principal.title authorStr = notifyLabel #from zope.i18n.locales import LocaleDates #dates = LocaleDates() #my_formatter = dates.getFormatter('dateTime', 'full') #my_formatter = self.request.locale.dates.getFormatter( #'dateTime', 'medium') #userTZ = getUserTimezone() #userTZ = getUserTimezone() #longTimeString = my_formatter.format(\ #userTZ.fromutc(datetime.utcnow())) #longTimeString = my_formatter.format(\ #datetime.utcnow()) #versionStr = "%s [%s]" % (longTimeString, getIkVersion()) versionStr = "[%s]" % (getIkVersion()) if ISuperclass.providedBy(notifyEvent.object): notifyEvent.object.generatePdf(\ f_name, authorStr, versionStr) else: self.generatePdf(f_name, authorStr, versionStr) for rcpt in set(toList): msg = MIMEMultipart() msg['To'] = rcpt msg['From'] = self.from_addr msg['Subject'] = '[%s] %s' % (str(notifyLabel), notifyEvent.subject) msg['Date'] = Utils.formatdate(localtime=1) msg['Message-ID'] = Utils.make_msgid() if type(notifyEvent.object) == type("") or \ type(notifyEvent.object) == type(""): outText = notifyEvent.object else: if ISuperclass.providedBy(notifyEvent.object): outText = u"System: '%s': state changed" % \ (notifyEvent.object.ikName) else: outText = u"unknown object type in ict-ok.org instance" body = MIMEText(outText, _subtype='plain', _charset='latin-1') msg.attach(body) datafile = open(f_name, "r") msg.attach(self.attachment(filename, datafile)) datafile.close() en_utility.send(self.from_addr, [rcpt], msg.as_string()) #print "self.from_addr: ", self.from_addr #print "toList: ", toList #print "msg.as_string(): ", msg.as_string() os.remove(f_name) for rcpt in set(toShortList): msg = MIMEMultipart() msg['To'] = rcpt msg['From'] = self.from_addr msg['Subject'] = '[%s] %s' % (str(notifyLabel), notifyEvent.subject) msg['Date'] = Utils.formatdate(localtime=1) msg['Message-ID'] = Utils.make_msgid() if type(notifyEvent.object) == type("") or \ type(notifyEvent.object) == type(""): outText = notifyEvent.object else: if ISuperclass.providedBy(notifyEvent.object): outText = u"System: '%s': state changed" % \ (notifyEvent.object.ikName) else: outText = u"unknown object type in ict-ok.org instance" body = MIMEText(outText, _subtype='plain', _charset='latin-1') msg.attach(body) en_utility.send(self.from_addr, [rcpt], msg.as_string())
def send_mail(self, sender, receivers, message, subject, ccreceivers='', attatchments=[]): def attachment(filename): fd = open(filename, 'rb') mimetype, mimeencoding = mimetypes.guess_type(filename) if mimeencoding or (mimetype is None): mimetype = 'application/octet-stream' maintype, subtype = mimetype.split('/') if maintype == 'text': retval = MIMEText(fd.read().encode('utf-8'), _subtype=subtype, _charset='utf-8') else: retval = MIMEBase(maintype, subtype) retval.set_payload(fd.read()) Encoders.encode_base64(retval) retval.add_header('Content-Disposition', 'attachment', filename=filename) fd.close() return retval msg = MIMEMultipart() if isinstance(receivers, (str, unicode)): t_receivers = string.split(receivers, ";") + string.split( ccreceivers, ';') msg['To'] = receivers msg['CC'] = ccreceivers else: t_receivers = receivers.extend(ccreceivers) msg['To'] = ';'.join(receivers) msg['CC'] = ';'.join(ccreceivers) msg['From'] = sender msg['Subject'] = Header(subject, 'utf-8') msg['Date'] = Utils.formatdate(localtime=1) msg['Message-ID'] = Utils.make_msgid() body = MIMEText(message, _subtype='html', _charset='utf-8') msg.attach(body) for filename in attatchments: msg.attach(attachment(filename)) smtp = smtplib.SMTP() for server in self.server_list: print 'Connecting to mail server %s' % server try: smtp.connect(server) smtp.sendmail(sender, t_receivers, msg.as_string()) print "Mail has been sent out." smtp.quit() break except smtplib.SMTPException, ex: continue except socket.error, se: print 'connection error: %s' % str(se) continue
def EnviaCorreo(TOADDRESS, HOST, TIPO): handler.log.info('enviando alerta por correo a ' + TOADDRESS) try: mailServer = SMTP(SMTPHOST, SMTPPORT) mailServer.set_debuglevel(SMTPDEBUGLEVEL) mailServer.ehlo() mailServer.starttls() mailServer.ehlo() mailServer.login(SMTPUSER, SMTPPASS) # creo el mensaje msg = MIMEMultipart('alternative') msg['From'] = SMTPUSER msg['To'] = TOADDRESS msg['Date'] = Utils.formatdate(localtime = 1) msg['Message-ID'] = Utils.make_msgid() msg['Subject'] = "Alerta SBC - " + HOST if TIPO == 0: # Create the body of the message (a plain-text and an HTML version). text = "Estimado " + TOADDRESS + "!\n\n el servidor " + HOST + " ha vuelto a estar en linea" html = """\ <html> <head></head> <body> <p>Estimado usuario!<br><br> el servidor ha vuelto a estar en linea </p> </body> </html> """ elif TIPO == 1: # Create the body of the message (a plain-text and an HTML version). text = "Estimado " + TOADDRESS + "!\n\n el servidor " + HOST + " esta fuera de linea" html = """\ <html> <head></head> <body> <p>Estimado usuario!<br><br> el servidor esta fuera de linea </p> </body> </html> """ else: handler.log.info('el tipo ' + TIPO + ' no es un valor valido') # Record the MIME types of both parts - text/plain and text/html. part1 = MIMEText(text, 'plain') part2 = MIMEText(html, 'html') # Attach parts into message container. # According to RFC 2046, the last part of a multipart message, in this case # the HTML message, is best and preferred. msg.attach(part1) msg.attach(part2) # envio del mensaje mailServer.sendmail(msg['From'], [msg['To']], msg.as_string()) mailServer.quit() except Exception as message: handler.log.error('error al enviar alerta por correo') handler.log.exception(message) finally: mailServer.close()
def createMessageID(): """Creates a unique message id @return: String containing the unique message id""" return Utils.make_msgid()
def _send_email(self, user_id, email): print 'Now processing %s' % email now = datetime.datetime.now() dt = datetime.date(year=now.year, month=now.month, day=now.day) date_from = dt - datetime.timedelta(days = settings.QUERY_FROM_DELTA) date_to = dt + datetime.timedelta(days = settings.QUERY_TO_DELTA) self._open_database() session = self.Session() # build query query_a = session.query(Birthday.date, Birthday.descr) query_a = query_a.filter(BirthdaySubscription.birthday_id == Birthday.id) query_a = query_a.filter(BirthdaySubscription.user_id == user_id) query_a = query_a.filter(Birthday.date.between(date_from, date_to)) query_b = session.query(SpecialDay.date, SpecialDay.descr) query_b = query_b.filter(SpecialDay.date.between(date_from, date_to)) query_c = session.query(Appointment.date, Appointment.descr) query_c = query_c.filter(Appointment.date.between(date_from, date_to)) query = query_a.union(query_b).union(query_c) query = query.order_by('1') # order by date column events = {} i = 0 for record in query.all(): i += 1 dt = datetime.datetime(year=record.date.year, month=record.date.month, day=record.date.day) sort_field = dt.strftime('%Y%m%d-') + str(i) events[sort_field] = '%s - %s' % (dt.strftime(settings.DATESTRING), record.descr) if not events: # nothing to do... return # note: Now sorted on date. Sorting on description would be sorted(events.iteritems()) body = [] for record in sorted(events): if settings.IS_TEST: print events[record] body.append(events[record]) if settings.IS_TEST: email = settings.EMAIL_RECEIVER_TEST # Create email msg = MIMEText("\n".join(body)) msg['Date'] = Utils.formatdate(localtime = 1) msg['Subject'] = settings.EMAIL_SUBJECT msg['From'] = settings.EMAIL_SENDER msg['To'] = email msg['Message-ID'] = Utils.make_msgid() # Send the message via our own SMTP server, but don't include the envelope header. s = smtplib.SMTP(settings.SMTP_SERVER, settings.SMTP_PORT) if settings.SMTP_TLS: s.ehlo() s.starttls() s.ehlo() s.login(settings.SMTP_USER, settings.SMTP_PASSWORD) s.sendmail(settings.EMAIL_SENDER, email, msg.as_string()) s.quit()
def _getMIMEmessage( sFrom, uTo, sSubject, sBody, uCC = None, bHtmlMsg = False, sCharSet = 'UTF-8', lAttachments= [], **kwargs ): # # other mail headers can go in kwargs # eg Return-Path # # from email.MIMEText import MIMEText # import base64, quopri # from cStringIO import StringIO from email import encoders from email import Utils from email.Message import Message from email.mime.base import MIMEBase from email.mime.multipart import MIMEMultipart from email.mime.text import MIMEText from mimetypes import guess_type from os.path import basename # from eMail.Get import getAddresseeStrOffSeq from File.Test import isFileThere from Iter.AllVers import tFilter # if lAttachments: # iLenBeg = len( lAttachments ) # tThere = tFilter( isFileThere, lAttachments ) # if len( tThere ) < iLenBeg: # lCannotFind = [ s for s in lAttachments if s not in tThere ] # print3( 'Cannot find attachment', ', '.join( lCannotFind ) ) # raise AttachmentFailure # # # sType = 'plain' # if bHtmlMsg: # sType = 'html' # # if lAttachments: # oMsg = MIMEMultipart() # oMsg.attach( MIMEText( sBody, sType, sCharSet ) ) # else: # oMsg = MIMEText( sBody, sType, sCharSet ) # # if bHtmlMsg: # oMsg.set_default_type( 'message/rfc822' ) # # oMsg[ 'To' ] = getAddresseeStrOffSeq( uTo ) oMsg[ 'From' ] = sFrom # if uCC is not None: # oMsg[ 'CC' ] = getAddresseeStrOffSeq( uCC ) # # oMsg[ 'Subject' ] = sSubject oMsg[ 'Date' ] = Utils.formatdate( localtime = 1 ) oMsg[ 'Message-ID' ] = Utils.make_msgid() # for sFileSpec in lAttachments: # if not isFileThere( sFileSpec ): continue # sContentType,sEncoding = guess_type(sFileSpec) # if sContentType is None or sEncoding is not None: # If no guess, use generic opaque text sContentType = "application/octet-stream" # sMainType, sSubType = sContentType.split('/', 1) # if sMainType == 'text': oFile = open(sFileSpec) # Note: we should handle calculating the charset oAttach = MIMEText(oFile.read(), _subtype = sSubType) elif sMainType == 'image': oFile = open(sFileSpec, 'rb') oAttach = MIMEImage(oFile.read(), _subtype = sSubType) elif sMainType == 'audio': oFile = open(sFileSpec, 'rb') oAttach = MIMEAudio(oFile.read(), _subtype = sSubType) else: oFile = open(sFileSpec, 'rb') oAttach = MIMEBase(sMainType, sSubType) oAttach.set_payload(oFile.read()) # Encode the payload using Base64 encoders.encode_base64(oAttach) # oFile.close() # oAttach.add_header( 'Content-Disposition', 'attachment; filename="%s"' % basename( sFileSpec ) ) oMsg.attach(oAttach) # for k, v in _getItemIter( kwargs ): # oMsg[ k ] = v # # if bHtmlMsg: # oMsg.set_default_type( 'message/rfc822' ) # # return oMsg.as_string()
def xmlrpc_confirm(self, token, mac): def badconfirmlinkmsg(): return self.Fault('Your confirm link was invalid; contact acctserv@hcs '\ 'further assistance.') token = (token or '').strip() mac = (mac or '').strip() cryptor = AES.new(self.secret_cipher, AES.MODE_ECB) try: plaintext = cryptor.decrypt(base64.urlsafe_b64decode(token)) mac = base64.urlsafe_b64decode(mac) except ValueError: # if the code is a not a multiple of 16 bytes long raise badconfirmlinkmsg() except TypeError: # invalid padding raise badconfirmlinkmsg() if self.computeMAC(plaintext) != mac: raise badconfirmlinkmsg() # A proper listvars is of the form # [ listname, password, listadmin, confirmation, padding ] listvars = plaintext.split("\x00") if len(listvars) == 5: listname = listvars[0] password = listvars[1] listadmin = listvars[2] confirmation = listvars[3] # make list; else return error # os.system('/usr/lib/mailman/bin/newlist %s %s %s' % (listname, listadmin, password)) p = subprocess.Popen(('/usr/lib/mailman/bin/newlist', listname, listadmin, password), stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE) p.stdin.write('\n\n') p.stdin.close() retcode = p.wait() if retcode is 0: # return success message output = p.stdout.read() mail('*****@*****.**', self.log_success_message % { 'date' : Utils.formatdate(localtime = True), 'messageid' : Utils.make_msgid(), 'listname' : listname, 'password' : '...', 'listadmin' : listadmin, 'confirmation' : confirmation, 'output' : output }) return listname elif retcode is 16: raise self.Fault( 'Sorry - list already exists. Choose a different list name.') else: # non-standard problem -- e-mail systems/acctserv output = p.stdout.read() outerr = p.stderr.read() mail('*****@*****.**', self.unknown_mailman_error % { 'date' : Utils.formatdate(localtime = True), 'messageid' : Utils.make_msgid(), 'listname' : listname, 'password' : password, 'listadmin' : listadmin, 'confirmation' : confirmation, 'output' : output, 'outerr' : outerr }) # return unknown error raise self.Fault('Internal error. The systems team has been notified '\ 'and will be getting back to you.') else: # User submitted bad hash raise badconfirmlinkmsg()
def xmlrpc_newlist(self, listname, password, listadmin, confirmation): def page(message): return self.page(message, listname, password, listadmin, confirmation) listname = (listname or '').strip() password = (password or '').strip() listadmin = (listadmin or '').strip() confirmation = (confirmation or '').strip() cryptor = AES.new(self.secret_cipher, AES.MODE_ECB) # check values are good; else return error if not listname or not password or not listadmin: raise self.Fault('Please fill in all fields.') if not re.search('^[0-9a-zA-Z\-_]+$',listname): raise self.Fault('Listname contains funny characters. Try again.') if not re.search('^[\+\.\w\-_]+@([\w\-_]+\.)+[a-zA-Z]{2,4}$', listadmin): raise self.Fault('List admin e-mail must be a real e-mail address.') if not confirmation: confirmation = listadmin if not re.search(r'@(.*\.)?harvard\.edu$', confirmation): raise self.Fault('Confirmation must be to a harvard address') hcsemail = re.match(r'([\+\.\w\-_]+)@hcs.harvard.edu', confirmation) if hcsemail != None and self.islist(hcsemail.group(1)): raise self.Fault('Cannot use a mailing list as a confirmation email.') # check if it exists as a list; if so, return error if self.islist(listname): raise self.Fault('Sorry - list already exists. Choose a different list name.') # check if it exists as an alias or user account if self.is_user_or_alias(listname): raise self.Fault('Sorry, the name "%s" is taken by an HCS account.' %\ listname) # AES has a block size of 16 bytes. By convention, pad the message at the # end with 16 - (len(message) % 16) bytes of value 16 - (len(message) % 16). # When the decrypted bytes are interpreted at the end, these pad bytes will # show up in the last part of the split list, and will be discarded. For # this reason, make sure the message ends with a null character by including # an empty string in the list to join. message = '\x00'.join([listname, password, listadmin, confirmation, '']) pad_size = 16 - (len(message) % 16) message += ''.join([chr(pad_size) for x in xrange(0, pad_size)]) token = cryptor.encrypt(message) confirmurl = "https://www.hcs.harvard.edu/make-list?%s" % \ urllib.urlencode( { 't' : base64.urlsafe_b64encode(token), 'm' : base64.urlsafe_b64encode(self.computeMAC(message)) }) # Send confirmation e-mail. mail(confirmation, self.confirm_message % { 'date' : Utils.formatdate(localtime = True), 'messageid' : Utils.make_msgid(), 'listname' : listname, 'password' : password, 'listadmin' : listadmin, 'confirmation' : confirmation, 'confirmurl' : confirmurl }) return True
#coding=utf8 #建立MIMEText对象 from email.MIMEText import MIMEText from email import Utils message = '''Hello, This is a test massage from test_MIMEText.py ''' msg = MIMEText(message) msg['From'] = '*****@*****.**' msg['To'] = 'Test Sender <*****@*****.**>' msg['Subject'] = u'来自test_MIMEText.py的问候…' msg['Date'] = Utils.formatdate(localtime=1) #产生当前日期时间 msg['Message-ID'] = Utils.make_msgid() #产生世界唯一的Message-ID print msg.as_string() ''' 构造一个邮件对象就是一个Messag对象,如果构造一个MIMEText对象,就表示一个文本邮件对象,如果构造一个MIMEImage对象,就表示一个作为附件的图片,要把多个对象组合 起来,就用MIMEMultipart对象,而MIMEBase可以表示任何对象。它们的继承关系如下: Message +- MIMEBase +- MIMEMultipart +- MIMENonMultipart +- MIMEMessage +- MIMEText +- MIMEImage '''
def createMessageID(): """Creates a unique message id @return: String containing the unique message id""" return Utils.make_msgid()
def create_html_mail(subject, html, text=None, from_addr=None, to_addr=None, headers=None, encoding='UTF-8', attachments=_marker): """Create a mime-message that will render HTML in popular MUAs, text in better ones. """ if attachments is _marker: attachments = [] # Use DumbWriters word wrapping to ensure that no text line # is longer than plain_text_maxcols characters. plain_text_maxcols = 72 html = html.encode(encoding) if text is None: # Produce an approximate textual rendering of the HTML string, # unless you have been given a better version as an argument textout = StringIO.StringIO() formtext = formatter.AbstractFormatter(formatter.DumbWriter( textout, plain_text_maxcols)) parser = htmllib.HTMLParser(formtext) parser.feed(html) parser.close() # append the anchorlist at the bottom of a message # to keep the message readable. counter = 0 anchorlist = "\n\n" + ("-" * plain_text_maxcols) + "\n\n" for item in parser.anchorlist: counter += 1 anchorlist += "[%d] %s\n" % (counter, item) text = textout.getvalue() + anchorlist del textout, formtext, parser, anchorlist else: text = text.encode(encoding) # if we would like to include images in future, there should # probably be 'related' instead of 'mixed' msg = MIMEMultipart('mixed') msg['Subject'] = subject msg['From'] = from_addr msg['To'] = to_addr msg['Date'] = formatdate(localtime=True) msg["Message-ID"] = Utils.make_msgid() if headers: for key, value in headers.items(): msg[key] = value msg.preamble = 'This is a multi-part message in MIME format.' alternatives = MIMEMultipart('alternative') msg.attach(alternatives) alternatives.attach(MIMEText(text, 'plain', _charset=encoding)) alternatives.attach(MIMEText(html, 'html', _charset=encoding)) # add the attachments for f, name, mimetype in attachments: if mimetype is None: mimetype = ('application', 'octet-stream') maintype, subtype = mimetype if maintype == 'text': # XXX: encoding? part = MIMEText(f.read(), _subtype=subtype) else: part = MIMEBase(maintype, subtype) part.set_payload(f.read()) Encoders.encode_base64(part) part.add_header( 'Content-Disposition', 'attachment; filename="%s"' % name) msg.attach(part) return msg
def sendNotify(self, notifyEvent=None, notifyObj=None): """ sending the real notification to the user """ print "NotifierEmail::sendNotify(%s, %s)" % (notifyEvent, notifyObj) pau_utility = getUtility(IAuthentication) en_utility = getUtility(IMailDelivery, 'ikEmailNotifierQueue') if pau_utility and pau_utility.has_key('principals'): principals = pau_utility['principals'] toList = [] toShortList = [] for (name, obj) in principals.items(): #print "v" * 60 #print "principal_name: %s" % name principal_id = principals.prefix + name #print "principal_id: %s" % principal_id notifDict = getNotifierDict4User(principal_id) #returns: #{'timezone': None, #'email': None, #'notifierChannels': None, #'notifierLevel': None, #'shortEmail': None, #'shortNotifierChannels': None, #'shortNotifierLevel': None, #'shortEmail': None, #} #print "notifDict: %s" % notifDict #print "notifyEvent.channels", notifyEvent.channels #print "notifyEvent.level", notifyEvent.level # long email #print "email: %s" % notifDict['email'] if notifDict['email'] is not None \ and len(notifDict['email']) > 0 \ and notifyEvent is not None \ and notifyEvent.channels is not None \ and notifyEvent.level is not None \ and notifDict['notifierChannels'] is not None \ and (notifyEvent.level >= notifDict['notifierLevel']) \ and (len(set(notifDict['notifierChannels'])\ .intersection(notifyEvent.channels)) > 0): toList.append(notifDict['email']) # short email #print "shortEmail: %s" % notifDict['shortEmail'] if notifDict['shortEmail'] is not None \ and len(notifDict['shortEmail']) > 0: toShortList.append(notifDict['shortEmail']) if notifDict['shortEmail'] is not None \ and len(notifDict['shortEmail']) > 0 \ and notifyEvent is not None \ and notifyEvent.channels is not None \ and notifyEvent.level is not None \ and notifDict['shortNotifierChannels'] is not None \ and (notifyEvent.level >= notifDict['shortNotifierLevel']) \ and (len(set(notifDict['shortNotifierChannels'])\ .intersection(notifyEvent.channels)) > 0): toShortList.append(notifDict['shortEmail']) #print "^" * 60 #if en_utility: #en_utility.send("aaa", [email], "ccc_msg") #email = pr_anno_utility.getAnnotationsById(principal_id).data['org.ict_ok.admin_utils.usermanagement']['email'] #print "email: %s" % email #dddd2 = AdmUtilUserManagement(obj) #print "dddd2: %s" % dddd2 #print "dddd2.email: %s" % dddd2.email print "toList: ", toList print "toShortList: ", toShortList if en_utility: msg = MIMEMultipart() #msg['To'] = '' #msg['Bcc'] = ",".join(toList) msg['From'] = self.from_addr msg['Subject'] = '[ict-ok.org] test' msg['Date'] = Utils.formatdate(localtime = 1) msg['Message-ID'] = Utils.make_msgid() ##body = MIMEText(message, _subtype='plain') outText = u"Hallo und ein Text mit Ä" body = MIMEText( outText, _subtype='plain', _charset='latin-1') msg.attach(body) filename = datetime.now().strftime('ictrpt_%Y%m%d%H%M%S.pdf') f_handle, f_name = tempfile.mkstemp(filename) #authorStr = self.request.principal.title authorStr = "ict-ok.org" #from zope.i18n.locales import LocaleDates #dates = LocaleDates() #my_formatter = dates.getFormatter('dateTime', 'full') #my_formatter = self.request.locale.dates.getFormatter( #'dateTime', 'medium') #userTZ = getUserTimezone() #userTZ = getUserTimezone() #longTimeString = my_formatter.format(\ #userTZ.fromutc(datetime.utcnow())) #longTimeString = my_formatter.format(\ #datetime.utcnow()) #versionStr = "%s [%s]" % (longTimeString, getIkVersion()) versionStr = "[%s]" % (getIkVersion()) self.generatePdf(f_name, authorStr, versionStr) datafile = open(f_name, "r") msg.attach(self.attachment(filename, datafile)) datafile.close() #ikreportmail = IkReportMail( "toooooo", outMeta) #tmpFile = os.tmpfile() #ikreportmail.gen( tmpFile, outList) #tmpFile.seek(0) #msg.attach( self.attachment( "IKOMtrol.pdf", tmpFile)) #return msg.as_string() en_utility.send(self.from_addr, toList, msg.as_string()) #en_utility.send(self.from_addr, toShortList, "ccc_msg_short") os.remove(f_name)