def email_notification(): msg = htmlTemplate.generate(__getstatus__()) message = Message(From=email_sender, To=email_receiver, charset="utf-8") message.Subject = email_subject message.Html = msg sender = Mailer(email_server, smtp_port) sender.send(message)
def send_email(user, pwd, recipient, subject, body): gmail_user = user gmail_pwd = pwd FROM = user TO = recipient if type(recipient) is list else [recipient] SUBJECT = subject TEXT = body message = Message(From=FROM, To=TO) message.Subject = SUBJECT message.Html = """ <html> <head></head> <body> <p>Hi! You've requested the UTNC practice schedule<br> How are you?<br> Here is the <a href="http://www.python.org">link</a> you wanted. </p> </body> </html> """ sender = Mailer('smtp.gmail.com',port=587, use_tls=True, usr=gmail_user, pwd=gmail_pwd) sender.send(message)
def test_send_mail__unencrypted_authorized(self, smtp_mock): mail_data = MailData() mail_data.recipients = ["*****@*****.**"] mail_data.subject = "Test mail" mail_data.body = "Test body" mailer_config = MailerConfig() mailer_config.smtp_host = "localhost" mailer_config.smtp_port = 25 mailer_config.use_starttls = False mailer_config.use_ssl = False mailer_config.user = "******" mailer_config.password = "******" mailer_config.sender = "*****@*****.**" mailer = Mailer() mail = mailer.create_mail(mail_data) mailer.send_mail(mailer_config, mail) assert smtp_mock.call_count == 1 assert smtp_mock.call_args == ((mailer_config.smtp_host, mailer_config.smtp_port),) assert smtp_mock.return_value.starttls.call_count == 0 assert smtp_mock.return_value.login.call_count == 1 assert smtp_mock.return_value.login.call_args == ((mailer_config.user, mailer_config.password),) assert smtp_mock.return_value.sendmail.call_count == 1 assert smtp_mock.return_value.sendmail.call_args == ((mail["From"], mail["To"], mail.as_string()),) assert smtp_mock.return_value.quit.call_count == 1
def giveup(self): if self.email: Mailer.send([self.email], self.sender, self.subject % (self.success), self.mail_message % (self.eid, self.logs, self.now()), self.reply) exit()
def test_create_mail__attach_text_and_zip(self): mail = MailData() mail.recipients = ["*****@*****.**"] mail.subject = "Test mail" mail.body = "Test body" mail.file_attachments = ["test.txt", "test.zip"] text_file = FileStub("TEXT") zip_file = FileStub("BINARY") Mailer.open_file = MagicMock(side_effect = [text_file, zip_file]) mimetypes.guess_type = MagicMock(side_effect = [("text/plain", None), ("application/zip", None)]) mailer = Mailer() result = mailer.create_mail(mail) self.assertEqual("*****@*****.**", result["To"]) self.assertEqual(mail.subject, result["Subject"]) self.assertTrue(result.is_multipart()) messages = result.get_payload() self.assertEqual(3, len(messages)) text_message = messages[0] self.assertEqual("text/plain", text_message.get_content_type()) self.assertEqual(mail.body, text_message.get_payload()) attachment1_message = messages[1] self.assertEqual("text/plain", attachment1_message.get_content_type()) self.assertEqual("TEXT", attachment1_message.get_payload()) attachment2_message = messages[2] self.assertEqual("application/zip", attachment2_message.get_content_type()) self.assertEqual(base64.b64encode("BINARY"), attachment2_message.get_payload())
class Notifier: LOG_FILE = 'farming.log' def __init__(self): self._logger = self.get_logger(Notifier.LOG_FILE) self._mailer = Mailer() def get_logger(self, log_file_name): logger = logging.getLogger('apscheduler.executors.default') logger.setLevel(logging.INFO) handler = logging.handlers.TimedRotatingFileHandler(log_file_name, when="midnight", backupCount=3) formatter = logging.Formatter( '%(asctime)s %(levelname)-8s %(message)s') handler.setFormatter(formatter) logger.addHandler(handler) return logger #Will log the message and will send a mail def notify(self, message, digest): print message self._logger.info(message) self._mailer.send_message(message, digest) def log(self, message): print message self._logger.info(message)
def notify(args): config = parse_config(args.config) db = database.WatchDb(db_path=DB_PATH) LOGGER.info("Notify if something is not working...") if db.get_status(config['notify']['track_last']): LOGGER.info("Everything seems to be ok.") else: LOGGER.warning("One of tests failed, generate report.") env = Environment(loader=FileSystemLoader(DIRECTORY)) template = env.get_template('template.html') body = template.render(table=db.get_latest(config['notify']['track_last'])) LOGGER.info("Sending email...") sender = Mailer( config['smtp']['host'], port=config['smtp']['port'], usr=config['smtp']['user'], pwd=config['smtp']['password'], ) message = Message( From=config['smtp']['user'], To=config['notify']['email'], ) message.Subject = config['notify']['subject'] message.Html = body sender.send(message)
def email_sender(msg): sender = Mailer(host=email_info['smtp'][0], port=email_info['smtp'][1], use_tls=True, usr=email_info['auth'][0], pwd=email_info['auth'][1]) return sender.send(msg)
def mail_manifest(self, emailfrom, emailto): message = Message(From=emailfrom, To=emailto) message.Subject = "Manifest" message.Html = self.fetch_manifest() sender = Mailer('localhost') sender.send(message)
def report_html(self, target): if not target: return view = report.HtmlView(self._table_list, self._title) view.set_encoding(self._options.encoding) if '@' in target: recp = [] for mail_to in target.split(';'): mail_to = mail_to.strip() if not mail_to: continue logger.info('send mail to %s', mail_to) recp.append(mail_to) msg = Message( recp = recp, subject = self._title, html = view.show()) mailer = Mailer() mailer.send(msg) else: path = os.path.abspath(target) logger.info('save html report in: %s', path) fp = open(path, 'wb') fp.write(view.show()) fp.close() return
def feedback_view(request): if request.method == 'POST': form = FeedbackForm(request.POST) if form.is_valid(): message = form.save() context = {'object': message} if message.city: if message.city.has_marts and message.city.city_recipient_email: recipient_email = message.city.city_recipient_email else: recipient_email = message.city.recipient_email recipients = list(message.city.recipients.all().values_list( 'email', flat=True)) if recipient_email: recipients.append(recipient_email) else: obj = VologdaCity.objects.all()[0] recipient_email = obj.recipient_email recipients = list(obj.recipients.all().values_list('email', flat=True)) if recipient_email: recipients.append(recipient_email) Mailer.send( recipients=recipients, context_data=context, template_name='assets/mail/feedback', ) return redirect('assets_feedback_success') else: form = FeedbackForm() return render(request, 'assets/feedback_form.html', { 'form': form, })
def forgot_password(email, link): conn = sqlite3.connect(url + "users.db") cur = conn.cursor() cur.execute(f"select email,userid from users where email='{email}'") data = cur.fetchone() conn.close() if (len(data) == 0): return "0" else: send = "*****@*****.**" recver = email message = Message(From=send, To=recver) message.Subject = "Reset Password for Miniature Stock Exchange" message.Html = f"""<p>Hello!<br><br> Here is the <a href="{link}">link</a> to reset your password.<br> This link will be valid for only one hour.<br><br> Regards,<br> Miniature Stock Exchange Team </p> """ try: sender = Mailer('smtp.gmail.com', use_tls=True, usr=send, pwd='ministockexchange') sender.send(message) return data[1] except: return "1"
def background_jobs(): mailer2 = Mailer(login_, password_) while True: db = TinyDB('database.json') print("background_jobs") tz = pytz.timezone('Asia/Kolkata') kolkata_now = datetime.now(tz) t = int(kolkata_now.strftime('%H%M')) print(t) for i in db.search(where('type') == 'notification'): if 0 <= t - i['time'] < 10: print(i) print('Sending notifications') output = extractPrice(i['source'], i['link']) history = get_history(i['link']) img = '' if history: times = [] prices = [] for i in history: times.append(i['time']) prices.append(i['price']) image = build_plot(times, prices) img = "<image src = '%s'>" % image print('Initializing mailer') mailer2.sendMail( i['email'], "Notification", '''<h3><a href="%s">%s</a></h3><br>The price at this moment is ₹%s<br>%s''' % (i['link'], i['name'], str(output), img)) time.sleep(60)
def outreach_first_api_call(sender, instance=None, **kwargs): try: if instance.application.first_active is not None: return if Token.objects.filter(application=instance.application).exists(): return if ArchivedToken.objects.filter( application=instance.application).exists(): return if Application.objects.filter( user=instance.application.user).count() != 1: return mailer = Mailer( subject='Congrats on Making Your First API Call', template_text='email/email-success-first-api-call-template.txt', template_html='email/email-success-first-api-call-template.html', to=[ instance.application.user.email, ], context={"FIRST_NAME": instance.application.user.first_name}) mailer.send() logger.info("Congrats on Making Your First API Call sent to %s (%s)" % (instance.application.user.username, instance.application.user.email)) except: # noqa logger.error( "Making Your First API Call Application failed send to %s (%s)" % (instance.application.user.username, instance.application.user.email))
def __init__(self, hs, pusherdict): self.hs = hs self.store = self.hs.get_datastore() self.clock = self.hs.get_clock() self.pusher_id = pusherdict['id'] self.user_id = pusherdict['user_name'] self.app_id = pusherdict['app_id'] self.email = pusherdict['pushkey'] self.last_stream_ordering = pusherdict['last_stream_ordering'] self.timed_call = None self.throttle_params = None # See httppusher self.max_stream_ordering = None self.processing = False if self.hs.config.email_enable_notifs: if 'data' in pusherdict and 'brand' in pusherdict['data']: app_name = pusherdict['data']['brand'] else: app_name = self.hs.config.email_app_name self.mailer = Mailer(self.hs, app_name) else: self.mailer = None
def turnOnLight(date, value): light(True) message = "lights is on at {}".format(datetime.datetime.now()) user = credentials["email"]["username"] password = credentials["email"]["password"] mailer = Mailer(user, password) mailer.send("*****@*****.**", "Light is on", message)
def send(self, from_address, to_address, subject, body=None, html=True): try: message = Message( From=from_address, To=to_address, charset=self.charset ) if body is None: body = '' self.body = body message.Subject = "%s - %s" % (self.subject_prefix, subject) message.Html = self.body message.Body = self.body except Exception as e: log.exception('[scaffold_mailer] - Failed to create message object for mailer') return False try: sender = Mailer( host=self.config.get('host'), port=self.config.get('port'), use_tls=self.config.get('use_tls', False), use_ssl=True, usr=self.config.get('username'), pwd=self.config.get('password')) sender.send(message) except Exception as e: log.exception('[scaffold_mailer] - Failed to connect to smtp sever and send message with subject: %s' % message.Subject) return False return True
def send_mail(query_records, addrs=None): """ Send an email for a set of records to a list of email addresses. """ addresses = addrs if addrs is None: addresses = ADDRESSES with open(SMTP_CONFIG) as conf: lines = conf.readlines() user = lines[0].strip() password = lines[1].strip() # Pretty-print the results! message_html = "" for (query, records) in query_records.items(): message_html += "<p>Items listed for \"" + query + "\"</p></br/>" table = tabulate( records, headers=['Date', 'What', 'Price', 'Where', 'Link']) message_html += "<pre>" + table + "</pre><br/><br/>" sender = '*****@*****.**' message = Message(From=sender, To=addresses, charset='utf-8') message.Subject = "Updates for East Bay Craigslist: \"" + "\", \"".join(query_records) + "\"" message.Html = message_html sender = Mailer('smtp.gmail.com:587', use_tls=True, usr=user, pwd=password) sender.send(message)
def alert_email(feed, cfg, entry): """Sends alert via email. Args: feed (:py:class:`Feed`): the feed cfg (dict): output config entry (dict): the feed entry """ logger = logging.LoggerAdapter(log, extra = { 'feed': feed.name, 'group': feed.group['name'], }) logger.debug(f"[{feed.name}] Alerting email: {entry.title}") description = strip_html(entry.description) try: smtp = Mailer(host=cfg['server']) message = Message(charset="utf-8", From=cfg['from'], To=cfg['to'], Subject = f"{feed.group['name']} Alert: ({feed.name}) {entry.title}") message.Body = f"Feed: {feed.name}\nDate: {entry.datestring}\n\n{description}" message.header('X-Mailer', 'rssalertbot') smtp.send(message) except Exception: logger.exception(f"[{feed.name}] Error sending mail")
def sendmail(mailto, subject, html='', text='', textfile='', htmlfile='', attachments=''): '''send mail''' if not mailto: print 'Error: Empty mailto address.\n' return mailto = [sb.strip() for sb in mailto.split(',')] if attachments: attachments = [att.strip() for att in attachments.split(',')] else: attachments = [] #USERNAME = hostname() subject = "%s-[%s]" % ( subject, hostname()) message = Message(From=USERNAME, To=mailto, Subject=subject, attachments=attachments) message.Body = text message.Html = html message.charset = 'utf8' try: if htmlfile: message.Html += open(htmlfile, 'r').read() if textfile: message.Body += open(textfile, 'r').read() except IOError: pass for att in attachments: message.attach(att) sender = Mailer(SERVER,port=465, use_tls=True, usr=USERNAME, pwd=PASSWD) #sender = Mailer(SERVER) #sender.login(USERNAME, PASSWD) sender.send(message)
def __init__(self): """Инициализация класса. Создать атрибуты self.mailer, self.hh, self.reporter. """ self.mailer = Mailer() self.hh = Hh() self.reporter = Reporter()
def send_reset_email(self): self.token = os.urandom(32).encode('hex') sender = Mailer('localhost', port=25) msg = Message(From="*****@*****.**", To=[self.email], charset="utf-8") msg.Subject = u'Accès trombinoscope ACR' msg.Body = _BODY % (unicode(self.token), unicode(self.login)) sender.send([msg])
def __init__(self, dart_config): email_config = dart_config['email'] self._env_name = dart_config['dart']['env_name'].upper() self._mailer = Mailer(**email_config['mailer']) self._from = email_config['from'] self._cc_on_error = email_config['cc_on_error'] self._debug = email_config.get('debug', False) self._suppress_send = email_config.get('suppress_send', False)
def emailSender(self): message = Message(From="*****@*****.**", To=["*****@*****.**"], Subject="University Management System") message.Body = """UMS deepanshu ahuja""" # message.attach("kitty.jpg") sender = Mailer('smtp.example.com') sender.send(message)
def send_email(msg): from mailer import Mailer, Message mail_msg = Message(From="监听者<%s>"%(os.environ["MAIL_ADDR"]), To=["*****@*****.**"], charset="utf-8") mail_msg.Subject = "Watchpmc Report" mail_msg.Html = msg sender = Mailer(host="smtp.yeah.net", usr=os.environ["MAIL_ADDR"], pwd=os.environ["MAIL_PASS"]) sender.send(mail_msg)
def _send(self, subject, htmlbody, textbody): for to in config().backupmailrecipients: logger().info("Sent backup report to [%s] via SMTP:%s" % (to, config().smtphost)) message = Message(From=config().backupmailfrom, To=to, charset="utf-8") message.Subject = subject message.Html = htmlbody message.Body = textbody sender = Mailer(config().smtphost) sender.send(message)
def sendEmail(toaddr, ccs, bccs, body, subject): """ 'sendEmail()' is called by 'feedConsumer()' when it is ready to send the e-mail to the specified recipient using SMTP; in case of failure to send, fallback gracefully to using the existing [email protected] account.""" mailer = Mailer('smtp.gmail.com', port=587, use_tls=True, usr="******", pwd="mailerbot") msg = Message(From="*****@*****.**", To=toaddr, CC=ccs, BCC=bccs, Body=body) msg.Subject = subject mailer.send(msg)
def send(self): """Send the email described by this object.""" message = Message(From=self.sender, To=self.to, charset="utf-8") message.Subject = self.subject message.Body = self.body mailer = Mailer(self.smtp_server) mailer.send(message)
def test_mailer(): mailer_message_1 = Mailer( sender="*****@*****.**", recipient_list=("*****@*****.**"), subject="Starlette-Vue mailer test", letter_body="<b>Hello world</b>", ) sending_result = mailer_message_1.send_email() assert True
def send_email(sender=REPORT_SENDER, recipient=REPORT_RECIPIENTS, subject='Reports finished', body=None): try: message = Message(From=sender, To=recipient, Subject=subject) message.Body = body sender = Mailer(EMAIL_RELAY) sender.send(message) except Exception as e: get_logger().error(e)
class EmailWatcher: def __init__(self, mail_settings_file_name, notification_address, sender_address): self._mailer = Mailer(mail_settings_file_name, 'KASA SmartPlug Power Manager', sender_address) self._notification_address = notification_address logging.info('Email notifications will be sent to %s' % self._notification_address) def notify_event(self, event_message): self._mailer.send_mail(self._notification_address, subject=event_message, message='SmartPlug power event at %s: %s' % (str(datetime.now()), event_message))
def _send(self, subject, htmlbody): for to in config().backupmailrecipients: logger().info("INFO: Sent backup report to [%s] via SMTP:%s" % (to, config().smtphost)) message = Message(From=config().backupmailfrom, To=to, charset="utf-8") message.Subject = subject message.Html = htmlbody message.Body = """This is an HTML e-mail with the backup overview, please use a HTML enabled e-mail client.""" sender = Mailer(config().smtphost) sender.send(message)
def send_btc_mail(subjectstring, messagestring): message = Message(From=settings.MAILSENDER, To=settings.TOLIST, charset="utf-8") message.Subject = subjectstring message.Html = messagestring mysender = Mailer(host=settings.MAILHOST, pwd=settings.MAILPWD, usr=settings.MAILSENDER) mysender.send(message)
def send_mail(self): message = Message(From=self.fr, To=self.to, Subject=self.sub, Charset='utf8') message.Body = self.body sender = Mailer(host=self.server,usr=self.usr,pwd=self.pwd) sender.send(message)
def send(self): message = Message(From=self.render(self.sender), To=self.render(self.to), Subject=self.render(self.subject), charset='utf-8') message.Body = self.render_file(self.template) message.Html = self.render_file(self.html_template) mailer = Mailer(**self.mailer_settings) mailer.send(message)
def send(self, from_address, to_address, subject, body='', html=True): message = Message(From="*****@*****.**", To=to_address, charset=self.charset) message.Subject = "%sAn HTML Email" % self.subject_prefix message.Html = body message.Body = body sender = Mailer(self.host) sender.send(message)
def verify_email(user): # logger.debug("Generated email verification link: " + user.reg_id) # if not user.active: message = Message(From="*****@*****.**",To="*****@*****.**",charset="utf-8") message.Subject = "Flotag Email Verification" message.Html = """This email uses <strong>Complete Flotag Registration</strong>!""" message.Body = """Flotag Registration""" sender = Mailer('127.0.0.1') sender.send(message)
def __init__(self) -> None: """ Initialising CertHandler instance. Script will exit here if there is no internet connection. """ self.cert_getter = CertGetter() self.mailer = Mailer() self.sites_to_notify = [] if not self.check_conn(): sys.exit("Can't establish Internet connection. Bye bye!")
def sendMail(item, hwp): sender = Mailer('smtp.gmail.com',use_tls=True) for to in MAILER_TO : sender.login(MAILER_USERNAME,MAILER_PASSWORD) message = Message(From='*****@*****.**', To=to) message.Subject = "가정통신문 :%s"%item['title'].encode('utf-8') message.Html = "" if hwp: message.attach(hwp) sender.send(message)
def send_email(email_txt, attach, subject=None): mail = Mailer(email=config['email']['sender'], password=config['email']['senderpwd']) mail.send( receiver=config['email']['receiver'], bcc=config['email']['bcc'], subject=config['email']['subject'] if subject is None else subject, message=email_txt, file=attach)
def send(self): body = self.body.getText() user = self.tuser.getText() passwd = self.tpasswd.getText() o = Mailer(user=user, passwd=passwd) if o.send(to="*****@*****.**", subject="Jython", body=body) == {}: self.body.setText("") else: pass
def send_email(self): try: message = self.message message = Message(From="localhost", To="*****@*****.**") message.Subject = "An HTML Email" message.Html = """<p>Hello!<br>The pipeline has failed Fix this and rerun it again message</p>""" sender = Mailer('localhost') sender.send(message) except TestFailed as message: print(message)
def send_mail(html, body, frm, receivers, subject): from mailer import Mailer from mailer import Message message = Message(From=frm, To= receivers, BCC = [], charset="utf-8") message.Subject = subject message.Html = html message.Body = body sender = Mailer(host = "smtp.gmail.com", port = 587, use_tls = True, usr = "******", pwd = "Learning36") sender.send(message)
def sendEmailTest(): from mailer import Mailer from mailer import Message message = Message(From="*****@*****.**", To="*****@*****.**") message.Subject = "An HTML Email" message.Html = """<p>Hi!<br> How are you?<br> Here is the <a href="http://172.16.2.249/kpi-android-cn.html">link</a>you wanted.</p>""" sender = Mailer("mail.bainainfo.com") sender.send(message)
def main(): rev = test_rev.get_rev('./') message = Message(From="*****@*****.**", To="*****@*****.**", charset="utf-8") message.Subject = "HYMLS test results for revision " + rev message.Body = dataparser.compare(rev) sender = Mailer('smtp.rug.nl') sender.send(message)
def send_email(image): # Format email message message = Message(From=MAIL_FROM,To=MAIL_TO) message.Subject = MAIL_SUBJECT message.Html = MAIL_HTML message.Body = MAIL_BODY message.attach(image) # Send message to SMTP server sender = Mailer(SMTP_HOST) sender.send(message)
def send(url, email): """Sends a html page to an email. Requires a local smtp server and the mailer module""" html = urllib2.urlopen(url).read() mail = Message(From = "test", To = email, charset='UTF-8') mail.Subject = "Test email" mail.Html = html sender = Mailer() sender.send(mail)
def send_email(image): # Format email message message = Message(From=MAIL_FROM, To=MAIL_TO) message.Subject = MAIL_SUBJECT message.Html = MAIL_HTML message.Body = MAIL_BODY message.attach(image) # Send message to SMTP server sender = Mailer(SMTP_HOST) sender.send(message)
def send_email(from_email, to_email_list, subject, html, smtp_host, smtp_port=587, username=None, password=None): message = Message(From=from_email, To=to_email_list, charset='utf-8') # Keep from creating threads in gmail... message.Subject = "{} -- {}".format(subject, datetime.now().strftime('%Y-%m-%dT%H:%M:%S')) message.Html = html.encode('utf-8') message.Body = 'See the HTML!' sender = Mailer(host=smtp_host, port=smtp_port, use_tls=True, usr=username, pwd=password) if username is not None: sender.login(username, password) sender.send(message)
def send_mail(subject, contents, host, use_ssl, sender, pwd, email_address): message = Message(From=sender, To=email_address, charset="utf-8") message.Subject = subject message.Html = contents sender = Mailer(host=host, use_ssl=use_ssl, usr=sender[:sender.find("@")], pwd=pwd) sender.send(message, debug=False) log.info("sender:%s,to=%s" % (sender, email_address))
def send_email(self): """Envia el correo""" sender = Mailer("smtp.gmail.com", 587, True) sender.login("*****@*****.**", "90062957564") try: sender.send(self.message) except smtplib.AMTPAuthenticationError as Error: print(Error) return False except IOError as (error_string, error_number): print(str(error_string) + " " + str(error_number)) return False
def __init__(self, id_, password, recipient, subject, body_html): self.message = Message(From=id_ + "@gmail.com", To=recipient, charset="utf-8") self.message.Subject = subject self.message.Html = body_html self.sender = Mailer("smtp.gmail.com", port=587, usr=id_ + "@gmail.com", pwd=password, use_tls=True)
def send_feedback_mail(version, username, feedback, logcat): # noinspection PyBroadException try: msg = Message(From=args.user, To=args.receiver, charset="utf8") msg.Subject = u"Feedback {} ({})".format(version, username) msg.Body = u"User: {0} http://pr0gramm.com/user/{0}\nFeedback: {1}\n\nLogcat: {2}\n".format(username, feedback, logcat) mailer = Mailer(args.host, port=587, use_tls=True, usr=args.user, pwd=args.password) mailer.send(msg) except: traceback.print_exc()
def send_report(self, message, post): sender = Mailer(host=settings.host, port=settings.port, usr=settings.username, pwd=settings.password, use_tls=settings.tls) email = Message(From=message['reportAddress'], To=message['reportAddress'], Subject='craigslist-auto-{}'.format(datetime.datetime.now())) html = 'Sent message to: <a href="{}">{}</a>\n'.format(post['url'], post['url']) html += 'Message Details:\nSubject: {} \nBody:\n{}'.format(message['subject'], message['body']) email.Html = html print 'Sending report for {}'.format(post['id']) sender.send(email)
def send_auth_email(email, auth_url): logger.info("Login here to use Spotify API: %s", auth_url) mailer = Mailer(**config.email) # pylint: disable=no-member html_content = LOGIN_HTML.read_text().replace( "SPOTIFY_AUTHENTICATION_URL", auth_url ) message = Message(From=config.email.usr or email, To=email, charset="utf-8") message.Subject = "Spotify API Authentication" message.Html = html_content message.Body = f"Login here to use Spotify API: {auth_url}" mailer.send(message)
def test_create_mail__text_two_recipients(self): mail = MailData() mail.recipients = ["*****@*****.**", "*****@*****.**"] mail.subject = "Test mail" mail.body = "Test body" mailer = Mailer() result = mailer.create_mail(mail) self.assertEqual("[email protected], [email protected]", result["To"]) self.assertEqual(mail.subject, result["Subject"]) self.assertFalse(result.is_multipart()) self.assertEqual("text/plain", result.get_content_type()) self.assertEqual(mail.body, result.get_payload())
def send_reply(self, message, toAddress): sender = Mailer(host=settings.host, port=settings.port, usr=settings.username, pwd=settings.password, use_tls=settings.tls) email = Message(From=message['fromAddress'], To=toAddress, Subject=message['subject'], CC=message['ccAddress']) email.Html = message['body'] messageUploads = '{}/{}/attachments/'.format(self.uploadsBasePath, message['_id']) for upload in os.listdir(messageUploads): email.attach('{}{}'.format(messageUploads, upload)) print 'Sending {} to {}'.format(message['subject'], toAddress) sender.send(email)