def test_mail_encoding_is_used_as_fallback(self): interface.config['mail.encoding'] = 'ISO-8859-1' message = Message('*****@*****.**', '*****@*****.**', 'Test') message.plain = 'Hello world!' msg = email.message_from_string(str(message)) self.assertEqual('text/plain; charset="iso-8859-1"', msg['Content-Type']) self.assertEqual('quoted-printable', msg['Content-Transfer-Encoding'])
def send_mail(subject='', to=[], cc=[], bcc=[], template='', lang='zh', values={}, ip=ip, ): interface.start(email_config) msg = Message(sender_address, to, subject, cc=cc, bcc=bcc, plain=subject if template else 'Plain Text', ) if template: try: url_root = request.url_root except: url_root = 'http://{}'.format(ip) if 'http://localhost' in url_root: url_root = 'http://{}'.format(ip) msg.rich = render_template('notifications/{}'.format(template), lang=lang, url_root=url_root, **values ) msg.send() interface.stop()
def test_message_instantiation_with_positional_parameters(self): message = Message('*****@*****.**', '*****@*****.**', 'Test') message.plain = 'Hello world!' msg_string = str(message) self.failUnless('From: [email protected]' in msg_string) self.failUnless('To: [email protected]' in msg_string) self.failUnless('Subject: Test' in msg_string)
def test_use_deprecated_recipient(self): message = Message(recipient='*****@*****.**') self.assertEqual('*****@*****.**', str(message.to)) self.assertEqual(message.recipient, message.to) message.recipient = '*****@*****.**' self.assertEqual('*****@*****.**', str(message.to)) self.assertEqual(message.recipient, message.to)
def test_use_deprecated_smtp_from(self): message = Message(smtpfrom='*****@*****.**') self.assertEqual('*****@*****.**', str(message.smtp_from)) self.assertEqual(message.smtpfrom, message.smtp_from) message.smtpfrom = '*****@*****.**' self.assertEqual('*****@*****.**', str(message.smtp_from)) self.assertEqual(message.smtpfrom, message.smtp_from)
def submit(self): ''' This function validates the submitted registration form and creates a new user. Restricted to ``POST`` requests. If successful, redirects to the result action to prevent resubmission. ''' user = User( self.form_result['username'], self.form_result['password'], email=self.form_result['email'], first_area_id=self.form_result['first_area'], first_area_level=self.form_result['first_area_level'], second_area_id=self.form_result['second_area'], second_area_level=self.form_result['second_area_level'] ) Session.add(user) Session.commit() msg = Message("*****@*****.**", self.form_result['email'], "InPhO registration") msg.plain = """%s, thank you for registering with the Indiana Philosophy Ontology Project (InPhO). You can access your """ % self.form_result['username'] msg.send() h.redirect(h.url(controller='account', action='result'))
def submit(self): ''' This function validates the submitted registration form and creates a new user. Restricted to ``POST`` requests. If successful, redirects to the result action to prevent resubmission. ''' user = User(self.form_result['username'], self.form_result['password'], email=self.form_result['email'], first_area_id=self.form_result['first_area'], first_area_level=self.form_result['first_area_level'], second_area_id=self.form_result['second_area'], second_area_level=self.form_result['second_area_level']) Session.add(user) Session.commit() msg = Message("*****@*****.**", self.form_result['email'], "InPhO registration") msg.plain = """%s, thank you for registering with the Indiana Philosophy Ontology Project (InPhO). You can access your """ % self.form_result[ 'username'] msg.send() h.redirect(h.url(controller='account', action='result'))
def test_use_deprecated_reply_to(self): message = Message(replyto='*****@*****.**') self.assertEqual('*****@*****.**', str(message.reply_to)) self.assertEqual(message.replyto, message.reply_to) message.replyto = '*****@*****.**' self.assertEqual('*****@*****.**', str(message.reply_to)) self.assertEqual(message.replyto, message.reply_to)
def send_email(sender, truename, emails, title, plain, rich): """ notify using email sending alert email to followers """ """ rand send email """ day_str = datetime.datetime.strftime(datetime.datetime.today(), "%d%H") sender = "Knowing <*****@*****.**>" % day_str logging.debug("Send email %s" % ", ".join((truename, str(emails), title, plain, rich))) try: mail = Message() mail.subject = title mail.sender = sender mail.to = u"%s <%s>" % (truename, emails[0]) if len(emails) > 1: mail.cc = u",".join(emails[1:]) mail.encoding = "utf-8" mail.plain = plain mail.rich = rich mail.send() except Exception, e: logging.exception("Fail to send email.")
def _reset(self, username=None): username = username or request.environ.get('REMOTE_USER', False) if not username: abort(401) try: user = h.get_user(username) except: abort(400) new_password = user.reset_password() msg = Message("*****@*****.**", user.email, "InPhO password reset") msg.plain = """ %(name)s, your password at the Indiana Philosophy Ontology (InPhO) has been changed to: Username: %(uname)s Password: %(passwd)s The Indiana Philosophy Ontology (InPhO) Team [email protected] """ % {'passwd' : new_password, 'uname' : user.username, 'name' : user.fullname or user.username or ''} msg.send() Session.commit() h.redirect(h.url(controller='account', action='reset_result'))
def request_enable(self, id=None): if id is None: abort(404) user = h.get_object_or_404(User, id=id) admins = User.query.filter_by(superuser=True).all() app_name = config['application_name'] from_addr = config['error_email_from'] suffix = config['email_suffix'] subject = "New user request for "+app_name requested_courses = request.params["requested_course_name"] user.requested_courses = requested_courses if not request.environ.has_key('REMOTE_ADDR'): request.environ['REMOTE_ADDR'] = "127.0.0.1" #must be debugging locally on paste ip = request.environ['REMOTE_ADDR'] for admin in admins: to_addr = admin.name + "@" + suffix body = "Dear "+admin.name+",\n\nA new user has requested an account on "+app_name+".\n\nDetails:\n\n" body += "username: "******"\n" body += "requested course(s): "+requested_courses+"\n" body += "timestamp: "+str(datetime.datetime.today())+"\n" body += "remote ip: "+ip+"\n\n\n" body += "Please login to https://comoto.cs.illinois.edu to approve or deny this request\n\n" body += "Thanks\n\n" body += "The "+app_name+" Team\n\n\n\n" body += "Please do not reply to this message, as this account is not monitored" message = Message(from_addr, to_addr, subject) message.plain = body message.send() session['flash'] = "Request Acknowledged" session.save() Session.commit() redirect_to(controller="login", action="index", id=None)
def email_test(self): from turbomail import Message msg = Message('*****@*****.**', '*****@*****.**', 'Subject') msg.plain = "Foo Bar" try: msg.send() # Message will be sent through the configured manager/transport. except Exception, err: print err
def test_message_instantiation_with_tuples(self): message = Message(('Foo Bar', '*****@*****.**'), ('To', '*****@*****.**'), 'Test') message.plain = 'Hello world!' msg_string = str(message) self.failUnless('From: Foo Bar <*****@*****.**>' in msg_string) self.failUnless('To: To <*****@*****.**>' in msg_string) self.failUnless('Subject: Test' in msg_string)
def test_message_instantiation_with_keyword_parameters(self): message = Message(sender='*****@*****.**', recipient='*****@*****.**', subject='Test') message.plain = 'Hello world!' msg_string = str(message) self.failUnless('From: [email protected]' in msg_string) self.failUnless('To: [email protected]' in msg_string) self.failUnless('Subject: Test' in msg_string)
def on_success(cls, request, values): g = request.globals config = g.getMailConfig() interface.start(config) msg = Message(config['mail.smtp.username'], g.mailRecipient, "Contact", encoding ='utf-8') msg.plain = u'\n\n'.join( map(lambda s: s.format(**values), [u'First Name: {name}', u'Email: {email}', u'Message: {message}']) ) msg.send() interface.stop(force=True) return {'success':True, 'redirect':request.fwd_url('website_home')}
def test_message_enqueue(self): config = {'mail.on': True} fake_setuptools = {'immediate': ImmediateManager, 'debug': DebugTransportFactory} interface.start(config, extra_classes=fake_setuptools) message = Message('*****@*****.**', '*****@*****.**', 'Test') message.plain = 'Hello world!' turbomail.enqueue(message)
def do_email_students(self): log.debug(str(request.params)) user = h.get_user(request.environ) student_ids_str = request.params['student_ids'] student_ids = ah.fileset_id_string_to_id_list(student_ids_str) students = Student.query.filter(Student.id.in_(student_ids)).all() students = filter(lambda student: request.params.has_key(str(student.id)), students) for student in students: check_student_access(student) subject = request.params['subject'] body = request.params['body'] from_addr = (user.givenName+" "+user.surName,user.name + '@illinois.edu') reply_to = user.name + '@illinois.edu' to_addrs = map(lambda student: (student.displayName, student.netid + "@illinois.edu"), students) from turbomail import Message message = Message() message.subject = subject message.plain = body message.author = from_addr message.reply_to = reply_to message.to = to_addrs message.cc = from_addr message.send() if request.params.has_key('assignment_id'): return redirect_to(controller='view_analysis', action='view', id=request.params['assignment_id']) else: return redirect_to(controller='view_analysis', action='list')
def test_use_sender_for_author_if_no_author_given(self): message = Message(sender='*****@*****.**', to='*****@*****.**', subject='Test') self.assertEqual('*****@*****.**', str(message.sender)) message.plain = 'Hello world!' msg_string = str(message) self.failUnless('From: [email protected]' in msg_string) self.failUnless('To: [email protected]' in msg_string) self.failUnless('Subject: Test' in msg_string) self.failIf('Sender: ' in msg_string) self.assertEqual('*****@*****.**', str(message.sender))
def __notify(chart, message): """ notify using email chart: Charts data row message: message body sending alert email to owner and followers """ config = __get_config('webapp') mail_config = {} mail_config['mail.on'] = config['turbomail']['enable'] mail_config['mail.manager'] = config['turbomail']['manager'] mail_config['mail.transport'] = config['turbomail']['transport'] mail_config['mail.smtp.server'] = config['turbomail']['server'] sender = config['turbomail']['sender'] """ rand send email """ day_str = datetime.datetime.strftime(datetime.datetime.today(),"%d%H") sender = 'Knowing <*****@*****.**>' % day_str subject = message u = session.query(Users).filter(Users.username == chart.owner) addressee = '' if u: for i in u: if i.mobile: addressee = i.mobile + '@139.com' else: logger.warning("no mobile set for user \"%s\"" % i.username) return interface.start(mail_config) now = str(datetime.datetime.now())[0:19] chart_url = 'http://knowing.corp.anjuke.com/chart/%d' % chart.id html_part = u"<html><body><h1>Look, %s</h1><p>时间: %s</p><p>详细信息: %s</p><p><a href='%s'>%s</a></p><p>This mail is sent by Knowing</p></body></html>" html_part %= (chart.name, now, message, chart_url, chart_url) text_part = u"[critical] 时间: %s 详细信息: %s" text_part %= (now, message) mail = Message(sender, addressee, subject) mail.encoding = 'utf-8' mail.plain = message mail.rich = html_part flag = mail.send()
def test_message_properties(self): message = Message('*****@*****.**', '*****@*****.**', 'Test') message.plain = 'Hello world!' property_names = ['bcc', 'cc', 'date', 'disposition', 'encoding', 'headers', 'organization', 'plain', 'priority', 'recipient', 'replyto', 'rich', 'sender', 'smtpfrom', 'subject'] for name in property_names: getattr(message, name) args = dict(zip(property_names, ['*****@*****.**'] * len(property_names))) Message(**args)
def new(self): user = None if "repoze.who.identity" in request.environ: user = request.environ.get('repoze.who.identity')['user'] values= dict(request.params) for email in session['site_settings']['contactusmail'].split(','): if user: message = Message(user.emails[0].email_address, email, "contactus from %s"%values['email'], encoding='utf-8') message.plain = "%s"%values['message'] message.send() else: message = Message(values['email'], email, "contactus asked to reply to %s"%values['email'], encoding='utf-8') message.plain = "%s"%values['message'] message.send() h.flash(_("Your message was sent successfully.")) return redirect(h.url(controller='contactus',action='index'))
def mail_user_error(self, user): app_name = config['application_name'] from_addr = config['error_email_from'] suffix = config['email_suffix'] to_addr = user.name + "@" + suffix subject = app_name+" static moss analysis graph generation failed" body = "Dear "+user.name+",\n\nThe static moss analysis graph that you requested is failed to generate.\n\n" body += "The "+app_name+" developers have been informed of this error and will correct it as soon as possible.\n\n" body += "Thanks\n\n" body += "The "+app_name+" Team\n\n\n\n" body += "Please do not reply to this message, as this account is not monitored" message = Message(from_addr, to_addr, subject) message.plain = body message.send()
def forgotaction(self): values = dict(request.params) del values["action"] msg = "" settingsf = file(config["settings_file"], "rb") session["site_settings"] = pickle.load(settingsf) settingsf.close() session.save() captchres = h.captcha.submit( values["recaptcha_challenge_field"], values["recaptcha_response_field"], "6LepGccSAAAAAMfzDtmvyRjJ7-A1FWuJa5qUTxX2", session["site_settings"]["ip_address"], ) if not captchres.is_valid: c.menu_items = h.top_menu(self.menu_items, _("Customers")) html = render("/derived/user/forgot.html") return htmlfill.render(html, values, errors={"captcha": _("Invalid Captcha try again")}) user = Session.query(User).join(User.emails).filter(Email.email_address == values["email"]).one() confcode = str(uuid.uuid1()) uconf = UserConfirm(user, confcode) Session.add(uconf) Session.commit() message = Message( session["site_settings"]["forgotpass"], user.emails[0].email_address, _("Kazhal trading Reset password"), encoding="utf-8", ) msg += _("If you requested a password reset click the below link\n") ##msg += "%s%s"%(request.application_url,h.url(controller='user',action='resetpassEmail',id=user.id,confcode=confcode)) msg += "%s%s" % ( request.application_url, url(controller="user", action="resetpassEmail", id=user.id, confcode=confcode), ) c.contents = msg msgHtml = render(_("/derived/emails/forgotpass.html")) message.rich = msgHtml message.plain = msg message.send() h.flash( _( "An email has been sent to your address.To reset your password check your email and click on the confirm link." ) ) return redirect(url(controller="user", action="forgot"))
def send_mail(sender, to, subject, body): if sender and to and subject and body: message = Message(author=sender, to=to, subject=subject) message.rich = body # TODO: convert mail body to plain message.plain = 'This mail should be viewed in HTML.' try: message.send() except Exception, msg: if str(msg) == '[Errno 111] Connection refused': # caused by connection problem to smtp server pass else: # other error, raise raise Exception
def send_user_enabled_email(user): from turbomail import Message #send mail to user to notify them app_name = config['application_name'] from_addr = config['error_email_from'] suffix = config['email_suffix'] to_addr = user.name + "@" + suffix subject = app_name+" user account request approved" body = "Dear "+user.name+",\n\nYour request for an account on "+app_name+" has been approved.\n\n" body += "You can now login to https://comoto.cs.illinois.edu to begin using the application.\n\n" body += "Thanks\n\n" body += "The "+app_name+" Team\n\n\n\n" body += "Please do not reply to this message, as this account is not monitored" message = Message(from_addr, to_addr, subject) message.plain = body message.send()
def mail_user(self,graph): app_name = config['application_name'] from_addr = config['error_email_from'] suffix = config['email_suffix'] to_addr = graph.requestingUser.name + "@" + suffix subject = app_name+" static moss analysis graph generation complete" body = "Dear "+graph.requestingUser.name+",\n\nThe static moss analysis graph that you requested is now complete and ready for viewing.\n\n" body += "Assignment: "+str(graph.assignment.course.name)+ " " + str(graph.assignment.name)+"\n\n" body += "Details: "+graph.to_str()+"\n\n" body += "You can now login to "+app_name+" to view your graph on the view analysis page where you requested it.\n\n" body += "Thanks\n\n" body += "The "+app_name+" Team\n\n\n\n" body += "Please do not reply to this message, as this account is not monitored" message = Message(from_addr, to_addr, subject) message.plain = body message.send()
def feedback(self): user = h.get_user(request.environ) from_addr = config['error_email_from'] suffix = config['email_suffix'] to_addr = "*****@*****.**" subject = "CoMoTo feedback from "+user.name body = request.params['feedback'] body += "\n\n" body += "revision reporting problem: "+c.revision if body is not None: message = Message(from_addr, to_addr, subject) message.plain = body message.send() session['flash'] = "Feedback Sent" session.save() redirect_to(controller='about', action='comoto')
def feedback(self): try: vars = self.request.json_body sanitized_description = bleach.clean(vars['description']) html_body = u"<h3>L\'utilisateur <a href=\"mailto:{0}\">{0}</a> " \ u"a remarqué le problème suivant:</h3><p>{1}</p>" \ u"<p><a href=\"{3}\">Ouvrir le lien vers la carte</a></p>" \ u"<h3>La couche suivante est concernée:</h3>" \ u"<p>{2}</p>" \ .format(vars['email'], sanitized_description, vars['layer'], vars['url'] ) support_email = self.config.get('feedback.support_email', '*****@*****.**') message = Message(author=vars['email'], to=support_email, subject=u'Un utilisateur a signalé un problème') message.plain = html_body message.rich = html_body message.encoding = 'utf-8' message.send() except Exception as e: log.exception(e) return HTTPNotFound() return {'success': True}
class TestDebugTransportStoresAllMail(unittest.TestCase): def setUp(self): config = {'mail.on': True, 'mail.manager': 'immediate', 'mail.transport': 'debug',} # conciously using classes and instances for fake_setuptools so that # the test also checks that TurboMail will do the right thing. fake_setuptools = {'immediate': ImmediateManager, 'debug': DebugTransportFactory()} interface.start(config, extra_classes=fake_setuptools) self.msg = Message('*****@*****.**', '*****@*****.**', 'Test', plain='Plain text body') def transport(self): return interface.manager.transport transport = property(transport) def tearDown(self): interface.stop(force=True) interface.config = {'mail.on': False} def test_fetch_sent_messages(self): msg_string = str(self.msg) self.msg.send() stored_mails = self.transport.get_sent_mails() self.assertEqual(1, len(stored_mails)) self.assertEqual(msg_string, str(stored_mails[0])) def test_message_send_themselves(self): msg_string = str(self.msg) self.msg.send() stored_mails = self.transport.get_sent_mails() self.assertEqual(1, len(stored_mails)) self.assertEqual(msg_string, str(stored_mails[0])) def test_wrapped_messages_send_themselves(self): msg_string = 'Subject: Test\n\nJust testing...' msg = WrappedMessage('*****@*****.**', '*****@*****.**', msg_string) msg.send() stored_mails = self.transport.get_sent_mails() self.assertEqual(1, len(stored_mails)) self.assertEqual(msg_string, str(stored_mails[0]))
def save_contact_form(self): '''Sends the form for sending contact emails if POSTed data validates; else redisplays the form with the error messages. ''' controls = self.request.params.items() try: appstruct = d.Form(contact_form_schema, buttons=('submit',), action=self.url('contact'), formid='contactform').validate(controls) # If form does not validate, returns the form except d.ValidationFailure as e: return dict(pagetitle=_("Contact"), contact_form=e.render()) # Form validation passes, so send the e-mail msg = Message(author=(appstruct['name'], appstruct['email']), subject=appstruct['subject'], plain=appstruct['message']) msg.send() self.request.override_renderer = 'contact_successful.genshi' return dict()
def mail_admin_error(self,user, assignment, tb, environ, includeSolution, anonymize, singletons, layoutEngine): from pprint import pformat app_name = config['application_name'] from_addr = config['error_email_from'] to_addr = config['email_to'] subject = "Error generating static graph" body = "Error generating static graph\n\n" body += tb+"\n\n" body += pformat(environ) + "\n\n" body += "user: "******" -- id: "+str(user.id)+"\n" body += "assignment: "+str(assignment)+" -- id: "+str(assignment.id)+"\n" body += "includeSolution: "+str(includeSolution)+"\n" body += "anonymize: "+str(anonymize)+"\n" body += "singletons: "+str(singletons)+"\n" body += "layoutEngine: "+str(layoutEngine)+"\n" message = Message(from_addr, to_addr, subject) message.plain = body message.send
def register(self, userlevel =''): # This is the subroutine/ method for registering users/ DEBTORS if request.method == 'POST': # If we have came from the register form state = State() state.session = Session try: params = register_user_form.validate(request.params, state=state) except tw.forms.core.Invalid, e: c.form_error = e.error_dict or {} else: # Create the new account in database if userlevel =="": userlevel =4 # Default to Debtors users = Users( username = params['user_name'], email = params['email_address'], displayname = params['display_name'], password = params['password'], activated = False, level =1 ) Session.add(users) http_server = request.environ.get('HTTP_ORIGIN') if not http_server: http_server = 'http://' + request.environ['HTTP_HOST'] activation_url = "%s%s?u=%s&key=%s" %( http_server, url(controller='account', action='activation'), quote(user.username), quote(activation.key) ) from turbomail import Message message = Message("*****@*****.**", user.email, "Welcome to RejuVu") message.plain = "Your RejuVu account is ready to use. Your username is '%s'. Activate your account at %s" %(user.username, activation_url) message.send() Session.commit() h.flash_info(u"A confirmation email has been sent to %s containing a link to activate your account." %(user.email_address,)) redirect(url('/'))
def submit(self): ''' This function validates the submitted registration form and creates a new user. Restricted to ``POST`` requests. If successful, redirects to the result action to prevent resubmission. ''' user = User( self.form_result['username'], fullname=self.form_result['fullname'], email=self.form_result['email'], first_area_id=self.form_result['first_area'], first_area_level=self.form_result['first_area_level'], second_area_id=self.form_result['second_area'], second_area_level=self.form_result['second_area_level'] ) Session.add(user) password = user.reset_password() Session.commit() msg = Message("*****@*****.**", self.form_result['email'], "InPhO registration") msg.plain = """Dear %(name)s, Thank you for registering with the Indiana Philosophy Ontology Project (InPhO). You can sign in at https://inpho.cogs.indiana.edu/signin with the following information: Username: %(uname)s Password: %(passwd)s You may change your password at https://inpho.cogs.indiana.edu/account/edit . The Indiana Philosophy Ontology Project (InPhO) Team [email protected] """ % {'passwd' : password, 'uname' : user.username, 'name' : user.fullname or user.username or ''} msg.send() h.redirect(h.url(controller='account', action='result'))
def save_contact_form(self): '''Sends the form for sending contact emails if POSTed data validates; else redisplays the form with the error messages. ''' controls = self.request.params.items() try: appstruct = d.Form(contact_form_schema, buttons=('submit', ), action=self.url('contact'), formid='contactform').validate(controls) # If form does not validate, returns the form except d.ValidationFailure as e: return dict(pagetitle=_("Contact"), contact_form=e.render()) # Form validation passes, so send the e-mail msg = Message(author=(appstruct['name'], appstruct['email']), subject=appstruct['subject'], plain=appstruct['message']) msg.send() self.request.override_renderer = 'contact_successful.genshi' return dict()
def _send_email_entry(self, entry): sender = self.request.registry.settings.get('mail.message.author', '*****@*****.**') recipient = entry.form.user.email subject = _("[MootiroForm] Entry #%(entry_number)d for the form %(form_title)s") \ % {"entry_number": entry.entry_number, "form_title": entry.form.name} labels = [f.label for f in entry.form.fields] value = [f.value(entry) for f in entry.form.fields] fields = [{ 'label': labels[i], 'value': value[i] } for i in range(len(labels))] try: rendered = self.request.registry.settings['genshi_renderer'] \ .fragment('email_entry.genshi', dict(entry=entry, fields=fields, url=self.url)) except KeyError as e: raise KeyError( "Simon says: cd mootiro_web; git pull; ./setup.py develop") # TODO: Remove this except block after developers have updated. # 2011-08-11 msg = Message(sender, recipient, self.tr(subject)) msg.rich = rendered msg.plain = "We've collected an entry for you form. Visit us to see." msg.send()
def comment(self): id = self.request.matchdict.get("map_id") map = Map.get(id) if map is None: return HTTPNotFound() # read the map author's email address from LDAP author = self.get_user_info(map.user_login) comment = self.request.params.get('comment') if self.request.params.get('name') and self.request.params.get('mail'): # feedback anonymous user feedback_name = self.request.params.get('name') feedback_mail = self.request.params.get('mail') else: # feedback loggedin user user = self.get_user_info(self.request.user.username) feedback_name = user[0] feedback_mail = user[1] try: message = Message( author='*****@*****.**', to=author[1], bcc='*****@*****.**', subject=(u'comment_email_subject') % {'title': map.title + " ( http://map.geoportail.lu/?map_id="+map.uuid+" ) ", 'feedback_name': feedback_name, 'feedback_mail': feedback_mail}, plain=comment) except: traceback.print_exc(file=sys.stdout) return HTTPNotFound() message.encoding = 'utf-8' message.send() return {'success': True}
def send(to, template_path, context=None, reply_to='', bcc='*****@*****.**'): """ Send message based on a mako template. The recipient is automatically added to the context_dict that gets fed to the template. """ t = EMAIL_TEMPLATE_LOOKUP.get_template(template_path) context = context or {} context['url_for'] = absolute_url_for def get_email(u, set_context=True): if isinstance(u, users.User): if set_context: context['user'] = u return u.email return u if isinstance(to, users.User): to = get_email(to) if isinstance(to, (list, tuple)): to = [get_email(u, set_context=False) for u in to] pc = pylons.config subject = t.get_def('subject').render_unicode(**context).strip() body = line_reduce(t.render_unicode(**context).strip()) f = (pc['mail.message.author_name'], pc['mail.message.author']) reroute = pc.get('mail.reroute') if reroute: old_to = to to = reroute lmsg = 'Sending email from %s to %s.' % (f, to) if reroute: lmsg += ' Message was rerouted from %s' % old_to logger.info(lmsg) msg = Message(f, to, subject, plain=body) msg.plain = body msg.bcc = bcc if reply_to: msg.reply_to = reply_to msg.send()
def __notify(chart, message): """ notify using email chart: Charts data row message: message body sending alert email to owner and followers """ config = __get_config('webapp') mail_config = {} mail_config['mail.on'] = config['turbomail']['enable'] mail_config['mail.manager'] = config['turbomail']['manager'] mail_config['mail.transport'] = config['turbomail']['transport'] mail_config['mail.smtp.server'] = config['turbomail']['server'] sender = config['turbomail']['sender'] """ rand send email """ day_str = datetime.datetime.strftime(datetime.datetime.today(), "%d%H") sender = 'Knowing <*****@*****.**>' % day_str subject = message u = session.query(Users).filter(Users.username == chart.owner) addressee = '' if u: for i in u: if i.mobile: addressee = i.mobile + '@139.com' else: logger.warning("no mobile set for user \"%s\"" % i.username) return interface.start(mail_config) now = str(datetime.datetime.now())[0:19] chart_url = 'http://knowing.corp.anjuke.com/chart/%d' % chart.id html_part = u"<html><body><h1>Look, %s</h1><p>时间: %s</p><p>详细信息: %s</p><p><a href='%s'>%s</a></p><p>This mail is sent by Knowing</p></body></html>" html_part %= (chart.name, now, message, chart_url, chart_url) text_part = u"[critical] 时间: %s 详细信息: %s" text_part %= (now, message) mail = Message(sender, addressee, subject) mail.encoding = 'utf-8' mail.plain = message mail.rich = html_part flag = mail.send()
def send_email(sender, truename, emails, title, plain, rich): """ notify using email sending alert email to followers """ """ rand send email """ day_str = datetime.datetime.strftime(datetime.datetime.today(),"%d%H") sender = 'Knowing <*****@*****.**>' % day_str logging.debug('Send email %s' % ', '.join((truename, str(emails), title, plain, rich))) try: mail = Message() mail.subject = title mail.sender = sender mail.to = u'%s <%s>' % (truename, emails[0]) if len(emails) > 1: mail.cc = u','.join(emails[1:]) mail.encoding = 'utf-8' mail.plain = plain mail.rich = rich mail.send() except Exception, e: logging.exception('Fail to send email.')
def send_email(self, imgs1, imgs2): day_str = datetime.datetime.strftime(datetime.datetime.today(), "%Y-%m-%d") mail = Message() mail.subject = u'#%s#SOS日报' % day_str mail.sender = '*****@*****.**' #mail.to = self.config['sos_receiver'] self.owner.append('*****@*****.**') self.owner.append('*****@*****.**') self.owner.append('*****@*****.**') self.owner.append('*****@*****.**') self.owner.append('*****@*****.**') self.owner.append('*****@*****.**') mailto = list(set(self.owner)) mail.to = ','.join(mailto) mail.encoding = 'utf-8' mail.plain = u'本邮件由Knowing系统自动发送,如有疑问请联系运维团队,谢谢。' title_style = 'font-size: 15px; font-weight: bold; padding-top: 10px;' items = [ u'<p>Hi All,</p><p>本邮件由Knowing系统自动发送,实时数据可<a href="http://knowing.corp.126.com/monitor/341">点此查看</a>,如有疑问请联系运维团队,谢谢。</p>' ] for img in imgs1: items.append( u'<div style="%s">%s</div><p><img src="cid:%d.png"></p>' % (title_style, img[1], img[0])) mail.embed(img[2], u'%d.png' % img[0]) items.append( '<table border="0" cellspacing="0" cellpadding="0" width="1024">') for i in xrange(0, len(imgs2), 2): items.append( u'<tr><td><div style="%s">%s</div><img src="cid:%d.png"></td>' % (title_style, imgs2[i][1], imgs2[i][0])) mail.embed(imgs2[i][2], u'%d.png' % imgs2[i][0]) if i + 1 < len(imgs2): items.append( u'<td valign="bottom"><div style="%s">%s</div><img src="cid:%d.png"></td></tr>' % (title_style, imgs2[i + 1][1], imgs2[i + 1][0])) mail.embed(imgs2[i + 1][2], u'%d.png' % imgs2[i + 1][0]) else: items.append(u'<td> </td></tr>') items.append('</table>') mail.rich = u''.join(items) print 'Sending email...' mail.send()