Ejemplo n.º 1
0
def ssl_preset_client(request, ssl_preset_server, event_loop):
    client = SMTP(
        hostname=ssl_preset_server.hostname, port=ssl_preset_server.port,
        loop=ssl_preset_server.loop, use_ssl=True, validate_certs=False)
    client.server = ssl_preset_server

    return client
Ejemplo n.º 2
0
def smtpd_client(request, smtpd_server, event_loop):
    client = SMTP(
        hostname=smtpd_server.hostname, port=smtpd_server.port,
        loop=event_loop, timeout=1)
    client.server = smtpd_server

    return client
Ejemplo n.º 3
0
def tls_preset_client(request, tls_preset_server, event_loop):
    client = SMTP(
        hostname=tls_preset_server.hostname, port=tls_preset_server.port,
        loop=event_loop, use_tls=True, validate_certs=False, timeout=1)
    client.server = tls_preset_server

    return client
Ejemplo n.º 4
0
def preset_client(request, preset_server, event_loop):
    client = SMTP(
        hostname=preset_server.hostname, port=preset_server.port,
        loop=event_loop, timeout=1)
    client.server = preset_server

    return client
Ejemplo n.º 5
0
def aiosmtpd_client(request, aiosmtpd_server, event_loop):
    client = SMTP(
        hostname=aiosmtpd_server.hostname, port=aiosmtpd_server.port,
        loop=event_loop)
    client.server = aiosmtpd_server

    return client
Ejemplo n.º 6
0
def preset_client(request, preset_server, event_loop):
    client = SMTP(
        hostname=preset_server.hostname, port=preset_server.port,
        loop=preset_server.loop)
    client.server = preset_server

    return client
    def __init__(self, queue, delay, loop):
        self.loop = loop
        self.delay = delay
        self.queue = queue

        self.smtp = SMTP(hostname="127.0.0.1", port=25)

        self.timer = None
        self.task = asyncio.ensure_future(self.process_queue())
Ejemplo n.º 8
0
async def send(mail: Mail, templates: Templates) -> str:
    """Send one email over smtp.

    Raises:
        CannotSendMessages: when cannot connect to smtp server
        FailedToSendMessage: - when cannot send the message

    Args:
        mail (Mail): mail to be sent
        templates (Dict[str, str]): dictionary of templates
    """
    smtp = SMTP(
        hostname=settings.smtp_host,
        port=int(settings.smtp_port),
        use_tls=settings.smtp_tls,
    )

    message = EmailMessage()

    message["From"] = settings.mail_from
    message["Return-Path"] = settings.mail_return
    message["Subject"] = mail.subject
    message["To"] = ", ".join(mail.to)

    if mail.cc:
        message["CC"] = ", ".join(mail.cc)

    if mail.bcc:
        message["BCC"] = ", ".join(mail.bcc)

    message = await attach_content(mail, templates, message)

    try:

        try:
            await smtp.connect()
            if settings.smtp_user:
                await smtp.ehlo()
                await smtp.auth_plain(
                    settings.smtp_user,
                    settings.smtp_password.get_secret_value(),
                )

        except (SMTPConnectError, SMTPAuthenticationError) as e:
            log.error(e)
            if log.getEffectiveLevel() == logging.DEBUG:
                log.exception(e)
            raise CannotSendMessages()

        await smtp.send_message(message)
        smtp.close()

        return str(message)

    except (SMTPRecipientsRefused, SMTPResponseException) as e:
        log.exception(e)
        raise FailedToSendMessage()
Ejemplo n.º 9
0
async def test_close_works_on_stopped_loop(smtpd_server, event_loop, hostname, port):
    client = SMTP(hostname=hostname, port=port, loop=event_loop)

    await client.connect()
    assert client.is_connected
    assert client.transport is not None

    event_loop.stop()

    client.close()
    assert not client.is_connected
Ejemplo n.º 10
0
async def test_bad_connect_response_raises_error(preset_server, event_loop):
    preset_client = SMTP(hostname=preset_server.hostname,
                         port=preset_server.port,
                         loop=event_loop,
                         timeout=1.0)

    preset_server.greeting = b'421 Please come back in 204232430 seconds.\n'
    with pytest.raises(SMTPConnectError):
        await preset_client.connect()

    preset_client.close()
Ejemplo n.º 11
0
async def test_default_port_on_connect(event_loop):
    client = SMTP(loop=event_loop)

    try:
        await client.connect(use_tls=False, timeout=0.000000001)
    except SMTPTimeoutError:
        pass  # Ignore connection failure

    assert client.port == 25

    client.close()
