def send_email(self, user_id, subject, content, pdf_attachment=None): if user_id not in self.request.root.users: logging.error("When sending email, user ID %s does not exist" % user_id) return False user = self.request.root.users[user_id] if user.profile == None or user.profile.email == None: logging.error("When sending email, user ID %s does not have a profile or email address" % user_id) return False try: # Compose message send_name = self.request.registry._settings["sender_name"] send_email = self.request.registry._settings["sender_email"] message = Message( author = '%s <%s>' % (send_name, send_email), subject = "%s - %s" % (PROP_KEYS.getProperty(self.request, PROP_KEYS.EVENT_NAME), subject), to = user.profile.email, rich = content["rich"], plain = content["plain"] ) # Attach any available PDFs if pdf_attachment != None: message.attach("tickets.pdf", data=pdf_attachment, maintype="application", subtype="pdf") # Dispatch Message get_mailer(self.request).send(message) logging.info("Sent email with subject '%s' to email %s" % (subject, user.profile.email)) return True except socket.error: logging.exception("Socket error occurred when sending email to user %s" % user_id) return False except Exception: logging.exception("Email send exception occurred to user %s" % user_id) return False
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_mail(subj, body, bifogade_filer, recipients=[], sender='*****@*****.**'): from marrow.mailer import Mailer, Message """Send mail to specified recipients.""" recipients = [*recipients] mailer = Mailer(dict(transport=dict(use='smtp', host='smtp.gu.se'))) mailer.start() message = Message( subject=f'{subj}', plain=f'{body}', author=sender, to=recipients, ) if bifogade_filer: for fil in bifogade_filer: if not os.path.isfile(fil): message.plain += "\n" message.plain += f"Error: attempted attachment {fil} does not appear to exist" else: message.attach(str(fil)) nl = "\n" message.plain += f"{nl}{nl}If you have any question you can reach us at:" message.plain += f"{nl}[email protected]" message.plain += f"{nl}" message.plain += f"{nl}Best regards," message.plain += f"{nl}Clinical Genomics Gothenburg" mailer.send(message)
def send_report_mail(plain_text, settings): """Send anomalies report by email Arguments: plain_text {string} -- Report body in plain text settings (dict) -- Settings from the class Config.Smtp Returns: """ mailer = Mailer({ 'manager.use': 'futures', 'transport.use': 'smtp', 'transport.host': settings['host'], 'transport.tls': settings['ssl'], 'transport.debug': False, 'transport.username': settings['username'], 'transport.password': settings['password'], 'transport.max_messages_per_connection': 5 }) mailer.start() message = Message(author=settings['mailfrom'], to=settings['mailto']) message.subject = settings['subject'] message.plain = plain_text mailer.send(message) mailer.stop() return True
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_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 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 send_bulk_email(self, user_ids, subject, content): emails = [] for user_id in user_ids: if not user_id in self.request.root.users: continue user = self.request.root.users[user_id] if user.profile == None or user.profile.email == None: continue emails.append(user.email) if len(emails) <= 0: return False try: # Compose message send_name = self.request.registry._settings["sender_name"] send_email = self.request.registry._settings["sender_email"] message = Message( author = '%s <%s>' % (send_name, send_email), subject = "%s - %s" % (PROP_KEYS.getProperty(self.request, PROP_KEYS.EVENT_NAME), subject), bcc = emails, rich = content["rich"], plain = content["plain"] ) # Dispatch Message get_mailer(self.request).send(message) logging.info("Sent email with subject '%s' to emails %s" % (subject, emails)) return True except socket.error: logging.exception("Socket error occurred when sending email to user %s" % user_id) return False except Exception: logging.exception("Email send exception occurred to user %s" % user_id) return False
def send_email(self, to, subject, content, author=''): self.mailer.start() self.mailer.send( Message(author=author or self.username, to=to, subject=subject, plain=content)) self.mailer.stop()
def build_message(self, **kw): return Message( author=('Author', '*****@*****.**'), to=('Recipient', '*****@*****.**'), subject='Test message subject.', plain='This is a test message plain text body.', **kw )
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 test_delivery(self): message = Message('*****@*****.**', '*****@*****.**', "Test subject.") message.plain = "Test message." self.transport.startup() self.transport.deliver(message) with open(self.filename, 'rb') as fh: self.assertEqual(str(message), b"\n".join(fh.read().splitlines()[1:]))
def test_delivery(self): message = Message('*****@*****.**', '*****@*****.**', "Test subject.") message.plain = "Test message." self.transport.startup() self.transport.deliver(message) filename = os.listdir(os.path.join(self.path, 'new'))[0] with open(os.path.join(self.path, 'new', filename), 'rb') as fh: self.assertEqual(str(message), fh.read())
def send_email(to, subject, template, **kwargs): mailer.start() template_plain = Template(template_file=template + '.txt') template_rich = Template(template_file=template + '.html') message = Message(author=sender, to=to, subject=subject, plain=template_plain.render_template(**kwargs), rich=template_rich.render_template(**kwargs)) s = mailer.send(message) mailer.stop() return s
def send_email(request, author, to, subject, message, reply=None): if not isinstance(to, (list, tuple)): to = [to] to = [unicode(x) for x in to if x] mailer = _get_mailer(request) args = dict(author=unicode(author), to=to, subject=subject, plain=message) if reply: args['reply'] = unicode(reply) message = Message(**args) mailer.send(message)
def send_local_mail(user: str): mailer = Mailer(dict(transport=dict(use="sendmail", host="localhost"))) mailer.start() otp = generate_otp_for_user(user) print(otp) message = Message(author="*****@*****.**", to=user) message.sendmail_f = "*****@*****.**" message.subject = "Login for Twit" message.plain = f"Your OTP is {otp}" mailer.send(message) mailer.stop()
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 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(subj, body, bifogad_fil, recipients=[], sender='*****@*****.**'): from marrow.mailer import Mailer, Message """Send mail to specified recipients.""" recipients = [*recipients] mailer = Mailer(dict( transport=dict(use='smtp', host='change.me.se'))) mailer.start() message = Message( subject=f'{subj}', plain=f'{body}', author=sender, to=recipients,) message.attach(str(bifogad_fil)) mailer.send(message) mailer.stop()
def test_missing_values(self): message = Message() self.assertRaises(ValueError, str, message) message.author = "*****@*****.**" self.assertRaises(ValueError, str, message) message.subject = "Attn: Bob Dole" self.assertRaises(ValueError, str, message) message.to = "*****@*****.**" self.assertRaises(ValueError, str, message) message.plain = "Testing!" try: str(message) except ValueError: self.fail("Message should be valid.")
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(cls, email_contents): """Sends an email via SMTP. :param dict email_contents: from_email - Email address to send FROM to_email - Email address to send TO subject - Subject of email plain_message - Plaintext messgae rich_message - Rich/HTML message """ mailer = Mailer({ 'manager.use': 'immediate', 'transport.use': 'smtp', 'transport.host': config.get('secrets.smtp.host'), 'transport.port': config.get('secrets.smtp.port'), 'transport.username': config.get('secrets.smtp.username'), 'transport.password': config.get('secrets.smtp.password'), 'transport.timeout': 10, }) mailer.start() message = Message( author=email_contents['from_email'], to=email_contents['to_email'], subject=email_contents['subject'], plain=email_contents.get('plain_message') or '-- message not available --', rich=email_contents.get('rich_message'), ) mailer.send(message) mailer.stop()
def test_delivery(self): self.assertEqual(len(self.messages), 1) message = Message('*****@*****.**', '*****@*****.**', 'Subject.', plain='Body.') msg = str(message) self.transport.deliver(message) self.assertEqual(len(self.messages), 3) expect = "DELIVER %s %s %d %r %r" % ( message.id, message.date.isoformat(), len(msg), message.author, message.recipients) self.assertEqual(self.messages[0].getMessage(), "Logging transport starting.") self.assertEqual(self.messages[1].getMessage(), expect) self.assertEqual(self.messages[1].levelname, 'INFO') self.assertEqual(self.messages[2].getMessage(), str(message)) self.assertEqual(self.messages[2].levelname, 'CRITICAL')
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 test_new(self): config = dict(manager=dict(use='immediate'), transport=dict(use='mock'), message=dict(author='*****@*****.**', retries=1, brand=False)) interface = Mailer(config).start() message = interface.new(retries=2) self.assertEqual(message.author, ["*****@*****.**"]) self.assertEqual(message.bcc, []) self.assertEqual(message.retries, 2) self.assertTrue(message.mailer is interface) self.assertEqual(message.brand, False) self.assertRaises(NotImplementedError, Message().send) self.assertEqual(message.send(), (message, True)) message = interface.new("*****@*****.**", "*****@*****.**", "Test.") self.assertEqual(message.author, ["*****@*****.**"]) self.assertEqual(message.to, ["*****@*****.**"]) self.assertEqual(message.subject, "Test.")
def emailClient(mailer, userName, clientName, clientNum, clientFileName, plain=""): """Email the new file to any client.""" if plain == "": plain = "Documents attached." mailer.start() message = Message(author=userName, to=clientKey[clientName]['client'], cc=emailKey[clientNum], bcc=userName, subject=clientFileName[1], plain=plain) message.attach(clientFileName[0]) mailer.send(message) mailer.stop() os.remove(clientFileName[0])
def test_missing_values(self): message = Message() with pytest.raises(ValueError): unicode(message) message.author = "*****@*****.**" with pytest.raises(ValueError): unicode(message) message.subject = "Attn: Bob Dole" with pytest.raises(ValueError): unicode(message) message.to = "*****@*****.**" with pytest.raises(ValueError): unicode(message) message.plain = "Testing!" try: unicode(message) except ValueError: assert False, "Message should be valid."
def test_new(self): config = dict( manager=dict(use='immediate'), transport=dict(use='mock'), message=dict(author='*****@*****.**', retries=1, brand=False)) interface = Mailer(config).start() message = interface.new(retries=2) assert message.author == ["*****@*****.**"] assert message.bcc == [] assert message.retries == 2 assert message.mailer is interface assert message.brand == False with pytest.raises(NotImplementedError): Message().send() assert message.send() == (message, True) message = interface.new("*****@*****.**", "*****@*****.**", "Test.") assert message.author == ["*****@*****.**"] assert message.to == ["*****@*****.**"] assert message.subject == "Test."