Python smtplib.SMTPSenderRefused() Examples

The following are 28 code examples of smtplib.SMTPSenderRefused(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module smtplib , or try the search function .
Example #1
Source File: tests.py    From jorvik with GNU General Public License v3.0 6 votes vote down vote up
def test_fallimento_sender(self, mock_smtp):
        """
        In caso di fallimento del sender il messaggio viene rimesso in coda,
        tranne che in caso di errore 5XX che è permanente
        """
        codici = (451, 452, 500, 501, 421)
        for codice in codici:
            msg = 'code {}'.format(codice)
            instance = mock_smtp.return_value
            instance.sendmail.side_effect = smtplib.SMTPSenderRefused(code=codice, msg=msg, sender=Messaggio.SUPPORTO_EMAIL)
            self._invia_msg_singolo()
            if codice == 501:
                self.assertEqual(Messaggio.in_coda().count(), 0)
            else:
                self.assertEqual(Messaggio.in_coda().count(), 1)
            self._reset_coda() 
Example #2
Source File: test_admin.py    From openwisp-users with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def test_admin_add_user_with_invalid_email(self):
        admin = self._create_admin()
        self.client.force_login(admin)
        params = dict(
            username='testmail',
            email='test@invalid.com',
            password1='tester',
            password2='tester',
        )
        params.update(self.add_user_inline_params)
        params.update(self._additional_params_add())
        with patch('allauth.account.models.EmailAddress.objects.add_email') as mocked:
            mocked.side_effect = smtplib.SMTPSenderRefused(
                501, '5.1.7 Bad sender address syntax', 'test_name@test_domain'
            )
            self.client.post(reverse(f'admin:{self.app_label}_user_add'), params)
            mocked.assert_called_once() 
Example #3
Source File: send.py    From byro with Apache License 2.0 6 votes vote down vote up
def test(self, from_addr):
        try:
            self.open()
            self.connection.ehlo_or_helo_if_needed()
            self.connection.rcpt("test@example.org")
            (code, resp) = self.connection.mail(from_addr, [])
            if code != 250:
                logger.warning(
                    "Error testing mail settings, code %d, resp: %s" % (code, resp)
                )
                raise SMTPSenderRefused(code, resp, from_addr)
            senderrs = {}
            (code, resp) = self.connection.rcpt("test@example.com")
            if (code != 250) and (code != 251):
                logger.warning(
                    "Error testing mail settings, code %d, resp: %s" % (code, resp)
                )
                raise SMTPRecipientsRefused(senderrs)
        finally:
            self.close() 
Example #4
Source File: mail.py    From muesli with GNU General Public License v3.0 5 votes vote down vote up
def sendMail(message, request=None):
    s = smtplib.SMTP(server)
    if not testing:
        try:
            s.sendmail(message.sender, message.send_to, message.as_string())
        except smtplib.SMTPSenderRefused as e:
            if request:
                request.session.flash(e[1], queue='errors')
            raise
    s.quit() 
Example #5
Source File: test_smtp.py    From sync-engine with GNU Affero General Public License v3.0 5 votes vote down vote up
def test_handle_disconnect(monkeypatch, smtp_port):
    def simulate_disconnect(self):
        raise smtplib.SMTPServerDisconnected()
    monkeypatch.setattr('smtplib.SMTP.rset', simulate_disconnect)
    monkeypatch.setattr('smtplib.SMTP.mail', lambda *args: (550, 'NOPE'))
    conn = SMTPConnection(account_id=1,
                          email_address='inboxapptest@gmail.com',
                          smtp_username='inboxapptest@gmail.com',
                          auth_type='password',
                          auth_token='secret_password',
                          smtp_endpoint=('smtp.gmail.com', smtp_port),
                          ssl_required=True,
                          log=get_logger())
    with pytest.raises(smtplib.SMTPSenderRefused):
        conn.sendmail(['test@example.com'], 'hello there') 
Example #6
Source File: test_sending.py    From sync-engine with GNU Affero General Public License v3.0 5 votes vote down vote up
def message_too_large(patch_token_manager, monkeypatch, request):
    monkeypatch.setattr(
        'inbox.sendmail.smtp.postel.SMTPConnection',
        erring_smtp_connection(
            smtplib.SMTPSenderRefused, 552,
            request.param, None)) 
Example #7
Source File: test_smtp.py    From sync-engine with GNU Affero General Public License v3.0 5 votes vote down vote up
def test_handle_disconnect(monkeypatch, smtp_port):
    def simulate_disconnect(self):
        raise smtplib.SMTPServerDisconnected()
    monkeypatch.setattr('smtplib.SMTP.rset', simulate_disconnect)
    monkeypatch.setattr('smtplib.SMTP.mail', lambda *args: (550, 'NOPE'))
    conn = SMTPConnection(account_id=1,
                          email_address='inboxapptest@gmail.com',
                          smtp_username='inboxapptest@gmail.com',
                          auth_type='password',
                          auth_token='secret_password',
                          smtp_endpoint=('smtp.gmail.com', smtp_port),
                          ssl_required=True,
                          log=get_logger())
    with pytest.raises(smtplib.SMTPSenderRefused):
        conn.sendmail(['test@example.com'], 'hello there') 
Example #8
Source File: test_sending.py    From sync-engine with GNU Affero General Public License v3.0 5 votes vote down vote up
def message_too_large(patch_token_manager, monkeypatch, request):
    monkeypatch.setattr(
        'inbox.sendmail.smtp.postel.SMTPConnection',
        erring_smtp_connection(
            smtplib.SMTPSenderRefused, 552,
            request.param, None)) 
Example #9
Source File: test_smtplib.py    From android_universal with MIT License 5 votes vote down vote up
def test_421_from_mail_cmd(self):
        smtp = smtplib.SMTP(HOST, self.port, local_hostname='localhost', timeout=15)
        smtp.noop()
        self.serv._SMTPchannel.mail_response = '421 closing connection'
        with self.assertRaises(smtplib.SMTPSenderRefused):
            smtp.sendmail('John', 'Sally', 'test message')
        self.assertIsNone(smtp.sock)
        self.assertEqual(self.serv._SMTPchannel.rset_count, 0) 
Example #10
Source File: test_smtplib.py    From android_universal with MIT License 5 votes vote down vote up
def test__rest_from_mail_cmd(self):
        smtp = smtplib.SMTP(HOST, self.port, local_hostname='localhost', timeout=15)
        smtp.noop()
        self.serv._SMTPchannel.mail_response = '451 Requested action aborted'
        self.serv._SMTPchannel.disconnect = True
        with self.assertRaises(smtplib.SMTPSenderRefused):
            smtp.sendmail('John', 'Sally', 'test message')
        self.assertIsNone(smtp.sock)

    # Issue 5713: make sure close, not rset, is called if we get a 421 error 
Example #11
Source File: test_smtplib.py    From Project-New-Reign---Nemesis-Main with GNU General Public License v3.0 5 votes vote down vote up
def test_421_from_mail_cmd(self):
        smtp = smtplib.SMTP(HOST, self.port, local_hostname='localhost', timeout=15)
        smtp.noop()
        self.serv._SMTPchannel.mail_response = '421 closing connection'
        with self.assertRaises(smtplib.SMTPSenderRefused):
            smtp.sendmail('John', 'Sally', 'test message')
        self.assertIsNone(smtp.sock)
        self.assertEqual(self.serv._SMTPchannel.rset_count, 0) 
Example #12
Source File: test_smtplib.py    From Project-New-Reign---Nemesis-Main with GNU General Public License v3.0 5 votes vote down vote up
def test__rest_from_mail_cmd(self):
        smtp = smtplib.SMTP(HOST, self.port, local_hostname='localhost', timeout=15)
        smtp.noop()
        self.serv._SMTPchannel.mail_response = '451 Requested action aborted'
        self.serv._SMTPchannel.disconnect = True
        with self.assertRaises(smtplib.SMTPSenderRefused):
            smtp.sendmail('John', 'Sally', 'test message')
        self.assertIsNone(smtp.sock)

    # Issue 5713: make sure close, not rset, is called if we get a 421 error 
Example #13
Source File: test_smtplib.py    From ironpython3 with Apache License 2.0 5 votes vote down vote up
def test_421_from_mail_cmd(self):
        smtp = smtplib.SMTP(HOST, self.port, local_hostname='localhost', timeout=15)
        smtp.noop()
        self.serv._SMTPchannel.mail_response = '421 closing connection'
        with self.assertRaises(smtplib.SMTPSenderRefused):
            smtp.sendmail('John', 'Sally', 'test message')
        self.assertIsNone(smtp.sock)
        self.assertEqual(self.serv._SMTPchannel.rset_count, 0) 
Example #14
Source File: test_smtplib.py    From ironpython3 with Apache License 2.0 5 votes vote down vote up
def test__rest_from_mail_cmd(self):
        smtp = smtplib.SMTP(HOST, self.port, local_hostname='localhost', timeout=15)
        smtp.noop()
        self.serv._SMTPchannel.mail_response = '451 Requested action aborted'
        self.serv._SMTPchannel.disconnect = True
        with self.assertRaises(smtplib.SMTPSenderRefused):
            smtp.sendmail('John', 'Sally', 'test message')
        self.assertIsNone(smtp.sock)

    # Issue 5713: make sure close, not rset, is called if we get a 421 error 
Example #15
Source File: test_smtplib.py    From Fluid-Designer with GNU General Public License v3.0 5 votes vote down vote up
def test_421_from_mail_cmd(self):
        smtp = smtplib.SMTP(HOST, self.port, local_hostname='localhost', timeout=15)
        smtp.noop()
        self.serv._SMTPchannel.mail_response = '421 closing connection'
        with self.assertRaises(smtplib.SMTPSenderRefused):
            smtp.sendmail('John', 'Sally', 'test message')
        self.assertIsNone(smtp.sock)
        self.assertEqual(self.serv._SMTPchannel.rset_count, 0) 
Example #16
Source File: test_smtplib.py    From Fluid-Designer with GNU General Public License v3.0 5 votes vote down vote up
def test__rest_from_mail_cmd(self):
        smtp = smtplib.SMTP(HOST, self.port, local_hostname='localhost', timeout=15)
        smtp.noop()
        self.serv._SMTPchannel.mail_response = '451 Requested action aborted'
        self.serv._SMTPchannel.disconnect = True
        with self.assertRaises(smtplib.SMTPSenderRefused):
            smtp.sendmail('John', 'Sally', 'test message')
        self.assertIsNone(smtp.sock)

    # Issue 5713: make sure close, not rset, is called if we get a 421 error 
Example #17
Source File: notifymail.py    From django-nyt with Apache License 2.0 5 votes vote down vote up
def _send_batch(self, context, connection, setting):
        """
        Loops through emails in a list of notifications and tries to send
        to each recepient

        """
        # STMP connection send loop
        notifications = context['notifications']

        if len(context['notifications']) == 0:
            return

        while True:
            try:
                self._send_user_notifications(context, connection)
                for n in notifications:
                    n.is_emailed = True
                    n.save()
                break
            except smtplib.SMTPSenderRefused:
                self.logger.error(
                    (
                        "E-mail refused by SMTP server ({}), "
                        "skipping!"
                    ).format(setting.user.email))
                continue
            except smtplib.SMTPException as e:
                self.logger.error(
                    (
                        "You have an error with your SMTP server "
                        "connection, error is: {}"
                    ).format(e))
                self.logger.error("Sleeping for 30s then retrying...")
                time.sleep(30)
            except Exception as e:
                self.logger.error(
                    (
                        "Unhandled exception while sending, giving "
                        "up: {}"
                    ).format(e))
                raise 
Example #18
Source File: emailer.py    From shutit with MIT License 5 votes vote down vote up
def send(self, attachment_failure=False):
		"""Send the email according to the configured setup

		   attachment_failure - used to indicate a recursive call after the
		   smtp server has refused based on file size.
		   Should not be used externally
		"""
		if not self.config['shutit.core.alerting.emailer.send_mail']:
			self.shutit.log('emailer.send: Not configured to send mail!',level=logging.INFO)
			return True
		msg = self.__compose()
		mailto = [self.config['shutit.core.alerting.emailer.mailto']]
		smtp = self.__get_smtp()
		if self.config['shutit.core.alerting.emailer.username'] != '':
			smtp.login(self.config['shutit.core.alerting.emailer.username'], self.config['shutit.core.alerting.emailer.password'])
		if self.config['shutit.core.alerting.emailer.mailto_maintainer']:
			mailto.append(self.config['shutit.core.alerting.emailer.maintainer'])
		try:
			self.shutit.log('Attempting to send email',level=logging.INFO)
			smtp.sendmail(self.config['shutit.core.alerting.emailer.mailfrom'], mailto, msg.as_string())
		except SMTPSenderRefused as refused:
			code = refused.args[0]
			if code == 552 and not attachment_failure:
				self.shutit.log("Mailserver rejected message due to " + "oversize attachments, attempting to resend without",level=logging.INFO)
				self.attaches = []
				self.lines.append("Oversized attachments not sent")
				self.send(attachment_failure=True)
			else:
				self.shutit.log("Unhandled SMTP error:" + str(refused),level=logging.INFO)
				if not self.config['shutit.core.alerting.emailer.safe_mode']:
					raise refused
		except Exception as error:
			self.shutit.log('Unhandled exception: ' + str(error),level=logging.INFO)
			if not self.config['shutit.core.alerting.emailer.safe_mode']:
				raise error
		finally:
			smtp.quit() 
Example #19
Source File: SMTPTester.py    From SMTPTester with GNU General Public License v3.0 5 votes vote down vote up
def internal_test(smtp_targets, port, fromaddr, toaddr, data, subject, debug):
    data += "\nThis email is part of internal relay and\\or spoofing test"

    for target in smtp_targets:
        LOGGER.info("[*] Checking host %s:%s for internal spoofing", target, str(port))
        data += "\nVulnerable server is: %s" % target
        try:
            if fromaddr and toaddr:  # making sure we have both from and to addresses
                from_domain = fromaddr.split('@').pop()  # getting the domain name from the address
                to_domain = toaddr.split('@').pop()  # getting the domain name from the address
                if from_domain != to_domain:  # making sure the spoofing is for the same domain
                    # otherwise it's relay and not spoofing
                    LOGGER.error("[!] Sender and recipient domains doesn't match!")
                else:
                    with SMTP(target, port) as current_target:
                        if debug:
                            current_target.set_debuglevel(1)
                        current_target.ehlo_or_helo_if_needed()
                        msg = MIMEText(data)
                        fromaddr = fromaddr
                        toaddr = toaddr
                        msg['Subject'] = subject
                        msg['From'] = fromaddr
                        msg['To'] = toaddr

                        current_target.sendmail(fromaddr, toaddr, msg.as_string())
                        LOGGER.critical("[+] Server %s Appears to be VULNERABLE for internal "
                                        "spoofing! Used FROM: %s", target, fromaddr)
            else:
                LOGGER.critical("[!] Problem with FROM and/or TO address!")
                exit(1)
        except (SMTPRecipientsRefused, SMTPSenderRefused) as e:
            LOGGER.critical("[!] SMTP Error: %s\n[-] Server: %s NOT vulnerable or TO address "
                            "doesn't exist!", str(e), target)
        except ConnectionRefusedError:
            LOGGER.critical("[!] Connection refused by host %s", target)
        except KeyboardInterrupt:
            LOGGER.critical("[CTRL+C] Stopping...")
            exit(1)
        except Exception as e:
            excptn(e) 
Example #20
Source File: delivery.py    From mail-security-tester with GNU General Public License v3.0 4 votes vote down vote up
def deliver_testcase(self, testcase, recipient):
        super().deliver_testcase(testcase, recipient)
        print("Sending test case {} from test '{}' to {}".format(self.testcase_index, self.testcases.name, recipient))
        self.allow_delay_increase()
        try:
            try:
                if testcase.delivery_sender:
                    sender = self.sender
                else:
                    sender = None
            except AttributeError:
                sender = None

            try:
                if testcase.delivery_recipient:
                    recipient = recipient
                else:
                    recipient = None
            except AttributeError:
                recipient = None

            result = self.smtp.send_message(testcase, sender, recipient)
            if result:
                for failed_recipient, (code, message) in result.items():
                    print("! Sending to recipient {} failed with error code {}: {}".format(failed_recipient, code, message))
                    self.logger.log(self.testcases.identifier, self.testcase_index, self.recipient, False, code, message)
                    if code in self.delay_increasing_status:
                        self.increase_delay()
            else:
                self.logger.log(self.testcases.identifier, self.testcase_index, self.recipient)
        except smtplib.SMTPRecipientsRefused as e:
            print("! Reciepent refused")
            for failed_recipient, (code, message) in e.recipients.items():
                print("! Sending to recipient {} failed with error code {}: {}".format(failed_recipient, code, str(message, "iso-8859-1")))
                self.logger.log(self.testcases.identifier, self.testcase_index, failed_recipient, False, code, str(message, "iso-8859-1"))
                if code in self.delay_increasing_status:
                    self.increase_delay()
        except smtplib.SMTPHeloError as e:
            print("! SMTP error while HELO: " + str(e))
            if e.smtp_code in self.delay_increasing_status:
                self.increase_delay()
        except smtplib.SMTPSenderRefused as e:
            print("! SMTP server rejected sender address: " + str(e))
            self.logger.log(self.testcases.identifier, self.testcase_index, self.recipient, False, e.smtp_code, e.smtp_error)
            if e.smtp_code in self.delay_increasing_status:
                self.increase_delay()
        except smtplib.SMTPDataError as e:
            print("! Unexpected SMTP error: " + str(e))
            self.logger.log(self.testcases.identifier, self.testcase_index, self.recipient, False, e.smtp_code, e.smtp_error)
            if e.smtp_code in self.delay_increasing_status:
                self.increase_delay()
        except smtplib.SMTPNotSupportedError as e:
            print("! SMTP server doesn't supports: " + str(e))
            self.logger.log(self.testcases.identifier, self.testcase_index, self.recipient, False, -1, str(e))
        except smtplib.SMTPServerDisconnected as e:
            self.logger.log(self.testcases.identifier, self.testcase_index, self.recipient, False, -2, str(e))
            print("! SMTP server disconnected unexpected - reconnecting: " + str(e))
            self.smtp = smtplib.SMTP(self.target) 
Example #21
Source File: report.py    From cobra with MIT License 4 votes vote down vote up
def notification(self, capture_path):
        """
        Email notification
        :param capture_path:
        :return: boolean
        """
        message = MIMEMultipart()
        message['From'] = self.user
        message['To'] = self.to
        message['Subject'] = self.subject

        # 周报图片以附件的形式发送
        # att = MIMEText(open(capture_path, 'rb').read(), 'base64', 'utf-8')
        # att['Content-Type'] = 'application/octet-stream'
        # att["Content-Disposition"] = 'attachment; filename="W({0}).png"'.format(self.wd)
        # message.attach(att)

        # 周报图片以在正文中直接显示
        with open(capture_path, "rb") as image_file:
            encoded_string = base64.b64encode(image_file.read())

        text = MIMEText('<img src="data:image/png;base64,{0}">'.format(encoded_string), 'html')
        message.attach(text)

        try:
            smtp = smtplib.SMTP_SSL(host=self.host, port=self.port)
            smtp.login(self.user, self.password)
            smtp.sendmail(self.user, self.to, message.as_string())
            logger.info('[EMAIL] Email delivered successfully.')
            return True
        except smtplib.SMTPRecipientsRefused:
            logger.critical('[EMAIL] Email delivery rejected.')
            return False
        except smtplib.SMTPAuthenticationError:
            logger.critical('[EMAIL] SMTP authentication error.')
            return False
        except smtplib.SMTPSenderRefused:
            logger.critical('[EMAIL] SMTP sender refused.')
            return False
        except smtplib.SMTPException as error:
            logger.critical(error)
            logger.critical('[EMAIL] Please config SMTP Server, port, username, to, password and sender in config file')
            return False 
Example #22
Source File: send_mail.py    From cobra with MIT License 4 votes vote down vote up
def send_mail(target, filename, receiver):
    host = Config('email', 'host').value
    port = Config('email', 'port').value
    username = Config('email', 'username').value
    password = Config('email', 'password').value
    sender = Config('email', 'sender').value
    is_ssl = to_bool(Config('email', 'ssl').value)

    if is_ssl:
        server = smtplib.SMTP_SSL(host=host, port=port)
    else:
        server = smtplib.SMTP(host=host, port=port)

    s_sid = filename.split('.')[0]
    msg = MIMEMultipart()
    msg['From'] = sender
    msg['To'] = receiver
    msg['Subject'] = '编号 {sid} 项目 Cobra 扫描报告'.format(sid=s_sid)

    msg.attach(MIMEText('扫描项目:{t}\n报告见附件'.format(t=target), 'plain', 'utf-8'))

    try:
        with open(filename, 'rb') as f:
            attachment = MIMEApplication(f.read())
            attachment.add_header('Content-Disposition', 'attachment', filename=os.path.split(filename)[1])
            msg.attach(attachment)
    except IOError:
        logger.warning('[EMAIL] No such file {}, please check input parameter'.format(filename))
        return False

    try:
        server.login(user=username, password=password)
        server.sendmail(from_addr=username, to_addrs=receiver, msg=msg.as_string())
        server.quit()
        logger.info('[EMAIL] Email delivered successfully.')
        return True
    except smtplib.SMTPRecipientsRefused:
        logger.critical('[EMAIL] Email delivery rejected.')
        return False
    except smtplib.SMTPAuthenticationError:
        logger.critical('[EMAIL] SMTP authentication error.')
        return False
    except smtplib.SMTPSenderRefused:
        logger.critical('[EMAIL] SMTP sender refused.')
        return False
    except smtplib.SMTPException as error:
        logger.critical(error)
        logger.critical('[EMAIL] Please config SMTP Server, port, username, password and sender in config file')
        return False 
Example #23
Source File: client.py    From tornado-smtpclient with MIT License 4 votes vote down vote up
def sendmail(self, from_addr, to_addrs, msg, mail_options=[],
                 rcpt_options=[]):

        yield self.ehlo_or_helo_if_needed()
        esmtp_opts = []
        if isinstance(msg, str):
            msg = smtplib._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) = yield self.mail(from_addr, esmtp_opts)
        if code != 250:
            if code == 421:
                self.close()
            else:
                yield self._rset()
            raise smtplib.SMTPSenderRefused(code, resp, from_addr)
        senderrs = {}
        if isinstance(to_addrs, str):
            to_addrs = [to_addrs]
        for each in to_addrs:
            (code, resp) = yield self.rcpt(each, rcpt_options)
            if (code != 250) and (code != 251):
                senderrs[each] = (code, resp)
            if code == 421:
                self.close()
                raise smtplib.SMTPRecipientsRefused(senderrs)
        if len(senderrs) == len(to_addrs):
            # the server refused all our recipients
            yield self._rset()
            raise smtplib.SMTPRecipientsRefused(senderrs)
        (code, resp) =  yield self.data(msg)
        if code != 250:
            if code == 421:
                self.close()
            else:
                yield self._rset()
            raise smtplib.SMTPDataError(code, resp)
        #if we got here then somebody got our mail
        return senderrs 