Ejemplo n.º 12
0
async def test_default_tls_port_on_connect(event_loop):
    client = SMTP(loop=event_loop)

    try:
        await client.connect(use_tls=True, timeout=0.01)
    except Exception:
        pass  # Ignore connection failure

    assert client.port == 465

    client.close()
Ejemplo n.º 13
0
async def test_close_works_on_stopped_loop(preset_server, event_loop):
    preset_client = SMTP(hostname=preset_server.hostname,
                         port=preset_server.port,
                         loop=event_loop)

    await preset_client.connect()
    assert preset_client.is_connected
    assert preset_client.transport is not None

    event_loop.stop()

    preset_client.close()
    assert not preset_client.is_connected
Ejemplo n.º 14
0
async def test_default_port_on_connect(event_loop, bind_address, use_tls,
                                       start_tls, expected_port):
    client = SMTP()

    try:
        await client.connect(hostname=bind_address,
                             use_tls=use_tls,
                             start_tls=start_tls,
                             timeout=0.001)
    except (asyncio.TimeoutError, OSError):
        pass

    assert client.port == expected_port

    client.close()
Ejemplo n.º 15
0
async def test_quit_then_connect_ok_with_preset_server(preset_server,
                                                       event_loop):
    preset_client = SMTP(
        hostname=preset_server.hostname,
        port=preset_server.port,
        loop=event_loop,
        timeout=1.0,
    )

    response = await preset_client.connect()
    assert response.code == 220

    response = await preset_client.quit()
    assert response.code == 221

    # Next command should fail
    with pytest.raises(SMTPServerDisconnected):
        await preset_client.noop()

    response = await preset_client.connect()
    assert response.code == 220

    # after reconnect, it should work again
    preset_server.responses.append(b"250 noop")
    response = await preset_client.noop()
    assert response.code == 250

    await preset_client.quit()
Ejemplo n.º 16
0
async def test_config_via_connect_kwargs(preset_server, event_loop):
    client = SMTP(
        hostname="",
        use_tls=True,
        port=preset_server.port + 1,
        source_address="example.com",
    )

    source_address = socket.getfqdn()
    await client.connect(
        hostname=preset_server.hostname,
        port=preset_server.port,
        loop=event_loop,
        use_tls=False,
        source_address=source_address,
    )
    assert client.is_connected

    assert client.hostname == preset_server.hostname
    assert client.port == preset_server.port
    assert client.loop == event_loop
    assert client.use_tls is False
    assert client.source_address == source_address

    await client.quit()
Ejemplo n.º 17
0
    async def connect_and_run_commands(*args, **kwargs):
        async with SMTP(hostname=hostname, port=port) as client:
            await client.ehlo()
            await client.help()
            response = await client.noop()

        return response
Ejemplo n.º 18
0
async def test_connect_and_sendmail_multiple_times_with_gather(
        smtpd_server, event_loop):
    sender = '*****@*****.**'
    recipients = [
        '*****@*****.**',
        '*****@*****.**',
        '*****@*****.**',
    ]
    mail_text = """
    Hello world!

    -a tester
    """

    client = SMTP(hostname=smtpd_server.hostname,
                  port=smtpd_server.port,
                  loop=event_loop)

    async def connect_and_send(*args, **kwargs):
        async with client:
            response = await client.sendmail(*args, **kwargs)

        return response

    tasks = [
        connect_and_send(sender, [recipient], mail_text)
        for recipient in recipients
    ]
    results = await asyncio.gather(*tasks, loop=event_loop)
    for errors, message in results:
        assert not errors
        assert isinstance(errors, dict)
        assert message != ''
Ejemplo n.º 19
0
async def test_connect_timeout_takes_precedence(hostname, smtpd_server_port):
    client = SMTP(hostname=hostname, port=smtpd_server_port, timeout=0.66)
    await client.connect(timeout=0.99)

    assert client.timeout == 0.99

    await client.quit()
Ejemplo n.º 20
0
async def test_connect_port_takes_precedence(event_loop, hostname, smtpd_server_port):
    client = SMTP(hostname=hostname, port=17)
    await client.connect(port=smtpd_server_port)

    assert client.port == smtpd_server_port

    await client.quit()
Ejemplo n.º 21
0
async def send_with_send_message(message, recipients):
    """Send email."""
    smtp_client = SMTP(hostname=app_config.MAIL_SERVER,
                       port=app_config.MAIL_PORT)
    await smtp_client.connect()
    await smtp_client.send_message(message=message, recipients=recipients)
    await smtp_client.quit()
Ejemplo n.º 22
0
def smtp_client_smtputf8(request, event_loop, hostname,
                         smtpd_server_smtputf8_port):
    client = SMTP(hostname=hostname,
                  port=smtpd_server_smtputf8_port,
                  timeout=1.0)

    return client
