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_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 send_email_notification(self, title, number): """ This function sends an email using Gmail SMTP Server to any email with a message telling that the manga has been sent to the kindle cloud. Keyword arguments: title - The title of the manga number - The chapter number of the manga """ msg = MIMEMultipart.MIMEMultipart() msg['from'] = "*****@*****.**" msg['To'] = "*****@*****.**" msg['Date'] = Utils.formatdate(localtime=True) msg['Subject'] = 'Manga %s %s notification' % (title, number) msg.attach( MIMEText.MIMEText( 'The chapter number %s of manga %s has been sent to ' 'the kindle cloud' % (number, title))) smtp = smtplib.SMTP("smtp.gmail.com", 587) smtp.ehlo() smtp.starttls() smtp.login("*****@*****.**", "xxxpasswordxxx") smtp.sendmail("*****@*****.**", "*****@*****.**", msg.as_string()) smtp.close()
def send_zh(self, filename_in): self.smtp = smtplib.SMTP() self.smtp.connect(self.server) self.smtp.login(self.username, self.password) self.msg = MIMEMultipart() self.msg['to'] = self.to_mail self.msg['from'] = self.from_mail self.msg['Subject'] = "Convert" self.filename = filename_in + ".txt" self.msg['Date'] = Utils.formatdate(localtime=1) content = open(self.filename.decode('utf-8'), 'rb').read() print content self.att = MIMEBase('application', 'octet-stream') self.att.set_payload(content) self.att.add_header('Content-Disposition', 'attachment', filename=('gbk', '', self.filename)) Encoders.encode_base64(self.att) #self.att['Content-Type']='application/octet-stream' #self.att["Content-Disposition"] = "attachment;filename=\"%s\"" %self.filename #print self.att["Content-Disposition"] self.msg.attach(self.att) self.smtp.sendmail(self.msg['from'], self.msg['to'], self.msg.as_string()) self.smtp.quit()
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 sendTokenRequestMail(body): mail_from = config.get('smtp.mail_from') body = add_msg_niceties("Carlos", body, "CKAN Portal", "http://data.ilri.org/portal") msg = MIMEText(body.encode('utf-8'), 'plain', 'utf-8') ssubject = "New token request" subject = Header(ssubject.encode('utf-8'), 'utf-8') msg['Subject'] = subject msg['From'] = _("%s <%s>") % ("CKAN Portal", mail_from) recipient = u"%s <%s>" % ("Carlos Quiros", "*****@*****.**") msg['To'] = Header(recipient, 'utf-8') msg['Date'] = Utils.formatdate(time()) try: smtp_connection = smtplib.SMTP() smtp_server = config.get('smtp.server', 'localhost') smtp_user = config.get('smtp.user') smtp_password = config.get('smtp.password') smtp_connection.connect(smtp_server) smtp_connection.login(smtp_user, smtp_password) smtp_connection.sendmail(mail_from, ["*****@*****.**"], msg.as_string()) logging.info("Token Email sent to [email protected]") except Exception,e: logging.info("Token Sendmail error: " + str(e))
def send_manga_throw_email(self, title, number): """ This function sends an email using Gmail SMTP Server to the kindle cloud with the comic attached into it. Keyword arguments: title - The title of the manga number - The chapter number of the manga """ msg = MIMEMultipart.MIMEMultipart() msg['from'] = "*****@*****.**" msg['To'] = "*****@*****.**" msg['Date'] = Utils.formatdate(localtime=True) msg['Subject'] = '' msg.attach(MIMEText.MIMEText('')) part = MIMEBase.MIMEBase('application', "octet-stream") filename = title+"_"+str(number)+".mobi" part.set_payload(open(filename, "rb").read()) Encoders.encode_base64(part) part.add_header('Content-Disposition', 'attachment', filename=filename) msg.attach(part) smtp = smtplib.SMTP("smtp.gmail.com", 587) smtp.ehlo() smtp.starttls() smtp.login("*****@*****.**", "xxxpasswordxxx") smtp.sendmail("*****@*****.**", "*****@*****.**", msg.as_string()) smtp.close()
def sendMail(body,targetName,targetEmail,targetName2,targetEmail2,dataset): print "Sending email!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!" #targetEmail = "*****@*****.**" #targetEmail2 = "*****@*****.**" mail_from = '*****@*****.**' body = add_msg_niceties(targetName, body, "ILRI Datasets Portal", "http://data.ilri.org/portal") msg = MIMEText(body.encode('utf-8'), 'plain', 'utf-8') ssubject = "The dataset " + '"' + dataset + '"' + " will be made available in next two weeks" subject = Header(ssubject.encode('utf-8'), 'utf-8') msg['Subject'] = subject msg['From'] = u"%s <%s>" % ("CKAN Portal", mail_from) recipient = u"%s <%s>" % (targetName, targetEmail) + "," + u"%s <%s>" % (targetName2, targetEmail2) msg['To'] = Header(recipient, 'utf-8') msg['Date'] = Utils.formatdate(time()) try: smtp_server = 'smtp.office365.com' smtp_user = '******' smtp_password = '******' server = smtplib.SMTP(smtp_server,587) server.ehlo() server.starttls() server.ehlo() server.login(smtp_user, smtp_password) server.sendmail(mail_from, [targetEmail,targetEmail2], msg.as_string()) server.quit() print("Email sent to " + targetEmail + " and " + targetEmail2) except Exception,e: print str(e) print("Sendmail error: " + str(e))
def send_email(self, from_address, to_addresses, cc_addresses, bcc_addresses, subject, body): """ Send an email Args: to_addresses: must be a list cc_addresses: must be a list bcc_addresses: must be a list """ try: # Note: need Python 2.6.3 or more conn = SMTP_SSL(self.smtp_host, self.smtp_port) conn.login(self.user, self.password) msg = MIMEText(body, 'plain', self.email_default_encoding) msg['Subject'] = Header(subject, self.email_default_encoding) msg['From'] = from_address msg['To'] = ', '.join(to_addresses) if cc_addresses: msg['CC'] = ', '.join(cc_addresses) if bcc_addresses: msg['BCC'] = ', '.join(bcc_addresses) msg['Date'] = Utils.formatdate(localtime=True) # TODO: Attached file conn.sendmail(from_address, to_addresses, msg.as_string()) except: raise finally: conn.close()
def send_att_mail(sender, to_list, sub, content, att, user=username, passw=password): msg = MIMEMultipart() sender = getrealmailaddress(sender)[0] to_list = getrealmailaddress(to_list) msg['Subject'] = Header(sub, 'utf-8') msg['From'] = sender msg['To'] = ','.join(to_list) msg['Date'] = Utils.formatdate(localtime=1) print msg['Date'] attachment_file = att att1 = MIMEText(open(attachment_file, 'rb').read(), 'base64', 'gb2312') att1["Content-Type"] = 'application/octet-stream' att1[ "Content-Disposition"] = 'attachment; filename=' + attachment_file.split( "/")[-1] msg.attach(att1) # mail_context=MIMEText(content,'text','utf-8') mail_context = MIMEText(content, _subtype='plain', _charset='gb2312') msg.attach(mail_context) smtp = smtplib.SMTP() smtp.connect(smtp_server) smtp.login(user, passw) smtp.sendmail(sender, to_list, 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 send_txt(self, filename): # 这里发送附件尤其要注意字符编码,当时调试了挺久的,因为收到的文件总是乱码 self.smtp = smtplib.SMTP_SSL(port=465) self.smtp.connect(self.server) self.smtp.login(self.username, self.password) #self.msg = MIMEMultipart() self.msg = MIMEText("content", 'plain', 'utf-8') self.msg['to'] = self.to_mail self.msg['from'] = self.from_mail self.msg['Subject'] = "459" self.filename = filename + ".txt" self.msg['Date'] = Utils.formatdate(localtime=1) content = open(self.filename.decode('utf-8'), 'rb').read() # print(content) #self.att = MIMEText(content, 'base64', 'utf-8') #self.att['Content-Type'] = 'application/octet-stream' # self.att["Content-Disposition"] = "attachment;filename=\"%s\"" %(self.filename.encode('gb2312')) #self.att["Content-Disposition"] = "attachment;filename=\"%s\"" % Header(self.filename, 'gb2312') # print(self.att["Content-Disposition"]) #self.msg.attach(self.att) #self.smtp.sendmail(self.msg['from'], self.msg['to'], self.msg.as_string()) self.smtp.sendmail(self.msg['from'], self.msg['to'], self.msg.as_string()) self.smtp.quit()
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 corrupt_message(why, fromlines=None, fromstring=None): log = getmailcore.logging.Logger() log.error('failed to parse retrieved message; constructing container for ' 'contents\n') if fromlines == fromstring == None: raise SystemExit('corrupt_message() called with wrong arguments') msg = email.message_from_string('') msg['From'] = '"unknown sender" <>' msg['Subject'] = 'Corrupt message received' msg['Date'] = Utils.formatdate(localtime=True) body = [ 'A badly-corrupt message was retrieved and could not be parsed', 'for the following reason:', '', ' %s' % why, '', 'Below the following line is the original message contents.', '', '--------------------------------------------------------------', ] if fromlines: body.extend([line.rstrip() for line in fromlines]) elif fromstring: body.extend([line.rstrip() for line in fromstring.splitlines()]) msg.set_payload(os.linesep.join(body)) for attr in message_attributes: setattr(msg, attr, '') return msg
def send_txt(self, name, price, percent, status): if 'up' == status: content = '%s > %.2f , %.2f' % (name, price, percent) if 'down' == status: content = '%s < %.2f , %.2f' % (name, price, percent) content = content + '%' print(content) subject = '%s' % name self.msg = MIMEText(content, 'plain', 'utf-8') self.msg['to'] = self.to_mail self.msg['from'] = self.from_mail self.msg['Subject'] = subject self.msg['Date'] = Utils.formatdate(localtime=1) try: self.smtp = smtplib.SMTP_SSL(port=465) self.smtp.connect(self.server) self.smtp.login(self.username, self.password) self.smtp.sendmail(self.msg['from'], self.msg['to'], self.msg.as_string()) self.smtp.quit() print("sent") except smtplib.SMTPException, e: print(e) return 0
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 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 sendMail(): sender = '*****@*****.**' receiver = ['*****@*****.**', '*****@*****.**', '*****@*****.**', '*****@*****.**', '*****@*****.**'] # receiver = ['*****@*****.**'] smtpserver = 'mail.epcare.com.cn' username = '******' password = '******' yestoday = date.today() - timedelta(hours=24); msgRoot = MIMEMultipart('related') msgRoot['Subject'] = '每日域报告' msgRoot['From'] = sender msgRoot['To'] = ';'.join(receiver) msgRoot["Date"] = Utils.formatdate(localtime = 1) #文本内容 html = ''' <html> <head><head> <body> <p>Hi, all<br> <br> 以上是昨天各个域的发送情况,详看附件!<br> <br> 顺祝工作愉快!<br> <br> <img src="cid:image1"> </p> </body> </html> ''' msgText = MIMEText(html, 'html', 'utf-8') msgRoot.attach(msgText) fp = open('D:\\me.jpg', 'rb') msgImage = MIMEImage(fp.read()) fp.close() msgImage.add_header('Content-ID', '<image1>') msgRoot.attach(msgImage) #构造附件 the_dir = 'C:\\Users\\zhang\\Desktop\\%s\\' % yestoday if os.path.exists(the_dir) : os.chdir('%s' % (the_dir)) else: print 'no %s' % the_dir sys.exit() for dirfile in os.listdir(the_dir): if os.path.isfile(dirfile): csvfile = open(dirfile, 'rb') att = MIMEText(csvfile.read(), 'base64', 'utf-8') csvfile.close() att["Content-Type"] = 'application/octet-stream' att["Content-Disposition"] = 'attachment; filename="%s"' % dirfile msgRoot.attach(att) smtp = smtplib.SMTP() smtp.connect(smtpserver) smtp.login(username, password) smtp.sendmail(sender, receiver, msgRoot.as_string()) smtp.quit()
def send_mail(sender, to_list, sub, content, user, passw): msg = MIMEText(content, _subtype='plain', _charset='gb2312') msg['Subject'] = Header(sub, 'utf-8') msg['From'] = sender msg['To'] = to_list msg['Date'] = Utils.formatdate(localtime=1) print msg['Date'] smtp = smtplib.SMTP() smtp.connect(smtp_server) smtp.login(user, passw) for recipient in to_list.split(','): smtp.sendmail(sender, recipient, msg.as_string()) smtp.quit
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 message(address): body = """ Dear Editor, the author {user} has uploaded replication files to your journal's data archive.\n {submission_id} You can review it here:\n\n\t {url} best regards from ZBW--Journal Data Archive """ d = { 'user': author, 'url': package_url(dataset), 'submission_id': subid() } body = body.format(**d) msg = MIMEText(body.encode('utf-8'), 'plain', 'utf-8') msg['Subject'] = Header( u"ZBW Journal Data Archive: Review Notification") msg['From'] = config.get('smtp.mail_from') msg['To'] = Header(address, 'utf-8') msg['Date'] = Utils.formatdate(time()) msg['X-Mailer'] = "CKAN {} [Plugin edawax]".format(ckan_version) return msg
def main(): """Shows basic usage of the Google Admin-SDK Groups Migration API. Creates a Google Admin-SDK Groups Migration API service object and inserts a test email into a group. """ credentials = get_credentials() http = credentials.authorize(httplib2.Http()) service = discovery.build('groupsmigration', 'v1', http=http) print('Warning: A test email will be inserted into the group entered.') groupId = raw_input( 'Enter the email address of a Google Group in your domain: ') # Format an RFC822 message message = MIMEText.MIMEText('This is a test.') # Generate a random 10 digit number for message Id. message['Message-ID'] = '<{0}-{1}>'.format(str(random.randrange(10**10)), groupId) message['Subject'] = 'Groups Migration API Test (Python)' message['From'] = '"Alice Smith" <*****@*****.**>' message['To'] = groupId message['Date'] = Utils.formatdate(localtime=True) stream = StringIO.StringIO() stream.write(message.as_string()) media = apiclient.http.MediaIoBaseUpload(stream, mimetype='message/rfc822') result = service.archive().insert(groupId=groupId, media_body=media).execute() print(result['responseCode'])
def sendTokenRequestMail(body, targetName, targetEmail): #print "IN sendTokenRequestMail********************" #targetEmail = "*****@*****.**" #targetEmail2 = "*****@*****.**" mail_from = config.get('smtp.mail_from') body = add_msg_niceties(targetName, body, "ILRI Datasets Portal", "http://data.ilri.org/portal") msg = MIMEText(body.encode('utf-8'), 'plain', 'utf-8') ssubject = "Your application for confidential information at http://data.ilri.org/portal" subject = Header(ssubject.encode('utf-8'), 'utf-8') msg['Subject'] = subject msg['From'] = _("%s <%s>") % ("CKAN Portal", mail_from) recipient = u"%s <%s>" % (targetName, targetEmail) msg['To'] = Header(recipient, 'utf-8') msg['Date'] = Utils.formatdate(time()) try: smtp_server = config.get('smtp.server', 'localhost') smtp_user = config.get('smtp.user') smtp_password = config.get('smtp.password') server = smtplib.SMTP(smtp_server, 587) server.ehlo() server.starttls() server.ehlo() server.login(smtp_user, smtp_password) server.sendmail(mail_from, [targetEmail], msg.as_string()) server.quit() logging.debug("Token Email sent to " + targetEmail) except Exception, e: print str(e) logging.debug("Token Sendmail error: " + str(e))
def send_txt(self, name, price, percent, status): if 'up' == status: content = '%s > %.2f , %.2f' % (name, price, percent) if 'down' == status: content = '%s < %.2f , %.2f' % (name, price, percent) content = content + '%' print(content) subject = '%s' % name self.msg = MIMEText(content, 'plain', 'utf-8') self.msg['to'] = self.to_mail self.msg['from'] = self.from_mail self.msg['Subject'] = subject self.msg['Date'] = Utils.formatdate(localtime=1) try: self.smtp = smtplib.SMTP_SSL(port=465) self.smtp.connect(self.server) self.smtp.login(self.username, self.password) self.smtp.sendmail(self.msg['from'], self.msg['to'], self.msg.as_string()) self.smtp.quit() print("sent") except smtplib.SMTPException as e: print(e) return 0
def mail_recipient(recipient_name, recipient_email, subject, body, headers=None): mail_from = config.get('openspending.mail_from', '*****@*****.**') body = add_msg_niceties(recipient_name, body, app_globals.site_title) msg = MIMEText(body.encode('utf-8'), 'plain', 'utf-8') if headers: msg.update(headers) subject = Header(subject.encode('utf-8'), 'utf-8') msg['Subject'] = subject msg['From'] = _("%s <%s>") % (app_globals.site_title, mail_from) recipient = u"%s <%s>" % (recipient_name, recipient_email) msg['To'] = Header(recipient, 'utf-8') msg['Date'] = Utils.formatdate(time()) msg['X-Mailer'] = "OpenSpending" try: server = smtplib.SMTP(config.get('smtp_server', 'localhost')) server.sendmail(mail_from, [recipient_email], msg.as_string()) server.quit() except Exception as e: msg = '%r' % e log.exception(msg) raise MailerException(msg)
def send_mail(from_user, pwd, to_user, cc_users, subject, text, attach): COMMASPACE = ", " msg = MIMEMultipart("alternative") #msg = MIMEMultipart() msg["From"] = from_user msg["To"] = to_user msg["Cc"] = COMMASPACE.join(cc_users) msg["Subject"] = Header(s=subject, charset="utf-8") msg["Date"] = Utils.formatdate(localtime = 1) msg.attach(MIMEText(text, "html", _charset="utf-8")) if (attach != None): part = MIMEBase("application", "octet-stream") part.set_payload(open(attach, "rb").read()) Encoders.encode_base64(part) part.add_header("Content-Disposition", "attachment; filename=\"%s\"" % os.path.basename(attach)) msg.attach(part) smtp_server = "smtp.gmail.com" port = 587 smtp = smtplib.SMTP(smtp_server, port) smtp.starttls() smtp.login(from_user, pwd) print "gmail login OK!" smtp.sendmail(from_user, cc_users, msg.as_string()) print "mail Send OK!" smtp.close()
def SendToKindle(filename): filename = filename + ".txt" server = 'smtp.163.com' username = "******" password = '******' from_mail = '*****@*****.**' to_mail = '*****@*****.**' smtp = smtplib.SMTP() smtp.connect(server) smtp.login(username, password) msg = MIMEMultipart() msg['to'] = to_mail msg['from'] = from_mail msg['Subject'] = "Convert" msg['Date'] = Utils.formatdate(localtime=1) content = open(filename, 'rb').read() att = MIMEText(content, 'base64', 'utf-8') att['Content-Type'] = 'application/octet-stream' att["Content-Disposition"] = "attachment;filename=\"%s\"" % Header( filename, 'gb2312') msg.attach(att) smtp.sendmail(msg['from'], msg['to'], msg.as_string()) smtp.quit()
def _mail_recipient(recipient_name, recipient_email, sender_name, sender_url, subject, body, headers={}): mail_from = config.get('ckan.mail_from') body = add_msg_niceties(recipient_name, body, sender_name, sender_url) msg = MIMEText(body.encode('utf-8'), 'plain', 'utf-8') for k, v in headers.items(): msg[k] = v subject = Header(subject.encode('utf-8'), 'utf-8') msg['Subject'] = subject msg['From'] = _("%s <%s>") % (sender_name, mail_from) recipient = u"%s <%s>" % (recipient_name, recipient_email) msg['To'] = Header(recipient, 'utf-8') msg['Date'] = Utils.formatdate(time()) msg['X-Mailer'] = "CKAN %s" % __version__ try: server = smtplib.SMTP( config.get('test_smtp_server', config.get('smtp_server', 'localhost'))) #server.set_debuglevel(1) server.sendmail(mail_from, [recipient_email], msg.as_string()) server.quit() except Exception, e: msg = '%r' % e log.exception(msg) raise MailerException(msg)
def SendMail(self, subject, text): COMMASPACE = ", " from_user = '******' to_user = COMMASPACE.join(MAIL_ID_LIST) # cc_users = '*****@*****.**' cc_users = '*****@*****.**' # sender = 'ivms' attach = '' msg = MIMEMultipart("alternative") msg["From"] = from_user # msg['From'] = '=?euc-kr?B?' + base64.standard_b64encode(sender) + '?=' + '<' + from_user + '>' msg["To"] = to_user # msg["Cc"] = cc_users msg["Subject"] = Header(s=subject, charset="euc-kr") # msg["Subject"] = '=?euc-kr?B?' + base64.standard_b64encode(subject) + '?=' msg["Date"] = Utils.formatdate(localtime = 1) # msg.attach(MIMEText(text, _subtype='html', _charset='euc-kr')) msg.attach(MIMEText(text, _charset='euc-kr')) # if (attach != None): # part = MIMEBase("application", "octet-stream") # part.set_payload(open(attach, "rb").read()) # Encoders.encode_base64(part) # part.add_header("Content-Disposition", "attachment; filename=\"%s\"" % os.path.basename(attach)) # msg.attach(part) smtp = smtplib.SMTP(smtp_server, port) smtp.login(userid, passwd) # smtp.sendmail(from_user, cc_users, msg.as_string()) smtp.sendmail(from_user, MAIL_ID_LIST, msg.as_string()) smtp.close()
def send_manga_throw_email(self, title, number): """ This function sends an email using Gmail SMTP Server to the kindle cloud with the comic attached into it. Keyword arguments: title - The title of the manga number - The chapter number of the manga """ msg = MIMEMultipart.MIMEMultipart() msg['from'] = "*****@*****.**" msg['To'] = "*****@*****.**" msg['Date'] = Utils.formatdate(localtime=True) msg['Subject'] = '' msg.attach(MIMEText.MIMEText('')) part = MIMEBase.MIMEBase('application', "octet-stream") filename = title + "_" + str(number) + ".mobi" part.set_payload(open(filename, "rb").read()) Encoders.encode_base64(part) part.add_header('Content-Disposition', 'attachment', filename=filename) msg.attach(part) smtp = smtplib.SMTP("smtp.gmail.com", 587) smtp.ehlo() smtp.starttls() smtp.login("*****@*****.**", "xxxpasswordxxx") smtp.sendmail("*****@*****.**", "*****@*****.**", msg.as_string()) smtp.close()
def send_txt(self, name, real_price,price, percent, status): if 'up' == status: # content = 'stock name:%s current price: %.2f higher than price up:%.2f , ratio:%.2f' % (name, real_price,price, percent) content = '证券名称:%s 当前价格: %.2f 高于 定价模型上限价格:%.2f , 可卖出 预计盈利率:%.2f' %(name, real_price,price, percent+15) if 'down' == status: # content = 'stock name:%s current price: %.2f lower than price down:%.2f , 盈利率:%.2f' % (name, real_price,price, percent) content = '证券名称:%s 当前价格: %.2f 低于 定价模型下限价格:%.2f , 可买入 预计盈利率:%.2f' %(name, real_price,price, percent+15) content = content + '%' print content subject = '%s' % name self.msg = MIMEText(content, 'plain', 'utf-8') self.msg['to'] = self.to_mail self.msg['from'] = self.from_mail self.msg['Subject'] = subject self.msg['Date'] = Utils.formatdate(localtime=1) try: self.smtp = smtplib.SMTP_SSL(port=465) self.smtp.connect(self.server) self.smtp.login(self.username, self.password) self.smtp.sendmail(self.msg['from'], self.msg['to'], self.msg.as_string()) self.smtp.quit() print "sent" except smtplib.SMTPException, e: print e return 0
def __SetBySmtp(self): if len(self.__charset) == 0: raise Exception(-1, "empty Character Set of SendMail") COMMASPACE = ", " msg = MIMEMultipart("alternative") msg["From"] = self.__str_from msg["To"] = COMMASPACE.join(self.__list_to) msg["Subject"] = Header(s=self.__str_title, charset=self.__charset) msg["Date"] = Utils.formatdate(localtime=1) msg.attach(MIMEText(self.__str_text, "html", _charset=self.__charset)) if len(self.__list_file) > 0: for target in self.__list_file: part = MIMEBase("application", "octet-stream") part.set_payload(open(target, "rb").read()) Encoders.encode_base64(part) # RFC 2047 방식을 이용한 한글파일명 파일전송 file_target = '=?utf-8?b?' + base64.b64encode( os.path.basename(target)) + '?=' part.add_header("Content-Disposition", "attachment; filename=\"%s\"" % file_target) msg.attach(part) # RFC 2231 방식. 추후개발.(현재 오류있음) ''' file_target = "UTF-8''\""+urllib.quote(os.path.basename(target))+"\"" #part.add_header("Content-Transfer-Encoding", "base64") part.add_header("Content-Disposition", "attachment; filename*=%s" % file_target) msg.attach(part) ''' return msg
def send_mail(from_user, to_user, cc_users, subject, text, attach): COMMASPACE = ", " msg = MIMEMultipart("alternative") msg["From"] = from_user msg["To"] = to_user msg["Cc"] = COMMASPACE.join(cc_users) msg["Subject"] = Header(s=subject, charset="utf-8") msg["Date"] = Utils.formatdate(localtime=1) msg.attach(MIMEText(text, "html", _charset="utf-8")) if (attach != None): part = MIMEBase("application", "octet-stream") part.set_payload(open(attach, "rb").read()) Encoders.encode_base64(part) part.add_header( "Content-Disposition", "attachment; filename=\"%s\"" % os.path.basename(attach)) msg.attach(part) smtp = smtplib.SMTP(smtp_server, port) smtp.ehlo() smtp.starttls() smtp.login(userid, passwd) smtp.sendmail(from_user, to_user, msg.as_string()) smtp.close()
def reauthor(dataset, author_mail, msg, context): """ notify author that dataset should be revised """ body = u""" Dear Author, the Editors of '{journal}' have requested that you revise the replication files named '{title}' which you submitted to the ZBW--Journal Data Archive. URL: {url} {message} """ def create_message(): if msg: return u"Message: \n========\n\n{}".format(msg) return u"" pkg = tk.get_action('package_show')(context, {'id': dataset}) org_id = pkg.get('owner_org', pkg.get('group_id', False)) org = tk.get_action('organization_show')(context, {'id': org_id}) d = {'journal': org['title'], 'url': package_url(dataset), 'title': pkg.get('name'), 'message': create_message()} body = body.format(**d) message = MIMEText(body.encode('utf-8'), 'plain', 'utf-8') message['Subject'] = Header(u"ZBW Journal Data Archive: Please revise your uploaded dataset") message['From'] = config.get('smtp.mail_from') message['To'] = Header(author_mail, 'utf-8') message['Date'] = Utils.formatdate(time()) message['X-Mailer'] = "CKAN {} [Plugin edawax]".format(ckan_version) return sendmail(author_mail, message) # boolean
def send_email(self, subject, content, attachment): # Create a root container main_msg = MIMEMultipart('alternative') # Create a text container to show the contents of the email text_msg = MIMEText(content, 'plain', 'utf-8') # Attach the contents main_msg.attach(text_msg) contype = 'application/octet-stream' maintype, subtype = contype.split('/', 1) # Create attachment att = open(attachment, 'rb') att_msg = MIMEBase(maintype, subtype) # Read the contents of the attachment and format it att_msg.set_payload(att.read()) att.close() encoders.encode_base64(att_msg) # Add the header for attachment att_msg.add_header('Content-Disposition', 'attachment', filename=attachment.split('\\')[-1]) main_msg.attach(att_msg) # Set the attibutes for the root container main_msg['Subject'] = subject main_msg['From'] = self.mail_from main_msg['To'] = ','.join(self.mail_to) main_msg['Cc'] = ','.join(self.mail_cc) main_msg['Date'] = Utils.formatdate() server = smtplib.SMTP() server.connect(self.mail_host) server.sendmail(self.mail_from, self.mail_to + self.mail_cc, main_msg.as_string()) server.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 _mail_recipient(recipient_name, recipient_email, sender_name, sender_url, subject, body, headers={}): mail_from = config.get('smtp.mail_from') body = add_msg_niceties(recipient_name, body, sender_name, sender_url) msg = MIMEText(body.encode('utf-8'), 'plain', 'utf-8') for k, v in headers.items(): msg[k] = v subject = Header(subject.encode('utf-8'), 'utf-8') msg['Subject'] = subject msg['From'] = _("%s <%s>") % (sender_name, mail_from) recipient = u"%s <%s>" % (recipient_name, recipient_email) msg['To'] = Header(recipient, 'utf-8') msg['Date'] = Utils.formatdate(time()) msg['X-Mailer'] = "CKAN %s" % ckan.__version__ # Send the email using Python's smtplib. smtp_connection = smtplib.SMTP() if 'smtp.test_server' in config: # If 'smtp.test_server' is configured we assume we're running tests, # and don't use the smtp.server, starttls, user, password etc. options. smtp_server = config['smtp.test_server'] smtp_starttls = False smtp_user = None smtp_password = None else: smtp_server = config.get('smtp.server', 'localhost') smtp_starttls = paste.deploy.converters.asbool( config.get('smtp.starttls')) smtp_user = config.get('smtp.user') smtp_password = config.get('smtp.password') smtp_connection.connect(smtp_server) try: #smtp_connection.set_debuglevel(True) # Identify ourselves and prompt the server for supported features. smtp_connection.ehlo() # If 'smtp.starttls' is on in CKAN config, try to put the SMTP # connection into TLS mode. if smtp_starttls: if smtp_connection.has_extn('STARTTLS'): smtp_connection.starttls() # Re-identify ourselves over TLS connection. smtp_connection.ehlo() else: raise MailerException("SMTP server does not support STARTTLS") # If 'smtp.user' is in CKAN config, try to login to SMTP server. if smtp_user: assert smtp_password, ("If smtp.user is configured then " "smtp.password must be configured as well.") smtp_connection.login(smtp_user, smtp_password) smtp_connection.sendmail(mail_from, [recipient_email], msg.as_string()) log.info("Sent email to {0}".format(recipient_email)) except smtplib.SMTPException, e: msg = '%r' % e log.exception(msg) raise MailerException(msg)
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 _mail_recipient(recipient_name, recipient_email, sender_name, sender_url, subject, body, headers={}): mail_from = config.get('smtp.mail_from') body = add_msg_niceties(recipient_name, body, sender_name, sender_url) msg = MIMEText(body.encode('utf-8'), 'plain', 'utf-8') for k, v in headers.items(): msg[k] = v subject = Header(subject.encode('utf-8'), 'utf-8') msg['Subject'] = subject msg['From'] = _("%s <%s>") % (sender_name, mail_from) recipient = u"%s <%s>" % (recipient_name, recipient_email) msg['To'] = Header(recipient, 'utf-8') msg['Date'] = Utils.formatdate(time()) msg['X-Mailer'] = "CKAN %s" % __version__ # Send the email using Python's smtplib. smtp_connection = smtplib.SMTP() if 'smtp.test_server' in config: # If 'smtp.test_server' is configured we assume we're running tests, # and don't use the smtp.server, starttls, user, password etc. options. smtp_server = config['smtp.test_server'] smtp_starttls = False smtp_user = None smtp_password = None else: smtp_server = config.get('smtp.server', 'localhost') smtp_starttls = paste.deploy.converters.asbool( config.get('smtp.starttls')) smtp_user = config.get('smtp.user') smtp_password = config.get('smtp.password') smtp_connection.connect(smtp_server) try: #smtp_connection.set_debuglevel(True) # Identify ourselves and prompt the server for supported features. smtp_connection.ehlo() # If 'smtp.starttls' is on in CKAN config, try to put the SMTP # connection into TLS mode. if smtp_starttls: if smtp_connection.has_extn('STARTTLS'): smtp_connection.starttls() # Re-identify ourselves over TLS connection. smtp_connection.ehlo() else: raise MailerException("SMTP server does not support STARTTLS") # If 'smtp.user' is in CKAN config, try to login to SMTP server. if smtp_user: assert smtp_password, ("If smtp.user is configured then " "smtp.password must be configured as well.") smtp_connection.login(smtp_user, smtp_password) smtp_connection.sendmail(mail_from, [recipient_email], msg.as_string()) log.info("Sent email to {0}".format(recipient_email)) except smtplib.SMTPException, e: msg = '%r' % e log.exception(msg) raise MailerException(msg)
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 __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 insertResentHeaders(i): m._headers.insert(i, ('resent-from', MH.Header( fromAddress.address).encode())) m._headers.insert(i, ('resent-to', MH.Header( mimeutil.flattenEmailAddresses(toAddresses)).encode())) m._headers.insert(i, ('resent-date', EU.formatdate())) m._headers.insert(i, ('resent-message-id', smtp.messageid('divmod.xquotient')))
def timehandler(rawtime): timeinput = re.split('[\s:-]', rawtime) timeinput.insert(2, year) t1 = ' '.join(timeinput) timeobject = time.strptime(t1, "%d %b %Y %H %M") unixtime = time.mktime(timeobject) date = Utils.formatdate(unixtime) return unixtime, date
def dateTimeToRFC2882Date(dt): """Converts a C{datetime} object to a RFC2882 Date String @param dateTime: a C{datetime} instance @type dateTime: C{datetime} @return: RFC2882 Date String """ ticks = mktime(dt.timetuple()) return Utils.formatdate(ticks, True)
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 test_formatdate_localtime(self): now = 1005327232.109884 ldate = Utils.formatdate(now, localtime=1) zone = ldate.split()[5] offset = int(zone[1:3]) * 3600 + int(zone[-2:]) * 60 # Remember offset is in seconds west of UTC, but the timezone is in # minutes east of UTC, so the signs differ. if zone[0] == '+': offset = -offset if time.daylight and time.localtime(now)[-1]: toff = time.altzone else: toff = time.timezone self.assertEqual(offset, toff)
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 test_formatdate(self): now = 1005327232.109884 gm_epoch = time.gmtime(0)[0:3] loc_epoch = time.localtime(0)[0:3] # When does the epoch start? if gm_epoch == (1970, 1, 1): # traditional Unix epoch matchdate = 'Fri, 09 Nov 2001 17:33:52 -0000' elif loc_epoch == (1904, 1, 1): # Mac epoch matchdate = 'Sat, 09 Nov 1935 16:33:52 -0000' else: matchdate = "I don't understand your epoch" gdate = Utils.formatdate(now) self.assertEqual(gdate, matchdate)
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 getBasicHeaders(self): """ Returns the basic headers :return: The headers :rtype: ``dict`` """ from email import Utils, Header from svnmailer import version return { 'X-Mailer': Header.Header( ("svnmailer-%s" % version.string).decode('utf-8'), 'iso-8859-1' ), 'Date': Utils.formatdate(), }
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 send(self, mail): if mail.text is "": return False server = smtplib.SMTP_SSL(mail.server, mail.port) server.login(self.__username, self.__mail_authorization_code) # 仅smtp服务器需要验证时 # 构造MIMEMultipart对象做为邮件主体 body_mail = MIMEMultipart() # 构造显示内容并添加到邮件主体 text_mail = None if mail.mode == 0: text_mail = MIMEText(mail.text, _charset="utf-8") elif mail.mode == 1: text_mail = MIMEText(mail.file_path.decode("gbk") + "\r\n\r\n\r\n" + mail.text, _charset="utf-8") else: # 构造附件并添加到邮件主体 text_mail = MIMEText(mail.text, _charset="utf-8") file_mail = MIMEText(open(mail.file_path, 'rb').read(), 'base64', 'utf-8') file_mail["Content-Type"] = 'application/x-zip-compressed' basename = os.path.basename(mail.file_path) file_mail["Content-Disposition"] = 'attachment; filename=' + basename body_mail.attach(file_mail) body_mail.attach(text_mail) # 设置邮件主体属性 body_mail['From'] = mail.Special_Form body_mail['To'] = mail.Special_To body_mail['Reply-to'] = mail.Special_Reply body_mail['Subject'] = mail.subject body_mail['Date'] = Utils.formatdate() # 得到格式化后的完整文本 full_text = body_mail.as_string() # 用smtp发送邮件 try: server.sendmail(self.__username, mail.to_user, full_text) return True except smtplib.SMTPDataError: return False finally: server.quit()
def sendmail(self,subject,content,temail,femail=DEFAULT_FEMAIL,priority=DEFAULT_PRIORITY): # log.debug("Get mail task : %s for %s" % (subject,self.module)) if len(str(subject))*len(content)*len(temail) == 0: return False,'illegal argument!' mime = MIMEText(content,'html', 'utf-8') mime['To'] = ", ".join(temail) mime['From'] = femail mime['Subject'] = Header.Header(subject,'utf-8') mime['X-Priority'] = priority mime['Date'] = Utils.formatdate(localtime = 1) try: s = smtplib.SMTP(EMAIL_SERVER) s.sendmail(femail, temail, mime.as_string()) # log.info("Mail task:%s %s :%s" % (self.module,subject,temail)) return True,'' except smtplib.SMTPException, se: return False,se
def send_txt(self,filename): self.smtp=smtplib.SMTP() self.smtp.connect(self.server) self.smtp.login(self.username,self.password) self.msg=MIMEMultipart() self.msg['to']=self.to_mail self.msg['from'] =self.from_mail self.msg['Subject']="Convert" self.filename=filename+ ".txt" self.msg['Date']=Utils.formatdate(localtime = 1) content=open(self.filename.decode('utf-8'),'rb').read() print content self.att=MIMEText(content,'base64','utf-8') self.att['Content-Type']='application/octet-stream' #self.att["Content-Disposition"] = "attachment;filename="%s"" %(self.filename.encode('gb2312')) self.att["Content-Disposition"] = "attachment;filename=""%s" % Header(self.filename,'gb2312') print self.att["Content-Disposition"] self.msg.attach(self.att)