Example #24
Source File: dmg_report.py    From yobot with GNU General Public License v3.0 4 votes vote down vote up
def _sendmail(self):
        mailconfig = None
        with open(os.path.join(self._path, "mailconf.json"), "r", encoding="utf-8") as f:
            mailconfig = json.load(f)
        if not mailconfig["subscriber"][self._groupid]:
            self.txt_list.append("没有订阅者")
            return
        mail_host = mailconfig["sender"]["host"]
        mail_user = mailconfig["sender"]["user"]
        mail_pass = mailconfig["sender"]["pswd"]
        if mail_user == "unknown" or mail_pass == "unknown":
            self.txt_list.append("没有设置发件人,请在{}里填写发件人信息".format(
                os.path.join(self._path, "mailconf.json")))
            return
        sender = mailconfig["sender"]["sender"]
        receivers = mailconfig["subscriber"][self._groupid]
        message = MIMEMultipart()
        mail_text = MIMEText("公会战的统计报告已生成,详见附件", "plain", "utf-8")
        message.attach(mail_text)
        with open(os.path.join(self._path, "report", self.rpt_name, self.rpt_name+".zip"), "rb") as attach:
            mail_attach = MIMEBase("application", "octet-stream")
            mail_attach.set_payload(attach.read())
        encode_base64(mail_attach)
        mail_attach.add_header("Content-Disposition",
                               "attachment",
                               filename=self._groupid+"_battle_report.zip")
        message.attach(mail_attach)
        message["From"] = mailconfig["sender"]["sender"]
        message["To"] = "客户"
        subject = "公会战统计报告"
        message["Subject"] = Header(subject, "utf-8")
        smtp_obj = smtplib.SMTP()
        try:
            smtp_obj.connect(mail_host, 25)
            smtp_obj.login(mail_user, mail_pass)
            smtp_obj.sendmail(sender, receivers, message.as_string())
        except smtplib.SMTPServerDisconnected:
            self.txt_list.append("SMTP连接失败,请检查您与" +
                                 mailconfig["sender"]["host"] + "的连接")
            return
        except smtplib.SMTPAuthenticationError:
            self.txt_list.append(
                r"发件邮箱密码错误,请发送“设置邮箱”输入正确密码")
            return
        except smtplib.SMTPSenderRefused:
            self.txt_list.append(
                r"发件邮箱已被服务商禁用,请发送“设置邮箱”输入新的邮箱")
            return
        except Exception as other:
            self.txt_list.append("未知错误:")
            self.txt_list.append(str(other))
            return
        smtp_obj.quit()
        self.txt_list.append("报告已发送至:")
        for addr in receivers[:-1]:  # 不显示最后一个
            self.txt_list.append(addr) 
