def raise_smtp(reg_profile): raise SMTPRecipientsRefused(recipients=[reg_profile.user.email])
def emailmessage_raise_smtp(): raise SMTPRecipientsRefused(recipients=[])
def raise_smtp(*a, **kw): raise SMTPRecipientsRefused(recipients=[self.u.email])
def mailPassword(self, login, REQUEST, immediate=False): """ Wrapper around mailPassword """ membership = getToolByName(self, 'portal_membership') if not membership.checkPermission('Mail forgotten password', self): raise Unauthorized( _(u"Mailing forgotten passwords has been disabled.")) utils = getToolByName(self, 'plone_utils') member = get_member_by_login_name(self, login, raise_exceptions=False) if member is None: raise ValueError( _(u'The username you entered could not be found.')) # Make sure the user is allowed to set the password. portal = getToolByName(self, 'portal_url').getPortalObject() acl_users = getToolByName(portal, 'acl_users') user = acl_users.getUserById(member.getId()) orig_sm = getSecurityManager() try: newSecurityManager(REQUEST or self.REQUEST, user) tmp_sm = getSecurityManager() if not tmp_sm.checkPermission(SetOwnPassword, portal): raise Unauthorized( _(u"Mailing forgotten passwords has been disabled.")) finally: setSecurityManager(orig_sm) # assert that we can actually get an email address, otherwise # the template will be made with a blank To:, this is bad email = member.getProperty('email') if not email: raise ValueError(_(u'That user does not have an email address.')) else: # add the single email address if not utils.validateSingleEmailAddress(email): raise ValueError(_(u'The email address did not validate.')) check, msg = _checkEmail(email) if not check: raise ValueError(msg) # Rather than have the template try to use the mailhost, we will # render the message ourselves and send it from here (where we # don't need to worry about 'UseMailHost' permissions). reset_tool = getToolByName(self, 'portal_password_reset') reset = reset_tool.requestReset(member.getId()) registry = getUtility(IRegistry) encoding = registry.get('plone.email_charset', 'utf-8') mail_text = self.mail_password_template( self, REQUEST, member=member, reset=reset, password=member.getPassword(), charset=encoding) # The mail headers are not properly encoded we need to extract # them and let MailHost manage the encoding. if isinstance(mail_text, unicode): mail_text = mail_text.encode(encoding) message_obj = message_from_string(mail_text.strip()) subject = message_obj['Subject'] m_to = message_obj['To'] m_from = message_obj['From'] msg_type = message_obj.get('Content-Type', 'text/plain') host = getToolByName(self, 'MailHost') try: host.send(mail_text, m_to, m_from, subject=subject, charset=encoding, immediate=immediate, msg_type=msg_type) except SMTPRecipientsRefused: # Don't disclose email address on failure raise SMTPRecipientsRefused( _(u'Recipient address rejected by server.')) except SMTPException as e: raise(e) # return the rendered template "mail_password_response.pt" # (in Products.PasswordResetTool) return self.mail_password_response(self, REQUEST)
def send_mail_raise_smtp(subject, content, from_emal, recipients): """Patch mail.send_mail with this in your tests to check what happens when an email fails to send.""" raise SMTPRecipientsRefused(recipients=recipients)
def fail(from_addr, to_addrs, msg): raise SMTPRecipientsRefused(mock)
def sendmail(self, from_addr, to_addrs, msg, mail_options=[], rcpt_options=[]): """This command performs an entire mail transaction. The arguments are: - from_addr : The address sending this mail. - to_addrs : A list of addresses to send this mail to. A bare string will be treated as a list with 1 address. - msg : The message to send. - mail_options : List of ESMTP options (such as 8bitmime) for the mail command. - rcpt_options : List of ESMTP options (such as DSN commands) for all the rcpt commands. msg may be a string containing characters in the ASCII range, or a byte string. A string is encoded to bytes using the ascii codec, and lone \\r and \\n characters are converted to \\r\\n characters. If there has been no previous EHLO or HELO command this session, this method tries ESMTP EHLO first. If the server does ESMTP, message size and each of the specified options will be passed to it. If EHLO fails, HELO will be tried and ESMTP options suppressed. This method will return normally if the mail is accepted for at least one recipient. It returns a dictionary, with one entry for each recipient that was refused. Each entry contains a tuple of the SMTP error code and the accompanying error message sent by the server. This method may raise the following exceptions: SMTPHeloError The server didn't reply properly to the helo greeting. SMTPRecipientsRefused The server rejected ALL recipients (no mail was sent). SMTPSenderRefused The server didn't accept the from_addr. SMTPDataError The server replied with an unexpected error code (other than a refusal of a recipient). SMTPNotSupportedError The mail_options parameter includes 'SMTPUTF8' but the SMTPUTF8 extension is not supported by the server. Note: the connection will be open even after an exception is raised. Example: >>> import smtplib >>> s=smtplib.SMTP("localhost") >>> tolist=["*****@*****.**","*****@*****.**","*****@*****.**","*****@*****.**"] >>> msg = '''\\ ... From: [email protected] ... Subject: testin'... ... ... This is a test ''' >>> s.sendmail("*****@*****.**",tolist,msg) { "*****@*****.**" : ( 550 ,"User unknown" ) } >>> s.quit() In the above example, the message was accepted for delivery to three of the four addresses, and one was rejected, with the error code 550. If all addresses are accepted, then the method will return an empty dictionary. """ self.ehlo_or_helo_if_needed() esmtp_opts = [] if isinstance(msg, str): msg = _fix_eols(msg).encode('ascii') if self.does_esmtp: if self.has_extn('size'): esmtp_opts.append("size=%d" % len(msg)) for option in mail_options: esmtp_opts.append(option) (code, resp) = self.mail(from_addr, esmtp_opts) if code != 250: if code == 421: self.close() else: self._rset() raise SMTPSenderRefused(code, resp, from_addr) senderrs = {} if isinstance(to_addrs, str): to_addrs = [to_addrs] for each in to_addrs: (code, resp) = self.rcpt(each, rcpt_options) if (code != 250) and (code != 251): senderrs[each] = (code, resp) if code == 421: self.close() raise SMTPRecipientsRefused(senderrs) if len(senderrs) == len(to_addrs): # the server refused all our recipients self._rset() raise SMTPRecipientsRefused(senderrs) (code, resp) = self.data(msg) if code != 250: if code == 421: self.close() else: self._rset() raise SMTPDataError(code, resp) #if we got here then somebody got our mail return senderrs
def handleApply(self, action): data, errors = self.extractData() if errors: self.status = self.formErrorsMessage return portal = getToolByName(self, 'portal_url').getPortalObject() encoding = portal.getProperty('email_charset', 'utf-8') result = data['publications'].split(",") publications = [] for p in result: k = p.split(":") if len(k) == 2: image = uuidToObject(k[0]) qty = k[1] publications.append([image, qty]) data['publications'] = publications data['greeting'] = self.getGreeting(data['greeting']) data['titles'] = self.getTitles(data['titles']) trusted_template = trusted(portal.order_email) mail_text = trusted_template(self, charset=encoding, data = data) subject = self.context.translate(_(u"New order")) if isinstance(mail_text, str): mail_text = mail_text.encode(encoding) host = getToolByName(self, 'MailHost') registry = getUtility(IRegistry) mail_settings = registry.forInterface(IMailSchema, prefix='plone') m_to = mail_settings.email_from_address # to admin m_from = m_to try: host.send(mail_text, m_to, m_from, subject=subject, charset=encoding, immediate=True, msg_type="text/html") print(m_to) except SMTPRecipientsRefused: raise SMTPRecipientsRefused( _(u'Recipient address rejected by server.')) except SMTPException as e: raise(e) # to client trusted_template = trusted(portal.order_email2) mail_text = trusted_template(self, charset=encoding, data = data) subject = self.context.translate(_(u"New order")) if isinstance(mail_text, str): mail_text = mail_text.encode(encoding) try: host.send(mail_text, data['email'], m_from, subject=subject, charset=encoding, immediate=True, msg_type="text/html") except SMTPRecipientsRefused: raise SMTPRecipientsRefused( _(u'Recipient address rejected by server.')) except SMTPException as e: raise(e) IStatusMessage(self.request).add(_(u"Submit complete"), type='info') return self._redirect(target=self.context.absolute_url())
def sendmail(self, sender, recipients, message, mail_options=[], rcpt_options=[]): """This command performs an entire mail transaction. The arguments are: - sender : The address sending this mail. - recipients : A list of addresses to send this mail to. A bare string will be treated as a list with 1 address. - message : The message string to send. - mail_options : List of ESMTP options (such as 8bitmime) for the mail command. - rcpt_options : List of ESMTP options (such as DSN commands) for all the rcpt commands. message must be a string containing characters in the ASCII range. The string is encoded to bytes using the ascii codec, and lone \\r and \\n characters are converted to \\r\\n characters. If there has been no previous EHLO or HELO command this session, this method tries ESMTP EHLO first. If the server does ESMTP, message size and each of the specified options will be passed to it. If EHLO fails, HELO will be tried and ESMTP options suppressed. This method will return normally if the mail is accepted for at least one recipient. It returns a dictionary, with one entry for each recipient that was refused. Each entry contains a tuple of the SMTP error code and the accompanying error message sent by the server. This method may raise the following exceptions: SMTPHeloError The server didn't reply properly to the helo greeting. SMTPRecipientsRefused The server rejected ALL recipients (no mail was sent). SMTPSenderRefused The server didn't accept the from_addr. SMTPDataError The server replied with an unexpected error code (other than a refusal of a recipient). Note: the connection will be open even after an exception is raised. Example: >>> import asyncio >>> import aiosmtplib >>> loop = asyncio.get_event_loop() >>> smtp = aiosmtplib.SMTP(hostname='localhost', port=25) >>> loop.run_until_complete(smtp.ready) >>> tolist=["*****@*****.**","*****@*****.**","*****@*****.**"] >>> msg = '''\\ ... From: [email protected] ... Subject: testin'... ... ... This is a test ''' >>> future = asyncio.async(smtp.sendmail("*****@*****.**", tolist, msg)) >>> loop.run_until_complete(future) >>> future.result() { "*****@*****.**" : ( 550 ,"User unknown" ) } >>> smtp.close() In the above example, the message was accepted for delivery to two of the three addresses, and one was rejected, with the error code 550. If all addresses are accepted, then the method will return an empty dictionary. """ if isinstance(recipients, str): recipients = [recipients] esmtp_options = [] if self.supports_esmtp: if self.supports('size'): size_option = "size={}".format(len(message)) esmtp_options.append(size_option) esmtp_options = esmtp_options + mail_options yield from self.ehlo_or_helo_if_needed() code, response = yield from self.mail(sender, esmtp_options) # sender worked errors = {} for address in recipients: code, response = yield from self.rcpt(address, rcpt_options) if code not in (SMTP_COMPLETED, SMTP_WILL_FORWARD): errors[address] = (code, response) if len(errors) == len(recipients): # the server refused all our recipients raise SMTPRecipientsRefused(errors) code, response = yield from self.data(message) # if we got here then somebody got our mail return errors
def send_mail_raise_smtp(messages): """Patch email_utils.send_messages with this in your tests to check what happens when an email fails to send.""" raise SMTPRecipientsRefused(recipients=messages[0].recipients())
def handleSubmit(self, action): data, errors = self.extractData() if errors: return False username = data.get('username', '') user = api.user.get(username=username) reason = None if user: try: # Here we need to generate a token which is valid for let's say, 2 hours # using which it should be possible to reset the bar-code. The `signature` # generated should be saved in the user profile `bar_code_reset_token`. ska_secret_key = get_ska_secret_key(request=self.request, user=user) signature = Signature.generate_signature( auth_user=username, secret_key=ska_secret_key, lifetime=7200 # 2 hours ) request_helper = RequestHelper(signature_param='signature', auth_user_param='auth_user', valid_until_param='valid_until') signed_url = request_helper.signature_to_url( signature=signature, endpoint_url='{0}/{1}'.format(self.context.absolute_url(), '@@reset-bar-code')) # Save the `signature` value to the `bar_code_reset_token`. user.setMemberProperties( mapping={ 'bar_code_reset_token': str(signature), }) # Now we need to send an email to user with URL in and a small explanations. try: host = getToolByName(self, 'MailHost') mail_text_template = self.context.restrictedTraverse( 'request_bar_code_reset_email') mail_text = mail_text_template( member=user, bar_code_reset_url=signed_url, charset='utf-8') mail_text = mail_text.format(bar_code_reset_url=signed_url) host.send(mail_text, immediate=True, msg_type='text/html') except SMTPRecipientsRefused as e: raise SMTPRecipientsRefused( 'Recipient address rejected by server') IStatusMessage(self.request).addStatusMessage( _("An email with instructions on resetting your bar-code is sent successfully." ), 'info') redirect_url = "{0}".format(self.context.absolute_url()) self.request.response.redirect(redirect_url) except ValueError as e: reason = _(str(e)) else: reason = _("Invalid username.") if reason is not None: IStatusMessage(self.request).addStatusMessage( _("Request for bar-code reset is failed! {0}".format(reason)), 'error')
def patch_smtp_refused(self, mocker): mock = mocker.patch("aiosmtpd.handlers.smtplib.SMTP") mock().sendmail.side_effect = SMTPRecipientsRefused(self.BAD_BART)
def erroring_send(self): raise SMTPRecipientsRefused(['foo@bar'])
def handleSubmit(self, action): data, errors = self.extractData() if errors: return False username = data.get('username', '') mobile_number = data.get('mobile_number', '') user = api.user.get(username=username) reason = None if user: try: # Here we need to generate a token which is valid for let's say, 2 hours # using which it should be possible to reset the mobile number. The `signature` # generated should be saved in the user profile `mobile_number_reset_token`. ska_secret_key = get_ska_secret_key(request=self.request, user=user) # We also need to generate another token (no security, just a random string) # to sent to users' mobile number. mobile_number_reset_code = generate_code(user) token_lifetime = get_ska_token_lifetime() signature = Signature.generate_signature( auth_user=username, secret_key=ska_secret_key, lifetime=token_lifetime, extra={'mobile_number': mobile_number}) request_helper = RequestHelper(signature_param='signature', auth_user_param='auth_user', valid_until_param='valid_until') signed_url = request_helper.signature_to_url( signature=signature, endpoint_url='{0}/{1}'.format(self.context.absolute_url(), '@@reset-mobile-number')) # Send the SMS sms_sent = send_mobile_number_reset_confirmation_code_sms( mobile_number=mobile_number, code=mobile_number_reset_code) if not sms_sent: IStatusMessage(self.request).addStatusMessage( _("An error occured while sending the SMS to the number specified." ), 'info') redirect_url = "{0}".format(self.context.absolute_url()) self.request.response.redirect(redirect_url) return # Save the `signature` value to the `mobile_number_reset_token`. user.setMemberProperties( mapping={ 'mobile_number_reset_token': str(signature), 'mobile_number_reset_code': mobile_number_reset_code, 'mobile_number_authentication_code': '', }) # Now we need to send an email to user with URL in and a small explanations. try: host = getToolByName(self, 'MailHost') mail_text_template = self.context.restrictedTraverse( 'request_mobile_number_reset_email') mail_text = mail_text_template( member=user, mobile_number_reset_url=signed_url, charset='utf-8') mail_text = mail_text.format( mobile_number_reset_url=signed_url) host.send(mail_text.encode('UTF-8'), immediate=True, msg_type='text/html') except SMTPRecipientsRefused as e: raise SMTPRecipientsRefused( 'Recipient address rejected by server') IStatusMessage(self.request).addStatusMessage( _("An email with further instructions for (re)setting your mobile number has been sent." ), 'info') redirect_url = "{0}/@@reset-email-sent".format( self.context.absolute_url()) self.request.response.redirect(redirect_url) except ValueError as e: reason = _(str(e)) else: reason = _("Invalid username.") if reason is not None: IStatusMessage(self.request).addStatusMessage( _("Request for mobile number reset is failed! {0}").format( reason), 'error')