def test_message_build(): # Test simple build m = emails.Message(**common_email_data()) assert m.as_string() # If no html or text - raises ValueError with pytest.raises(ValueError): emails.Message().as_string() # Test file-like html and text m = emails.Message(html=StringIO('X'), text=StringIO('Y')) assert m.html == 'X' assert m.text == 'Y'
def __send_login_email(self, email, ip): """ Send a validation email (tries 2 times) to a user to notice them to activate the account :param activation_hash: generated hash for activation :param email: the email were the activation link will be sent :return: """ self.logger.info("Will send email to {}".format(email)) self.logger.info("Got ip of req: {}".format(ip)) url = 'http://0.0.0.0:16000/api/login' for i in range(5): m = emails.Message( html='<html>New login on from ip <a href="%s"></a></html>' % (ip, ), subject='Keep it app. New login!', mail_from='') r = m.send(smtp={ 'host': 'smtp.gmail.com', 'tls': True, 'user': '', 'password': '' }, to=email) if r.status_code not in (250, ) and i != 1: self.logger.info("Email sending error: {}".format( r.status_code)) time.sleep(5) else: break
def send_email(email_to: str, subject_template="", html_template="", environment={}): if not settings.EMAILS_ENABLED: if settings.EMAIL_TESTING: logging.info("\nMessage: " + subject_template + "\nSent to: " + email_to) return raise HTTPException(status_code=HTTP_403_FORBIDDEN, detail="Emails not enabled.") message = emails.Message( subject=JinjaTemplate(subject_template), html=JinjaTemplate(html_template), mail_from=(settings.EMAILS_FROM_NAME, settings.EMAILS_FROM_EMAIL), ) smtp_options = {"host": settings.SMTP_HOST, "port": settings.SMTP_PORT} if settings.SMTP_TLS: smtp_options["tls"] = True if settings.SMTP_USER: smtp_options["user"] = settings.SMTP_USER if settings.SMTP_PASSWORD: smtp_options["password"] = settings.SMTP_PASSWORD response = message.send(to=email_to, render=environment, smtp=smtp_options) logging.info(f"send email result: {response}")
def _prepare_message_body(self) -> dict: html = plain = None # type: Optional[str] if self._html: html = self._html if not self._text: plain = self._html_to_plaintext(self._html) if self._text: plain = self._text if not self._html: html = f"<pre>{escape(self._text)}</pre>" msg = emails.Message(subject=self._subject, mail_from=self._from, mail_to=self._to, html=html, text=plain, cc=self._cc, bcc=self._bcc, headers=None, charset="utf-8") for attachment in self._attachments: msg.attach(filename=attachment.name, data=attachment.path.read_bytes()) body = { "raw": Base64(raw_bytes=msg.build_message().as_bytes()).to_b64() } if self.parent is not None: body["threadId"] = self.parent.thread_id return body
def send(self): message = emails.Message( html=self.__html, text=self.__text, subject=self.__subject, mail_from=(self.__from_name if self.__from_name is not None else self.__config['from_name'], self.__from_email if self.__from_email is not None else self.__config['from_email']), cc=self.__cc, bcc=self.__bcc) for file_attach in self.__files_attachments: message.attach(data=open(file_attach['file'], 'rb'), filename=file_attach['filename']) for string_attach in self.__strings_attachments: buffer = BytesIO() b = bytearray() b.extend(string_attach['data'].encode()) buffer.write(b) buffer.seek(0) message.attach(data=buffer, filename=string_attach['filename']) response = message.send(to=self.__to, smtp={ 'host': self.__config['host'], 'port': self.__config['port'], 'tls': self.__config['tls'], 'user': self.__config['user'], 'password': self.__config['password'] }) return True if response.status_code == 250 else False
def send_validation_mail(self, email, activation_hash): """ Send a validation email (tries 2 times) to a user to notice them to activate the account :param activation_hash: generated hash for activation :param email: the email were the activation link will be sent :return: """ url = 'http://127.0.0.1:16000/activation' for i in range(2): m = emails.Message( html= '<html>To activate your account <a href="%s/%s">click here</a></html>' % (url, activation_hash), subject='Activate your account!', mail_from='*****@*****.**') r = m.send(render={ 'url': url, 'hash': activation_hash }, smtp={ 'host': 'smtp.gmail.com', 'tls': True, 'user': '******', 'password': '******' }, to=email) if r.status_code not in (250, ) and i != 1: time.sleep(5) else: break
def get_letters(): # Test email with attachment URL = 'http://lavr.github.io/python-emails/tests/campaignmonitor-samples/sample-template/images/gallery.png' data = common_email_data(subject='Single attachment', attachments=[ emails.store.LazyHTTPFile(uri=URL), ]) yield emails.html(**data), None # Email with render yield emails.html(**common_email_data(subject='Render with name=John')), { 'name': u'John' } # Email with several inline images url = 'http://lavr.github.io/python-emails/tests/campaignmonitor-samples/sample-template/template-widgets.html' data = common_email_data(subject='Sample html with inline images') del data['html'] yield emails.loader.from_url(url=url, message_params=data, images_inline=True), None # Email with utf-8 "to" yield emails.Message( **common_email_data(mail_to="anaï[email protected]", subject="UTF-8 To")), None
def send_email( email_to: str, subject_template: str = "", html_template: str = "", environment: Dict[str, Any] = {}, ) -> None: assert settings.EMAILS_ENABLED, "no provided configuration for email variables" message = emails.Message( subject=JinjaTemplate(subject_template), html=JinjaTemplate(html_template), mail_from=(settings.EMAILS_FROM_NAME, settings.EMAILS_FROM_EMAIL), ) smtp_options = {"host": settings.SMTP_HOST, "port": settings.SMTP_PORT} if settings.SMTP_TLS: smtp_options["tls"] = True if settings.SMTP_SSL: smtp_options["ssl"] = True if settings.SMTP_USER: smtp_options["user"] = settings.SMTP_USER if settings.SMTP_PASSWORD: smtp_options["password"] = settings.SMTP_PASSWORD response = message.send(to=email_to, render=environment, smtp=smtp_options) print(response) logging.info(f"send email result: {response}")
def send_email(email_to: str, subject_template="", html_template="", environment=None) -> Union[SMTPResponse, bool]: if environment is None: environment = {} assert config.EMAILS_ENABLED, "no provided configuration for email variables" message = emails.Message( subject=JinjaTemplate(subject_template), html=JinjaTemplate(html_template), mail_from=(config.EMAILS_FROM_NAME, config.EMAILS_FROM_EMAIL), ) smtp_options = {"host": config.SMTP_HOST, "port": config.SMTP_PORT} if config.SMTP_TLS: smtp_options["tls"] = True if config.SMTP_USER: smtp_options["user"] = config.SMTP_USER if config.SMTP_PASSWORD: smtp_options["password"] = config.SMTP_PASSWORD try: response = message.send(to=email_to, render=environment, smtp=smtp_options) assert response.status_code == 250 logging.info(f"Send email result: {response}") except SMTPException as error: logging.error(f"Error while trying to send email: {error}") return False except AssertionError: logging.error(f"Failed to send email, send email result: {response}") return False return response
def send_email(func, target, code): if func == settings.FUNCTION_REGISTER: content = T(u"<html><p>您正在进行用户注册操作,验证码 {{ code }},请在 15 分钟内按提示提交验证码。") elif func == settings.FUNCTION_UPDATE: content = T(u"<html><p>您正在进行手机号更新操作,验证码 {{ code }},请在 15 分钟内按提示提交验证码。") elif func == settings.FUNCTION_RESET: content = T(u"<html><p>您正在进行密码重置操作,验证码 {{ code }},请在 15 分钟内按提示提交验证码。") else: logger.warning('invalid function parameter %s' % func) return m = emails.Message( html=content, subject=T(u"随阅易手机阅读 - 验证码"), mail_from=(u"随阅易手机阅读", settings.SMTP_FROM), ) response = m.send( render={ "code": code, }, to=target, smtp={ "host": settings.SMTP_SERVER, "port": settings.SMTP_PORT, 'ssl': True, 'user': settings.SMTP_FROM, 'password': settings.SMTP_PASSWORD, }, ) if response.status_code not in [250, ]: logger.warning('cannot send email, target=%s, code=%s. %s' % (target, code, str(response))) return logger.info('email has sent, target=%s, code=%s' % (target, code))
def send_email( email_to: str, subject_template: str = "", html_template: str = "", environment: Dict[str, Any] = {}, ) -> None: assert current_app.config[ "EMAILS_ENABLED"], "no provided configuration for email variables" message = emails.Message( subject=JinjaTemplate(subject_template), html=JinjaTemplate(html_template), mail_from=(current_app.config["EMAILS_FROM_NAME"], current_app.config["EMAILS_FROM_EMAIL"]), ) smtp_options = { "host": current_app.config["MAIL_SERVER"], "port": current_app.config["MAIL_PORT"] } if current_app.config["MAIL_USE_TLS"]: smtp_options["tls"] = True if current_app.config["MAIL_USERNAME"]: smtp_options["user"] = current_app.config["MAIL_USERNAME"] if current_app.config["MAIL_PASSWORD"]: smtp_options["password"] = current_app.config["MAIL_PASSWORD"] response = message.send(to=email_to, render=environment, smtp=smtp_options) logging.info(f"send email result: {response}")
def test_message_policy(): if is_py34_plus: def gen_policy(**kw): import email.policy return email.policy.SMTP.clone(**kw) # Generate without policy m1 = emails.Message(**common_email_data()) m1.policy = None # Just generate without policy m1.as_string() # Generate with policy m1 = emails.Message(**common_email_data()) m1.policy = gen_policy(max_line_length=60)
def test_before_build(): def my_before_build(message): message.render_data['x-before-build'] = 1 m = emails.Message(**common_email_data()) m.before_build = my_before_build s = m.as_string() assert m.render_data['x-before-build'] == 1
def send_email(mail_to, subject='Registration', text='Welcome'): message = emails.Message(mail_from=EmailConfig.HOST_USER, mail_to=mail_to, subject=subject, text=text) resp = message.send(smtp=EmailConfig.make_config()) if resp.status_code not in (250, ): raise ValueError('Email was not sent correctly')
def test_sanitize_header(): for header, value in ( ('subject', 'test\n'), ('headers', { 'X-Header': 'test\r' }), ): with pytest.raises(emails.exc.BadHeaderError): print('header {0}'.format(header)) emails.Message(html='...', **{header: value}).as_message()
def send_email(email_to: str, subject_template: str = "", html_template: str = "", environment: Dict[str, Any] = {}) -> None: message = emails.Message(subject=JinjaTemplate(subject_template), html=JinjaTemplate(html_template), mail_from=(None, None)) smtp_options = {"host": config.SMTP_HOST, "port": config.SMTP_PORT} response = message.send(to=email_to, render=environment, smtp=smtp_options) logging.info(f"send email result: {response}")
def send_email(self, subject, message, files=[]): if self.email is None: return htmlbody = '<html><head><title>{}</title></head><body><img src="cid:{}" alt="Profile image" title="Profile image" align="right" style="max-width:300px;border-radius:25%;">{}</body></html>' for receiver in self.email['receiver']: mail_tls_ssl = ['tls', 'ssl', None] while not len(mail_tls_ssl) == 0: email_message = emails.Message( headers={ 'X-Mailer': 'TerrariumPI version {}'.format(self.__version) }, html=htmlbody.format( subject, os.path.basename(self.__profile_image), message.decode().replace('\n', '<br />')), text=message, subject=subject, mail_from=('TerrariumPI', receiver)) with open(self.__profile_image, 'rb') as fp: profile_image = fp.read() email_message.attach(filename=os.path.basename( self.__profile_image), content_disposition="inline", data=profile_image) for attachment in files: with open(attachment, 'rb') as fp: attachment_data = fp.read() email_message.attach( filename=os.path.basename(attachment), data=attachment_data) smtp_settings = {'host': self.email['server'], 'port': 25} if '' != self.email['serverport']: smtp_settings['port'] = self.email['serverport'] smtp_security = mail_tls_ssl.pop(0) if smtp_security is not None: smtp_settings[smtp_security] = True if '' != self.email['username']: smtp_settings['user'] = self.email['username'] smtp_settings['password'] = self.email['password'] response = email_message.send(to=re.sub( r'(.*)@(.*)', '\\1+terrariumpi@\\2', receiver, 0, re.MULTILINE), smtp=smtp_settings) if response.status_code == 250: # Mail sent, clear remaining connection types mail_tls_ssl = []
def _create_message_from_template(self, mail_to, subject, template_path, cc, bcc, templates_encoding): mail_from = self.smtp_settings.sender full_template_path = path.join(self.templates_path, template_path) with io.open(full_template_path, 'r', encoding=templates_encoding) as file: template_content = file.read() file.close() message = emails.Message( mail_from=mail_from, mail_to=mail_to, cc=cc, bcc=bcc, subject=T(subject), html=T(template_content)) return message
def send_email(self, html, subject, recipients, ccrecipients=None, attachments=None): """ Send an email. recipients and ccrecipients is a list of address-like elements, i.e.: * "name <email>" * "email" * (name, email) """ message = emails.Message(html=html, subject=subject, mail_from=(self._fromuser, self._fromemail), mail_to=recipients, cc=ccrecipients) if attachments: for attachment in attachments: self._add_log( 'Attempting to attach file: {0}'.format(attachment)) filename = os.path.split(attachment)[1] message.attach(filename=filename, data=open(attachment, 'rb')) if self._smtplogin: self._add_log( 'Attempting to use SMTP with authentication to: {0}:{1}'. format(self._smtphost, self._port)) smtp = { 'host': self._smtphost, 'port': self._port, 'ssl': self._ssl, 'user': self._smtplogin, 'password': self._smtppass } else: self._add_log( 'Attempting to use SMTP without authentication to: {0}:{1}'. format(self._smtphost, self._port)) smtp = {'host': self._smtphost, 'port': self._port} save_html = os.getenv('AWS_AWARE_SAVE_EMAIL', False) if save_html: htmlfilepath = os.path.join(os.getcwd(), 'aws-instance-report.html') outputfile = open(htmlfilepath, "w") outputfile.write(html) outputfile.close() result = message.send(to=recipients, smtp=smtp) assert result.status_code == 250
def send(email, subject=None, from_email=None, to_email=None, cc=None, bcc=None, reply_to=None, smtp=None): """Send markdown email Args: email (str/obj): A markdown string or EmailContent object subject (str): subject line from_email (str): sender email address to_email (str/list): recipient email addresses cc (str/list): CC email addresses (string or a list) bcc (str/list): BCC email addresses (string or a list) reply_to (str): Reply-to email address smtp (dict): SMTP configuration (dict) Schema of smtp dict: host (str): SMTP server host. Default: localhost port (int): SMTP server port. Default: 25 tls (bool): Use TLS. Default: False ssl (bool): Use SSL. Default: False user (bool): SMTP login user. Default empty password (bool): SMTP login password. Default empty """ if is_string(email): email = EmailContent(email) from_email = sanitize_email_address(from_email or email.headers.get('from')) to_email = sanitize_email_address(to_email or email.headers.get('to')) cc = sanitize_email_address(cc or email.headers.get('cc')) bcc = sanitize_email_address(bcc or email.headers.get('bcc')) reply_to = sanitize_email_address(reply_to or email.headers.get('reply-to')) message_args = { 'html': email.html, 'text': email.text, 'subject': (subject or email.headers.get('subject', '')), 'mail_from': from_email, 'mail_to': to_email } if cc: message_args['cc'] = cc if bcc: message_args['bcc'] = bcc if reply_to: message_args['headers'] = {'reply-to': reply_to} message = emails.Message(**message_args) for filename, data in email.inline_images: message.attach(filename=filename, content_disposition='inline', data=data) message.send(smtp=smtp)
def send_email(email_to: str, subject_template='', html_template='', context: dict = {}): assert settings.EMAILS_ENABLED, 'please configure email backend to send emails' message = emails.Message(subject=JinjaTemplate(subject_template), html=JinjaTemplate(html_template), mail_from=(settings.EMAIL_FROM_NAME, settings.EMAIL_FROM_EMAIL)) smtp_options = {'host': settings.SMTP_HOST, 'port': settings.SMTP_PORT, 'user': settings.EMAIL_HOST_USER, 'password': settings.EMAIL_HOST_PASSWORD} if settings.SMTP_TLS: smtp_options['tls'] = True message.send(email_to, render=context, smtp=smtp_options)
def test_after_build(): AFTER_BUILD_HEADER = 'X-After-Build' def my_after_build(original_message, built_message): built_message[AFTER_BUILD_HEADER] = '1' kwargs = common_email_data() m = emails.Message(**kwargs) m.after_build = my_after_build s = m.as_string() print("type of message.as_string() is {0}".format(type(s))) assert AFTER_BUILD_HEADER in to_unicode(s, 'utf-8')
def send_email( self, email_to: str, subject: str, template: str, ) -> int: message = emails.Message( subject=subject, html=template, mail_from=(config.get_email_name(), config.get_smtp_user()), ) logging.info(f"Sending email to {email_to} with subject: {subject}") response = message.send(to=email_to, smtp=self.smtp_options) logging.info(f"Email sent, service response: {response}") return response.status_code
def send_email(email_to: str, subject_template="", html_template="", environment={}): assert config.EMAILS_ENABLED, "no provided configuration for email variables" message = emails.Message( subject=JinjaTemplate(subject_template), html=JinjaTemplate(html_template), mail_from=(config.EMAILS_FROM_NAME, config.EMAILS_FROM_EMAIL), ) smtp_options = {"host": config.SMTP_HOST, "port": config.SMTP_PORT} if config.SMTP_TLS: smtp_options["tls"] = True if config.SMTP_USER: smtp_options["user"] = config.SMTP_USER if config.SMTP_PASSWORD: smtp_options["password"] = config.SMTP_PASSWORD response = message.send(to=email_to, render=environment, smtp=smtp_options) logging.info(f"send email result: {response}")
def send_email(email_to: str, subject_template: str = "", html_template: str = "", environment: Dict[str, Any] = {}) -> None: assert settings.EMAIL_ENABLED, "no provided configuration for email variables" message = emails.Message(subject=JinjaTemplate(subject_template), html=JinjaTemplate(html_template), mail_from=(settings.EMAIL_FROM_NAME, settings.EMAIL_FROM_ADDRESS)) smtp_options = {"host": settings.SMTP_HOST, "port": settings.SMTP_PORT} if settings.SMTP_TLS: smtp_options["tls"] = True if settings.SMTP_USER: smtp_options["user"] = settings.SMTP_USER if settings.SMTP_PASSWORD: smtp_options["password"] = settings.SMTP_PASSWORD message.send(to=email_to, render=environment, smtp=smtp_options)
def send_email( email_to: str, subject_template: str = "", html_template: str = "", environment=None, ) -> None: """ send email to some mail address :param email_to: send to this email :param subject_template: email subject :param html_template: email content :param environment: template params :return: email send response """ if environment is None: environment = {} assert settings.EMAILS_ENABLED, "no provided configuration for email variables" # email message message = emails.Message( subject=T(subject_template), html=T(html_template), mail_from=(settings.EMAILS_FROM_NAME, settings.EMAILS_FROM_EMAIL), ) # smtp server smtp_options = {"host": settings.SMTP_HOST, "port": settings.SMTP_PORT} if settings.SMTP_SSL: smtp_options["ssl"] = True if settings.SMTP_USER: smtp_options["user"] = settings.SMTP_USER if settings.SMTP_PASSWORD: smtp_options["password"] = settings.SMTP_PASSWORD # send response = message.send(to=email_to, render=environment, smtp=smtp_options) if response.status_code not in [ 250, ]: logger.info(f"send email failed {response}") else: logger.info(f"send email to {email_to} successfully")
def send(self): message = emails.Message(html=self.notification.html_body, text=self.notification.body, mail_from=self.notification.from_address, mail_to=self.notification.recipients, cc=self.notification.cc_recipients, bcc=self.notification.bcc_recipients, subject=self.notification.subject) settings = { 'host':self.settings.host, 'port': self.settings.port, 'ssl': self.settings.mode == 'ssl', 'tls': self.settings.mode == 'tls', 'user': str(self.settings.username), 'password': str(self.settings.password) } self.last_result = message.send(smtp=settings) return self.last_result and self.last_result.status_code == 250
def send_email(self, message): if strtobool(self.config["emailnotifications"]["enabled"]) == 0: return smtp = { "host": self.config["emailnotifications"]["server"], "port": self.config["emailnotifications"]["port"], "user": self.config["emailnotifications"]["username"], "password": self.config["emailnotifications"]["password"] } m = emails.Message( text=message, subject=self.config["emailnotifications"]["subject"], mail_from=(self.config["emailnotifications"]["from"], self.config["emailnotifications"]["from_address"])) response = m.send(to=self.config["emailnotifications"]["to"], smtp=smtp)
def send_email(template, subject, data_map, recipient): template_path = os.path.join(os.path.dirname(os.path.abspath(__file__)), "..", "email_templates", template) smtp_config = { 'host': CONFIG.smtp_host, 'port': CONFIG.smtp_port, 'user': CONFIG.smtp_user, 'password': CONFIG.smtp_pass, 'ssl': True } message = emails.Message(html=JinjaTemplate(open(template_path).read()), subject=subject, mail_from=("VulnFeed Agent", "*****@*****.**")) if CONFIG.has_dkim: message.dkim(key=open(CONFIG.dkim_privkey), domain=CONFIG.dkim_domain, selector=CONFIG.dkim_selector) response = message.send(render=data_map, to=recipient, smtp=smtp_config) return response
def send_messages(self, message_list): try: for msg in message_list: full_msg = emails.Message(html=msg['msg_html'], subject=msg['msg_subject'], mail_from=self.imap_login) response = full_msg.send(to=self.mail_to, smtp={ 'host': self.smtp_server, 'ssl': True, 'user': self.smtp_login, 'password': self.smtp_password }) logger("Sending message status: {}".format(response), "INFO") if response.status_code != 250: logger("Some error occured: {}".format(response.error), "ERROR") except Exception: logger(traceback.format_exc(), "EXCEPTION")