Example #25
Source File: trading.py    From cryptotrader with MIT License 4 votes vote down vote up
def send_email(self, subject, body):
        try:
            assert isinstance(self.email, dict) and \
                   isinstance(subject, str) and isinstance(body, str)
            for key in self.email:
                if key == 'email':
                    gmail_user = self.email[key]
                elif key == 'psw':
                    gmail_pwd = self.email[key]
                elif key == 'to':
                    TO = self.email[key] if type(self.email[key]) is list else [self.email[key]]

            FROM = gmail_user
            SUBJECT = subject
            TEXT = body

            # Prepare actual message
            message = """From: %s\nTo: %s\nSubject: %s\n\n%s
                    """ % (FROM, ", ".join(TO), SUBJECT, TEXT)

            server = smtplib.SMTP("smtp.gmail.com", 587)
            server.ehlo()
            server.starttls()
            server.login(gmail_user, gmail_pwd)
            server.sendmail(FROM, TO, message)
            server.close()

        # If we have no internet, wait five seconds and retry
        except gaierror:
            try:
                sleep(5)
                self.send_email(subject, body)
            except gaierror as e:
                # If there is no internet yet, log error and move on
                Logger.error(TradingEnvironment.send_email, self.parse_error(e))

        except smtplib.SMTPServerDisconnected as e:
            # If there is no internet yet, log error and move on
            Logger.error(TradingEnvironment.send_email, self.parse_error(e))

        except smtplib.SMTPSenderRefused as e:
            # If there is no internet yet, log error and move on
            Logger.error(TradingEnvironment.send_email, self.parse_error(e))

        except Exception as e:
            try:
                Logger.error(TradingEnvironment.send_email, self.parse_error(e))
                if hasattr(self, 'email'):
                    self.send_email("Error sending email: %s at %s" % (e,
                                    datetime.strftime(self.timestamp, "%Y-%m-%d %H:%M:%S")),
                                    self.parse_error(e))
            except Exception as e:
                Logger.error(TradingEnvironment.send_email, self.parse_error(e)) 