Ejemplo n.º 23
0
async def send_verify_email(target_email: str, token: str):
    """Send an auth email."""
    subject = "LUHack Discord Verification Bot Authentication Email"

    body = textwrap.dedent(f"""
        Hello!
        You are receiving this email because you have requested to authenticate yourself as a valid Lancaster University student on the LUHack Discord server.


        Your authentication token is: {token}

        DM the bot and use the command: "!verify {token}"
        """)

    message = EmailMessage()
    message["From"] = from_email_address
    message["To"] = target_email
    message["Subject"] = subject
    message.set_content(body)

    smtp_client = SMTP(hostname="smtp.lancs.ac.uk")
    async with smtp_client:
        await smtp_client.send_message(message)

    logger.info(f"Sent auth email to: {target_email}")
Ejemplo n.º 24
0
def tls_smtp_client(request, event_loop, hostname, port):
    tls_client = SMTP(hostname=hostname,
                      port=port,
                      use_tls=True,
                      validate_certs=False)

    return tls_client
Ejemplo n.º 25
0
async def send_mail(to_mails: Sequence[EmailStr], text: str, subject: str,
                    email_type: str):
    """
    发送邮件
    :param to_mails:
    :param text:
    :param subject:
    :param email_type:
    :return:
    """
    to_mails = to_mails
    text = text
    subject = subject
    # config = await get_config_by_key('email_config')
    # client = SMTP(hostname=config.get('mail_host'), port=config.get('mail_port'), username=config.get('mail_user'),
    #               password=config.get('mail_password'), use_tls=True)
    client = SMTP(hostname="smtp.office365.com",
                  port=587,
                  username="******",
                  password="******",
                  start_tls=True)
    if email_type == "html":
        message = MIMEText(text, 'html', 'utf-8')
    else:
        message = EmailMessage()
        message.set_content(text)
    message['From'] = "*****@*****.**"
    message['Subject'] = subject
    async with client:
        ret = await client.send_message(
            message,
            recipients=to_mails,
        )
    return ret
Ejemplo n.º 26
0
async def test_connect_error_with_no_server(hostname, unused_tcp_port):
    client = SMTP(hostname=hostname, port=unused_tcp_port)

    with pytest.raises(SMTPConnectError):
        # SMTPConnectTimeoutError vs SMTPConnectError here depends on
        # processing time.
        await client.connect(timeout=1.0)
Ejemplo n.º 27
0
async def test_starttls_certificate_options_take_precedence(
        event_loop, hostname, port, smtpd_server, valid_cert_path,
        valid_key_path):
    client = SMTP(
        hostname=hostname,
        port=port,
        validate_certs=False,
        client_cert="test1",
        client_key="test1",
        cert_bundle="test1",
    )

    await client.connect(
        validate_certs=False,
        client_cert="test2",
        client_key="test2",
        cert_bundle="test2",
    )

    await client.starttls(
        client_cert=valid_cert_path,
        client_key=valid_key_path,
        cert_bundle=valid_cert_path,
        validate_certs=True,
    )

    assert client.client_cert == valid_cert_path
    assert client.client_key == valid_key_path
    assert client.cert_bundle == valid_cert_path
    assert client.validate_certs is True

    await client.quit()
Ejemplo n.º 28
0
async def test_connect_error_second_attempt(event_loop):
    client = SMTP(hostname="127.0.0.1", port=65534, loop=event_loop)

    with pytest.raises(SMTPConnectError):
        await client.connect(timeout=0.1)

    with pytest.raises(SMTPConnectError):
        await client.connect(timeout=0.1)
Ejemplo n.º 29
0
async def test_loop_kwarg_deprecation_warning_connect(event_loop, hostname,
                                                      port, smtpd_server):
    client = SMTP(hostname=hostname, port=port)

    with pytest.warns(DeprecationWarning):
        await client.connect(loop=event_loop)

    assert client.loop == event_loop
Ejemplo n.º 30
0
async def test_connect_source_address_takes_precedence(event_loop, hostname,
                                                       port, smtpd_server):
    client = SMTP(hostname=hostname, port=port, source_address="example.com")
    await client.connect(source_address=socket.getfqdn())

    assert client.source_address != "example.com"

    await client.quit()
Ejemplo n.º 31
0
async def test_connect_hostname_takes_precedence(event_loop, hostname, port,
                                                 smtpd_server):
    client = SMTP(hostname="example.com", port=port)
    await client.connect(hostname=hostname)

    assert client.hostname == hostname

    await client.quit()