def send_mail_via_smtp_(config, payload): """ Send email via SMTP :param config: :param payload: :return: """ mailer_config = { 'transport': { 'use': 'smtp', 'host': config['host'], 'username': config['username'], 'password': config['password'], 'tls': config['encryption'], 'port': config['port'] } } mailer = Mailer(mailer_config) mailer.start() message = Message(author=payload['from'], to=payload['to']) message.subject = payload['subject'] message.plain = strip_tags(payload['html']) message.rich = payload['html'] mailer.send(message) mailer.stop()
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' mailer.send(message) except Exception as e: log.exception(e) return HTTPNotFound() return {'success': True}
def send_email_task_smtp(payload, smtp_config, headers=None): mailer_config = { 'transport': { 'use': 'smtp', 'host': smtp_config['host'], 'username': smtp_config['username'], 'password': smtp_config['password'], 'tls': smtp_config['encryption'], 'port': smtp_config['port'] } } try: mailer = Mailer(mailer_config) mailer.start() message = Message(author=payload['from'], to=payload['to']) message.subject = payload['subject'] message.plain = strip_tags(payload['html']) message.rich = payload['html'] if payload['attachments'] is not None: for attachment in payload['attachments']: message.attach(name=attachment) mailer.send(message) logging.info('Message sent via SMTP') except urllib.error.HTTPError as e: if e.code == 554: empty_attachments_send(mailer, message) mailer.stop()
def send_email(self, send_to, template, subject, **kwargs): """ Sends an email to the target email with two types 1) HTML 2) Plain We will try the template with .htm for rich and .txt for plain, if one isn't found we will only send the correct one. Both will rendered with Jinja2 """ message = Message(author=self._config.EMAIL_SENDER, to=send_to) message.subject = subject try: rendered_template = self._jinja_env.get_template(template + '.txt') message.plain = rendered_template.render(**kwargs) self._log.debug('Plain text email is %s', message.plain) except TemplateNotFound: self._log.debug('txt template not found') try: rendered_template = self._jinja_env.get_template(template + '.htm') message.rich = rendered_template.render(**kwargs) self._log.debug('html email generated %s' % message.rich) except TemplateNotFound: self._log.debug('html template not found') self._mailer.send(message)
def sendMail(mail): try: message = Message(author="*****@*****.**", to=mail) # mail subject, obviously message.subject = "Subject" # plain text variant: message.plain = "Please view this mail with html enabled." # when pressing "reply", send mail to: message.reply = "*****@*****.**" # HTML variant: message.rich = """ <h1>Header</h1> <p>some text</p> """ message.attach(name='path-to-attachment.pdf') mailer.send(message) print('successfull sent mail to ' + mail) return True except: print('There was an error for mail ' + mail + ", skipping this.") return False
def feedbackcrues(self): try: vars = self.request.json_body map_id = self.config['age_crues']['map_id'] map = self.db_mymaps.query(Map).get(map_id) if map is None: return HTTPNotFound() message = u"L\'utilisateur {1} <a href=\"mailto:{0}\">({0})</a> " \ u"a remarqué le problème dessiné sur la carte :</p>" \ .format(vars['email'], vars['name'] ) features = vars['features'].\ replace(u'\ufffd', '?') feature_collection = geojson.\ loads(features, object_hook=geojson.GeoJSON.to_instance) for feature in feature_collection['features']: obj = None try: obj = Feature(feature) obj.name = vars['name'] obj.description = message except Exception as e: log.exception(e) if obj is not None: map.features.append(obj) self.db_mymaps.flush() html_body = u"<h3>L\'utilisateur {2}<a href=\"mailto:{0}\">" \ u"({0})</a> " \ u"<p><a href=\"{1}\">Ouvrir le lien vers la carte</a></p>" \ u"<p>L'incident a été enregistré dans cette <a href=\"{3}\">" \ u"mymaps</a>:</p>" \ .format(vars['email'], vars['url'], vars['name'], "http://map.geoportail.lu?map_id=" + map_id, ) support_email = self.config['age_crues']['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' mailer.send(message) except Exception as e: log.exception(e) return HTTPNotFound() return {'success': True}
def send_email(self, send_to, template, subject, content, files=[], **kwargs): """ Sends an email to the target email with two types 1) HTML 2) Plain We will try the template with .html for rich and .txt for plain, if one isn't found we will only send the correct one. Both will rendered with Jinja2 """ message = Message(author=self._config.EMAIL_SENDER, to=send_to) message.subject = subject if len(files) > 0: for f in files: #part = MIMEBase('application', "octet-stream") #part.set_payload( open(f,"rb").read() ) # Encoders.encode_base64(part) filename = os.path.basename(f) #part.add_header('Content-Disposition', 'attachment; filename="%s"' % filename) message.attach(filename, data=f) if template: try: rendered_template = self._jinja_env.get_template(template + '.txt') message.plain = rendered_template.render(**kwargs) self._log.debug('Plain text email is %s', message.plain) except TemplateNotFound: self._log.debug('txt template not found') try: rendered_template = self._jinja_env.get_template(template + '.html') message.rich = rendered_template.render(**kwargs) self._log.debug('html email generated %s' % message.rich) except TemplateNotFound: self._log.debug('html template not found') else: if content: message.plain = content else: raise MailConfigurationException( 'No Message content or template defined') self._mailer.send(message)
def send(subject, text, html, sender, recipient, cc=None, bcc=None): mailer = Mailer(dict(transport=dict(use='smtp', host='localhost'))) mailer.start() message = Message(author=sender, to=recipient, cc=cc, bcc=bcc) message.subject = subject message.rich = html message.plain = text mailer.send(message) mailer.stop()
def send_email(self, send_to, template, subject, content, files=[], **kwargs): """ Sends an email to the target email with two types 1) HTML 2) Plain We will try the template with .html for rich and .txt for plain, if one isn't found we will only send the correct one. Both will rendered with Jinja2 """ message = Message(author=self._config.EMAIL_SENDER, to=send_to) message.subject = subject if len(files) > 0: for f in files: #part = MIMEBase('application', "octet-stream") #part.set_payload( open(f,"rb").read() ) # Encoders.encode_base64(part) filename = os.path.basename(f) #part.add_header('Content-Disposition', 'attachment; filename="%s"' % filename) message.attach(filename, data=f) if template: try: rendered_template = self._jinja_env.get_template( template + '.txt') message.plain = rendered_template.render(**kwargs) self._log.debug('Plain text email is %s', message.plain) except TemplateNotFound: self._log.debug('txt template not found') try: rendered_template = self._jinja_env.get_template( template + '.html') message.rich = rendered_template.render(**kwargs) self._log.debug('html email generated %s' % message.rich) except TemplateNotFound: self._log.debug('html template not found') else: if content: message.plain = content else: raise MailConfigurationException( 'No Message content or template defined') self._mailer.send(message)
def notify_share(self, sender, contact, subject, plain_template, template, context): mailer = request.app.mailer html_message = self.load_template(template).render(**context) plain_message = self.load_template(plain_template).render(**context) from_email = request.app.config['smtp']['from_email'] if request.app.config['kliqtok']['debug']: recipients = ['*****@*****.**', '*****@*****.**'] else: recipients = [contact.email] message = Message(author=from_email, to=recipients) message.subject = subject % context message.plain = plain_message message.rich = html_message mailer.send(message)
def send_mail_via_smtp(payload): """ Send email via SMTP :param config: :param payload: :return: """ smtp_encryption = current_app.config['SMTP_ENCRYPTION'] if smtp_encryption == 'tls': smtp_encryption = 'required' elif smtp_encryption == 'ssl': smtp_encryption = 'ssl' elif smtp_encryption == 'tls_optional': smtp_encryption = 'optional' else: smtp_encryption = 'none' config = { 'host': current_app.config['SMTP_HOST'], 'username': current_app.config['SMTP_USERNAME'], 'password': current_app.config['SMTP_PASSWORD'], 'encryption': smtp_encryption, 'port': current_app.config['SMTP_PORT'], } mailer_config = { 'transport': { 'use': 'smtp', 'host': config['host'], 'username': config['username'], 'password': config['password'], 'tls': config['encryption'], 'port': config['port'] } } mailer = Mailer(mailer_config) mailer.start() message = Message(author=payload['from'], to=payload['to']) message.subject = payload['subject'] message.plain = strip_tags(payload['message']) message.rich = payload['message'] message.attach(payload['attachment']) mailer.send(message) mailer.stop()
def send_mail_via_smtp_task(config, payload): mailer_config = { 'transport': { 'use': 'smtp', 'host': config['host'], 'username': config['username'], 'password': config['password'], 'tls': config['encryption'], 'port': config['port'] } } mailer = Mailer(mailer_config) mailer.start() message = Message(author=payload['from'], to=payload['to']) message.subject = payload['subject'] message.plain = strip_tags(payload['html']) message.rich = payload['html'] mailer.send(message) logging.info('Message sent via SMTP') mailer.stop()
def send_email_task_smtp(payload): smtp_config = get_smtp_config() mailer_config = {'transport': {'use': 'smtp', **smtp_config}} mailer = Mailer(mailer_config) mailer.start() message = Message(author=payload['from'], to=payload['to']) message.subject = payload['subject'] message.plain = strip_tags(payload['html']) message.rich = payload['html'] if payload['bcc'] is not None: message.bcc = payload['bcc'] if payload['attachments'] is not None: for attachment in payload['attachments']: message.attach(name=attachment) try: mailer.send(message) logging.info('Message sent via SMTP') except urllib.error.HTTPError as e: if e.code == 554: empty_attachments_send(mailer, message) mailer.stop()
def send(rst, html, email, name, cc): from marrow.mailer import Mailer, Message mailer = Mailer( dict( transport = dict( use = 'smtp', host = 'localhost'))) mailer.start() message = Message( author="*****@*****.**", to=email, cc=cc, bcc='*****@*****.**' ) message.subject = "Karatbars replicated website for {0}".format(name) message.rich = html message.plain = rst mailer.send(message) mailer.stop()
def command(self): "run command" self.init() import baruwa here = os.path.dirname( os.path.dirname(os.path.abspath(baruwa.__file__)) ) path = os.path.join(here, 'baruwa', 'templates') logo = os.path.join(here, 'baruwa', 'public', 'imgs', 'logo.png') localedir = os.path.join(here, 'baruwa', 'i18n') cache_dir = os.path.join(self.conf['cache_dir'], 'templates') pkgname = 'baruwa' if not os.path.exists(logo): print sys.STDERR ("The logo image: %s does not exist" % logo) sys.exit(2) with open(logo) as handle: logo = base64.b64encode(handle.read()) mako_lookup = TemplateLookup( directories=[path], error_handler=handle_mako_error, module_directory=cache_dir, input_encoding='utf-8', default_filters=['escape'], output_encoding='utf-8', encoding_errors='replace', imports=['from webhelpers.html import escape'] ) mailer = Mailer(get_conf_options(self.conf)) mailer.start() users = Session.query(User)\ .filter(User.active == True)\ .filter(User.send_report == True) previous_records = Session\ .query(Release.messageid)\ .order_by(desc('timestamp')) for user in users: messages = Session.query(Message.id, Message.timestamp, Message.from_address, Message.to_address, Message.subject, case([(and_(Message.spam > 0, Message.virusinfected == 0, Message.nameinfected == 0, Message.otherinfected == 0, ), True)], else_=False).label('spam'), Message.to_domain)\ .filter(Message.isquarantined > 0)\ .filter(or_(Message.spam > 0, Message.nameinfected > 0, Message.otherinfected > 0))\ .order_by(desc('timestamp')) query = UserFilter(Session, user, messages) messages = query.filter() if int(self.options.days) > 0: a_day = datetime.timedelta(days=self.options.days) startdate = now().date() - a_day messages = messages.filter(Message.timestamp > str(startdate)) messages = messages.filter(~Message.id.in_(previous_records)) messages = messages[:25] if messages: lang = 'en' host_urls = dict([(domain.name, domain.site_url) for domain in user.domains if domain.status == True]) langs = [domain.language for domain in user.domains if domain.language != 'en'] if langs: lang = langs.pop(0) translator = set_lang(lang, pkgname, localedir) _ = translator.ugettext def make_release_records(spam): "map function" uuid = gen_uuid(user) spam.uuid = uuid return Release(uuid=uuid, messageid=spam.id) if user.is_peleb: torelease = [make_release_records(spam) for spam in messages] template = mako_lookup.get_template('/email/quarantine.html') html = template.render(messages=messages, host_urls=host_urls, url=url_for, default_url=self.conf['baruwa.default.url']) template = mako_lookup.get_template('/email/quarantine.txt') text = template.render(messages=messages) displayname = "%s %s" % (user.firstname, user.lastname) email = Msg(author=[(_('Baruwa Reports'), self.conf['baruwa.reports.sender'])], to=[(displayname, user.email)], subject=_('Baruwa quarantine report')) email.plain = text email.rich = html email.attach('logo.png', data=logo, maintype='image', subtype='png', inline=True) mailer.send(email) if 'torelease' in locals(): Session.add_all(torelease) Session.commit() mailer.stop()
def send(self, to, html_body, plain_body): message = Message(author=from_email, to=to) message.subject = subject message.plain = plain_body message.rich = html_body self.mailer.send(message)
def command(self): "run command" self.init() import baruwa here = os.path.dirname( os.path.dirname(os.path.abspath(baruwa.__file__))) path = os.path.join(here, 'baruwa', 'templates') logo = os.path.join(here, 'baruwa', 'public', 'imgs', 'logo.png') localedir = os.path.join(here, 'baruwa', 'i18n') cache_dir = os.path.join(self.conf['cache_dir'], 'templates') pkgname = 'baruwa' if not os.path.exists(logo): print sys.STDERR("The logo image: %s does not exist" % logo) sys.exit(2) with open(logo) as handle: logo = base64.b64encode(handle.read()) mako_lookup = TemplateLookup( directories=[path], error_handler=handle_mako_error, module_directory=cache_dir, input_encoding='utf-8', default_filters=['escape'], output_encoding='utf-8', encoding_errors='replace', imports=['from webhelpers.html import escape']) mailer = Mailer(get_conf_options(self.conf)) mailer.start() users = Session.query(User)\ .filter(User.active == True)\ .filter(User.send_report == True) previous_records = Session\ .query(Release.messageid)\ .order_by(desc('timestamp')) for user in users: messages = Session.query(Message.id, Message.timestamp, Message.from_address, Message.to_address, Message.subject, case([(and_(Message.spam > 0, Message.virusinfected == 0, Message.nameinfected == 0, Message.otherinfected == 0, ), True)], else_=False).label('spam'), Message.to_domain)\ .filter(Message.isquarantined > 0)\ .filter(or_(Message.spam > 0, Message.nameinfected > 0, Message.otherinfected > 0))\ .order_by(desc('timestamp')) query = UserFilter(Session, user, messages) messages = query.filter() if int(self.options.days) > 0: a_day = datetime.timedelta(days=self.options.days) startdate = now().date() - a_day messages = messages.filter(Message.timestamp > str(startdate)) messages = messages.filter(~Message.id.in_(previous_records)) messages = messages[:25] if messages: lang = 'en' host_urls = dict([(domain.name, domain.site_url) for domain in user.domains if domain.status == True]) langs = [ domain.language for domain in user.domains if domain.language != 'en' ] if langs: lang = langs.pop(0) translator = set_lang(lang, pkgname, localedir) _ = translator.ugettext def make_release_records(spam): "map function" uuid = gen_uuid(user) spam.uuid = uuid return Release(uuid=uuid, messageid=spam.id) if user.is_peleb: torelease = [ make_release_records(spam) for spam in messages ] template = mako_lookup.get_template('/email/quarantine.html') html = template.render( messages=messages, host_urls=host_urls, url=url_for, default_url=self.conf['baruwa.default.url']) template = mako_lookup.get_template('/email/quarantine.txt') text = template.render(messages=messages) displayname = "%s %s" % (user.firstname, user.lastname) email = Msg(author=[(_('Baruwa Reports'), self.conf['baruwa.reports.sender'])], to=[(displayname, user.email)], subject=_('Baruwa quarantine report')) email.plain = text email.rich = html email.attach('logo.png', data=logo, maintype='image', subtype='png', inline=True) mailer.send(email) if 'torelease' in locals(): Session.add_all(torelease) Session.commit() mailer.stop()
def buildnewsletter(book_list): """Routine to send an HTML newsletter """ logger.info('Pulling together the newsletter.') __tmp__file__loc = "tmpicon.jpg" mailer = Mailer( dict(transport=dict(use='smtp', host=config.settings['SMTPSettings']['host'], port=config.settings['SMTPSettings']['port'], username=config.settings['SMTPSettings']['user'], password=config.settings['SMTPSettings'] ['password'], tls=config.settings['SMTPSettings']['startttls']))) try: # Perform jinja message_template_file = config.settings['TEMPLATE_FILE'] message_banner_img = os.path.join( config.settings['TEMPLATE_DIR'], config.settings['TEMPLATE_BANNER_IMG']) message_unknown_img = os.path.join( config.settings['TEMPLATE_DIR'], config.settings['TEMPLATE_NOCOVER_IMG']) message_intropara_file = os.path.join( config.settings['TEMPLATE_DIR'], config.settings['TEMPLATE_INTROPARA']) cd = config.settings['TEMPLATE_DIR'] logger.info(cd) jinja_env = jinja2.Environment(loader=jinja2.FileSystemLoader(cd)) try: with open(message_intropara_file, 'r') as introparafile: message_intropara = introparafile.read().replace('\n', '') logger.info('Loaded newsletter intro paragraph.') except: message_intropara = "<p>New books added.</p>" logger.exception("Couldn't load intro paragraph.") logger.warn('Loading default newsletter intro paragraph.') messagebody = jinja_env.get_template(message_template_file).render( book_list=book_list, intropara_blk=message_intropara) mailer.start() message = Message(author=config.settings['SMTPSettings']['user']) message.subject = config.settings['SMTPSettings']['subject'] message.plain = "This is only exciting if you use an HTML capable email client. Please disregard." message.rich = messagebody message.embed(message_banner_img) flg_unknown_embedded = False for book in book_list: if book["book_cover_id"] != "Unknown.png": book['cover_thumbnail'].save(__tmp__file__loc, "JPEG") message.embed((book["book_cover_id"]), open(__tmp__file__loc)) elif book[ "book_cover_id"] == "Unknown.png" and not flg_unknown_embedded: message.embed(message_unknown_img) flg_unknown_embedded = True for winner in db_operations.get_dl_list(): message.to = winner if config.settings['DevMode']: mailer.send(message) logger.info('DevMode - Sending email to %s', winner) else: mailer.send(message) logger.info('sending email to %s', winner) except: logger.exception('Error sending email.') mailer.stop() logger.info('Completed newsletter routine.') return