Example #26
Source File: utils.py    From cryptotrader with MIT License 4 votes vote down vote up
def send_email(emails, subject, body):
    try:
        assert isinstance(emails, dict) and \
               isinstance(subject, str)# and isinstance(body, str)
        for key in emails:
            if key == 'email':
                gmail_user = emails[key]
            elif key == 'psw':
                gmail_pwd = emails[key]
            elif key == 'to':
                TO = emails[key] if type(emails[key]) is list else [emails[key]]

        FROM = gmail_user
        SUBJECT = subject
        TEXT = body

        # Prepare actual message
        message = """From: %s\nTo: %s\nSubject: %s\n\n%s
        """ % (FROM, ", ".join(TO), SUBJECT, TEXT)

        server = smtplib.SMTP("smtp.gmail.com", 587)
        server.ehlo()
        server.starttls()
        server.login(gmail_user, gmail_pwd)
        server.sendmail(FROM, TO, message)
        server.close()

    # If we have no internet, wait five seconds and retry
    except gaierror:
        try:
            sleep(5)
            send_email(email, subject, body)
        except gaierror as e:
            # If there is no internet yet, log error and move on
            Logger.error(send_email, e)

    except smtplib.SMTPServerDisconnected as e:
        # If there is no internet yet, log error and move on
        Logger.error(send_email, e)

    except smtplib.SMTPSenderRefused as e:
        # If there is no internet yet, log error and move on
        Logger.error(send_email, e)

    except Exception as e:
        error_msg = '\nerror -> ' + type(e).__name__ + ' in line ' + str(
            e.__traceback__.tb_lineno) + ': ' + str(e)
        Logger.error(send_email, error_msg) 
Example #27
Source File: notifymail.py    From django-nyt with Apache License 2.0 4 votes vote down vote up
def _send_batch(self, context, connection, setting):
        """
        Loops through emails in a list of notifications and tries to send
        to each recepient

        """
        # STMP connection send loop
        notifications = context['notifications']

        if len(context['notifications']) == 0:
            return

        while True:
            try:
                self._send_user_notifications(context, connection)
                for n in notifications:
                    n.is_emailed = True
                    n.save()
                break
            except smtplib.SMTPSenderRefused:
                self.logger.error(
                    (
                        "E-mail refused by SMTP server ({}), "
                        "skipping!"
                    ).format(setting.user.email))
                continue
            except smtplib.SMTPException as e:
                self.logger.error(
                    (
                        "You have an error with your SMTP server "
                        "connection, error is: {}"
                    ).format(e))
                self.logger.error("Sleeping for 30s then retrying...")
                time.sleep(30)
            except Exception as e:
                self.logger.error(
                    (
                        "Unhandled exception while sending, giving "
                        "up: {}"
                    ).format(e))
                raise 
Example #28
Source File: SMTPTester.py    From SMTPTester with GNU General Public License v3.0 4 votes vote down vote up
def external_test(smtp_targets, port, fromaddr, recipient, data, subject, debug):
    data += "\nThis email is part of external relay and\\or spoofing test"

    for target in smtp_targets:
        LOGGER.info("[*] Checking host " + target + ':' + str(port))
        LOGGER.info("[*] Testing for mail relaying (external)")
        data += "\nVulnerable server is: %s" % target
        try:
            if fromaddr and recipient:  # checking we have both to and from addresses
                with SMTP(target, port) as current_target:
                    if debug:
                        current_target.set_debuglevel(1)
                    current_target.ehlo_or_helo_if_needed()
################
                    # Create a multipart message and set headers
                    message = MIMEMultipart()
                    message["From"] = fromaddr
                    message["To"] = recipient
                    message["Subject"] = subject
                    # message["Bcc"] = receiver_email  # Recommended for mass emails

                    # Add body to email
                    message.attach(MIMEText(data, "plain"))

                    # # Open PDF file in binary mode
                    # with open(attachment, "rb") as attached:
                    #     # Add file as application/octet-stream
                    #     # Email client can usually download this automatically as attachment
                    #     part = MIMEBase("application", "octet-stream")
                    #     part.set_payload(attached.read())
                    #
                    # # Encode file in ASCII characters to send by email
                    # encoders.encode_base64(part)
                    #
                    # # Add header as key/value pair to attachment part
                    # part.add_header(
                    #     "Content-Disposition",
                    #     "attachment; filename= {attachment}",
                    # )
                    #
                    # # Add attachment to message and convert message to string
                    # message.attach(part)
                    text = message.as_string()
##############
                    current_target.sendmail(fromaddr, recipient, text)
                    LOGGER.critical("[+] Server %s Appears to be VULNERABLE for external relay! "
                                    "email send FROM: %s TO: %s", target, fromaddr, recipient)
            else:
                LOGGER.critical("[!] Problem with FROM and/or TO address!")
                exit(1)
        except (SMTPRecipientsRefused, SMTPSenderRefused, SMTPResponseException) as e:
            LOGGER.critical("[!] SMTP Error: %s\n[-] Server: %s NOT vulnerable!", str(e), target)
        except ConnectionRefusedError:
            LOGGER.critical("[!] Connection refused by host %s", target)
        except KeyboardInterrupt:
            LOGGER.critical("[!] [CTRL+C] Stopping...")
            exit(1)
        except Exception as e:
            excptn(e)