Exemplo n.º 1
0
async def send_mail(msg):
    smtp_args = dict(
        loop=cfg.APP.loop,
        hostname=cfg.SMTP_HOST,
        port=cfg.SMTP_PORT,
        use_tls=bool(cfg.SMTP_TLS_ENABLED),
    )
    log.debug("Sending email with smtp configuration: %s", pformat(smtp_args))
    if cfg.SMTP_PORT == 587:
        # NOTE: aiosmtplib does not handle port 587 correctly
        # plaintext first, then use starttls
        # this is a workaround
        smtp = aiosmtplib.SMTP(**smtp_args)
        await smtp.connect(use_tls=False, port=cfg.SMTP_PORT)
        if cfg.SMTP_TLS_ENABLED:
            log.info("Starting TLS ...")
            await smtp.starttls(validate_certs=False)
        if cfg.SMTP_USERNAME:
            log.info("Login email server ...")
            await smtp.login(cfg.SMTP_USERNAME, cfg.SMTP_PASSWORD)
        await smtp.send_message(msg)
        await smtp.quit()
    else:
        async with aiosmtplib.SMTP(**smtp_args) as smtp:
            if cfg.SMTP_USERNAME:
                log.info("Login email server ...")
                await smtp.login(cfg.SMTP_USERNAME, cfg.SMTP_PASSWORD)
            await smtp.send_message(msg)
Exemplo n.º 2
0
async def send_mail(recipient, subject, body):
    smtp_args = dict(
        loop=cfg.APP.loop,
        hostname=cfg.SMTP_HOST,
        port=cfg.SMTP_PORT,
        use_tls=cfg.SMTP_TLS,
    )

    msg = MIMEText(body, 'html')
    msg['Subject'] = subject
    msg['From'] = cfg.SMTP_SENDER
    msg['To'] = recipient

    if cfg.SMTP_PORT == 587:
        # aiosmtplib does not handle port 587 correctly
        # plaintext first, then use starttls
        # this is a workaround
        smtp = aiosmtplib.SMTP(**smtp_args)
        await smtp.connect(use_tls=False, port=cfg.SMTP_PORT)
        if cfg.SMTP_TLS:
            await smtp.starttls(validate_certs=False)
        if cfg.SMTP_USERNAME:
            await smtp.login(cfg.SMTP_USERNAME, cfg.SMTP_PASSWORD)
        await smtp.send_message(msg)
        await smtp.quit()
    else:
        async with aiosmtplib.SMTP(**smtp_args) as smtp:
            if cfg.SMTP_USERNAME:
                await smtp.login(cfg.SMTP_USERNAME, cfg.SMTP_PASSWORD)
            await smtp.send_message(msg)
Exemplo n.º 3
0
async def send_mail(app: web.Application, msg: MIMEText):
    cfg: LoginOptions = get_plugin_options(app)

    msg["From"] = cfg.SMTP_SENDER
    smtp_args = dict(
        loop=app.loop,
        hostname=cfg.SMTP_HOST,
        port=cfg.SMTP_PORT,
        use_tls=cfg.SMTP_TLS_ENABLED,
    )
    log.debug("Sending email with smtp configuration: %s", pformat(smtp_args))
    if cfg.SMTP_PORT == 587:
        # NOTE: aiosmtplib does not handle port 587 correctly
        # plaintext first, then use starttls
        # this is a workaround
        smtp = aiosmtplib.SMTP(**smtp_args)
        await smtp.connect(use_tls=False, port=cfg.SMTP_PORT)
        if cfg.SMTP_TLS_ENABLED:
            log.info("Starting TLS ...")
            await smtp.starttls(validate_certs=False)
        if cfg.SMTP_USERNAME:
            log.info("Login email server ...")
            await smtp.login(cfg.SMTP_USERNAME, cfg.SMTP_PASSWORD)
        await smtp.send_message(msg)
        await smtp.quit()
    else:
        async with aiosmtplib.SMTP(**smtp_args) as smtp:
            if cfg.SMTP_USERNAME:
                log.info("Login email server ...")
                await smtp.login(cfg.SMTP_USERNAME, cfg.SMTP_PASSWORD)
            await smtp.send_message(msg)
Exemplo n.º 4
0
 async def prove(self):
     usernamedic = self.read_file(
         self.parameter['U']) if 'U' in self.parameter.keys(
         ) else self.read_file(
             os.path.join(paths.DICT_PATH, 'smtp_usernames.txt'))
     passworddic = self.read_file(
         self.parameter['P']) if 'P' in self.parameter.keys(
         ) else self.read_file(
             os.path.join(paths.DICT_PATH, 'smtp_passwords.txt'))
     async for (username,
                password) in self.generate_dict(usernamedic, passworddic):
         if self.target_port == 465:
             use_tls = True
         else:
             use_tls = False
         try:
             async with aiosmtplib.SMTP(hostname=self.target_host,
                                        port=self.target_port,
                                        use_tls=use_tls) as smtp:
                 await smtp.login(username, password)
                 self.flag = 1
                 self.req.append({
                     "username": username,
                     "password": password
                 })
                 self.res.append({
                     "info": username + "/" + password,
                     "key": 'smtp'
                 })
                 return
         except aiosmtplib.SMTPException as e:
             pass
Exemplo n.º 5
0
async 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 = MIMEMultipart()
    message['Subject'] = subject_template
    message['From'] = settings.SMTP_USER
    message['To'] = email_to

    msg_template = Environment(loader=BaseLoader).from_string(html_template)
    msg_render = msg_template.render(**environment)

    message.attach(MIMEText(msg_render, "html", 'utf-8'))
    # Contact SMTP server and send Message
    smtp = aiosmtplib.SMTP(hostname=settings.SMTP_HOST,
                           port=settings.SMTP_PORT,
                           use_tls=not settings.SMTP_TLS)
    await smtp.connect()
    if settings.SMTP_TLS:
        await smtp.starttls()
    await smtp.login(settings.SMTP_USER, settings.SMTP_PASSWORD)
    await smtp.send_message(message)
    await smtp.quit()

    logging.info(f"send email success")
async def send_mail(subject, recipient, body):

    #Thanks: https://github.com/cole/aiosmtplib/issues/1
    host = app.config.get('MAIL_SERVER_HOST')
    port = app.config.get('MAIL_SERVER_PORT')
    user = app.config.get('MAIL_SERVER_USER')
    password = app.config.get('MAIL_SERVER_PASSWORD')

    loop = asyncio.get_event_loop()

    #server = aiosmtplib.SMTP(host, port, loop=loop, use_tls=False, use_ssl=True)
    server = aiosmtplib.SMTP(hostname=host,
                             port=port,
                             loop=loop,
                             use_tls=False)
    await server.connect()

    await server.starttls()
    await server.login(user, password)

    async def send_a_message():
        message = MIMEText(body)
        message['From'] = app.config.get('MAIL_SERVER_USER')
        #message['To'] = ','.join(new_obj.get('email_to'))
        message['To'] = recipient
        message['Subject'] = subject
        await server.send_message(message)

    await send_a_message()
Exemplo n.º 7
0
    async def get(self):
        args = self.validate_arguments()
        user_id = await self.get_user_id(args['email'][0])
        if not user_id:
            self.set_status(204)
            return

        smtp = aiosmtplib.SMTP(
            hostname=config['smtp']['server'], 
            port=int(config['smtp']['port']),
            use_tls=config['smtp']['use_tls'], 
            loop=self.application.ioloop,
        )
        await smtp.connect()
        if config['smtp']['user']:
            await smtp.login(config['smtp']['user'], config['smtp']['password'])

        url = await self.create_reset_url(user_id)
        message = MIMEText('''
        <html>
        <body>
            Reset your SEPLIS password here: <a href="{0}">{0}</a>
        </body>
        </html>
        '''.format(url), 'html')
        message["From"] = config['smtp']['from']
        message["To"] = args['email'][0]
        message["Subject"] = "Reset password"
        await smtp.send_message(message)

        self.set_status(204)
Exemplo n.º 8
0
    async def _send_mail_worker(self):
        """
        Async worker thread to be used internally.

        When started, will clear the mail queue as it becomes avalible to it.

        When cancelled with asyncio.cancel it will clean any remaining emails
        before closing itself out gracefully.
        """
        client = smtp.SMTP(hostname=self.dsn.hostname, port=self.dsn.port)
        try:
            while True:
                message = await self.mail_queue.get()
                await asyncio.shield(
                    self._send_mail_catch_error(client, message))
                self.mail_queue.task_done()
        except asyncio.CancelledError:
            # Before we allow the cancelation to take effect
            # clear out emails that still need sending
            while not self.mail_queue.empty():
                message = await self.mail_queue.get()
                await asyncio.shield(
                    self._send_mail_catch_error(client, message))
                self.mail_queue.task_done()
            raise
        finally:
            pass
Exemplo n.º 9
0
async def send_email(loop: asyncio.AbstractEventLoop,
                     mail_from: str,
                     mail_to: Union[Iterable, str],
                     subject: str,
                     body: str,
                     server: str = 'localhost') -> None:
    """Send an email to one or more recipients.

    Only supports plain text emails with a single message body.
    No attachments etc.
    """
    if type(mail_to) == str:
        mail_to = [mail_to]
    smtp = aiosmtplib.SMTP(hostname=server, port=25, loop=loop)
    try:
        await smtp.connect()
        for rcpt in mail_to:
            msg = MIMEText(body)
            msg['Subject'] = subject
            msg['From'] = mail_from
            msg['To'] = rcpt
            await smtp.send_message(msg)
        await smtp.quit()
    except aiosmtplib.errors.SMTPException as e:
        log.msg('Error sending smtp notification: %s' % (str(e)),
                'NOTIFICATIONS')
Exemplo n.º 10
0
    async def send(self):
        """ 发送邮件
        """
        message = MIMEMultipart('related')
        message['Subject'] = self._subject
        message['From'] = self._username
        message['To'] = ",".join(self._to_emails)
        message['Date'] = email.utils.formatdate()
        message.preamble = 'This is a multi-part message in MIME format.'
        ma = MIMEMultipart('alternative')
        mt = MIMEText(self._content, 'plain', 'GB2312')
        ma.attach(mt)
        message.attach(ma)

        smtp = aiosmtplib.SMTP(hostname=self._host,
                               port=self._port,
                               timeout=self._timeout,
                               use_tls=self._tls)
        await smtp.connect()
        await smtp.login(self._username, self._password)
        await smtp.send_message(message)
        logger.info('send email success! FROM:',
                    self._username,
                    'TO:',
                    self._to_emails,
                    'CONTENT:',
                    self._content,
                    caller=self)
Exemplo n.º 11
0
async def main(critic: api.critic.Critic, subscription: Subscription) -> None:
    settings = await api.systemsetting.getPrefixed(critic, "smtp")

    try:
        hostname = settings["smtp.address.host"]
        port = settings["smtp.address.port"]
        sender = settings["smtp.sender"]

        if not hostname or not isinstance(hostname, str):
            raise ConfigurationError("No SMTP server hostname set")

        if not port or not isinstance(port, int):
            raise ConfigurationError("No SMTP server port set")

        if not sender or not isinstance(sender, str):
            raise ConfigurationError("No sender email address set")

        async with aiosmtplib.SMTP(hostname=hostname, port=port) as smtp:
            logger.info("Connected to %s:%d", hostname, port)

            async for message_handle in subscription.messages:
                async with message_handle as message:
                    await handle_message(smtp, critic, message, sender)
    except Exception as error:
        logger.error("Will reject all outgoing mail: %s", error)
        async for message_handle in subscription.messages:
            async with message_handle as message:
                await reject_message(critic, message, str(error))
Exemplo n.º 12
0
async def send_mail(path, content):
    smtp = aiosmtplib.SMTP(system_config.SEND_MAIL_SMTP_HOST,
                           system_config.SEND_MAIL_SMTP_PORT,
                           use_tls=system_config.SEND_MAIL_SMTP_SSL)

    message = MIMEText(content, 'plain', 'utf-8')
    message['From'] = formataddr(("XSS Bot", system_config.SEND_MAIL_ADDR))
    message['To'] = formataddr(("User", system_config.RECV_MAIL_ADDR))

    subject = f'[XSS Notice] [{path}]'
    message['Subject'] = Header(subject, 'utf-8')

    async def login_and_send():
        try:
            await smtp.connect()
            await smtp.login(system_config.SEND_MAIL_ADDR,
                             system_config.SEND_MAIL_PASSWD)
            await smtp.sendmail(system_config.SEND_MAIL_ADDR,
                                [system_config.RECV_MAIL_ADDR],
                                message.as_string())
        except Exception as e:
            db_session = session_maker()
            await add_system_log(db_session, f"Mail send error [{str(e)}]",
                                 constants.LOG_TYPE_MAIL_SEND_ERROR)
            await db_session.close()

    asyncio.create_task(login_and_send())
Exemplo n.º 13
0
    async def report(self, report_type: ReportType, job: 'RunningJob',
                     config: Dict[str, Any]) -> None:
        mail = config['mail']
        if not ((mail['smtpHost'] or mail['smtp_host']) and
                mail['to'] and mail['from']):
            return  # email reporting disabled

        body = self._format_body(job)

        if mail['smtpHost']:
            smtp_host = mail['smtpHost']
        else:  # pragma: no cover
            logger.warning("smtp_host is deprecated, was renamed to smtpHost")
            smtp_host = mail['smtp_host']
        if mail['smtpPort']:
            smtp_port = mail['smtpPort']
        else:  # pragma: no cover
            logger.warning("smtp_port is deprecated, was renamed to smtpPort")
            smtp_port = mail['smtp_port']

        logger.debug("smtp: host=%r, port=%r", smtp_host, smtp_port)
        smtp = aiosmtplib.SMTP(hostname=smtp_host, port=smtp_port)
        await smtp.connect()
        message = MIMEText(body)
        message['From'] = mail['from']
        message['To'] = mail['to']
        if report_type == ReportType.SUCCESS:
            message['Subject'] = ('Cron job {!r} completed'
                                  .format(job.config.name))
        elif report_type == ReportType.FAILURE:
            message['Subject'] = ('Cron job {!r} failed'
                                  .format(job.config.name))
        else:  # pragma: no cover
            raise AssertionError
        await smtp.send_message(message)
Exemplo n.º 14
0
async def main():
    #Подключаемся к БД и получаем список пользователей
    async with aiopg.create_pool(dsn) as pool:
        async with pool.acquire() as conn:
            async with conn.cursor() as cur:
                await cur.execute("SELECT * FROM public.user")
                ret = []
                async for row in cur:
                    ret.append(row)
                    #print(row)

            async with aiosmtplib.SMTP(
                    hostname='smtp.gmail.com',  #'smtp.yandex.ru'
                    port=587,  #465 (Yandex), 587 (Google)
                    username=
                    '******',  #'*****@*****.**',
                    password=os.environ.get('SPASSWORD'),
                    start_tls=True) as smtp:
                #по всем адресатам
                for adress in ret:
                    #если пользователь не указал e-mail - пропускаем
                    if adress[2] == None:
                        continue
                    #чтобы избежать текста сообщения в ascii
                    body = EMAIL_BODY.replace('name',
                                              adress[1]).encode('utf-8')
                    await smtp.sendmail(FROM, adress[2], body)

    return ret
Exemplo n.º 15
0
    async def __aenter__(self):
        server = aiosmtplib.SMTP(
            hostname=self.mail.host,
            port=self.mail.port,
            use_tls=self.mail.use_tls,
            timeout=self.mail.timeout,
            source_address=self.mail.source_address,
            loop=self.mail.loop,
            validate_certs=self.mail.validate_certs,
            client_cert=self.mail.client_cert,
            client_key=self.mail.client_key,
            tls_context=self.mail.tls_context,
            cert_bundle=self.mail.cert_bundle,
        )

        await server.connect()

        if self.mail.use_starttls:
            await server.starttls()

        if self.mail.username and self.mail.password:
            await server.login(self.mail.username, self.mail.password)

        self.server = server

        return self
Exemplo n.º 16
0
async def setup(app):
    setattr(
        app, 'smtp',
        aiosmtplib.SMTP(hostname=app.conf.get('email.host', 'localhost'),
                        port=app.conf.get('email.port', 25),
                        timeout=app.conf.get('email.timeout', 5),
                        loop=app.loop))
    async def open(self):
        """
        Ensure an open connection to the email server. Return whether or not a
        new connection was required (True or False) or None if an exception
        passed silently.
        """

        if self.connection:
            # Nothing to do if the connection is already open.
            return False

        connection_params = {}
        if self.timeout is not None:
            connection_params["timeout"] = self.timeout

        try:
            self.connection = aiosmtplib.SMTP(hostname=self.host,
                                              port=self.port,
                                              **connection_params)

            await self.connection.connect()

            if self.use_tls:
                await self.connection.starttls()

            if self.username and self.password:
                await self.connection.login(self.username, str(self.password))

            return True
        except OSError:
            if not self.fail_silently:
                raise
Exemplo n.º 18
0
class Mailer:

    loop = asyncio.get_event_loop()
    server = aiosmtplib.SMTP(hostname=settings.EMAIL_HOST,
                             port=int(settings.EMAIL_PORT),
                             loop=loop)

    @staticmethod
    async def send_mail(subject, body, receiver, _charset='utf-8'):
        log.info(f'Sending mail to {receiver}')
        await Mailer.server.connect()
        await Mailer.server.starttls()
        await Mailer.server.login(username=settings.EMAIL_USER_NAME,
                                  password=settings.EMAIL_PASSWORD)
        message = MIMEMultipart('alternative')
        message['From'] = settings.EMAIL_USER_NAME
        message['To'] = receiver
        message['Subject'] = subject

        text = MIMEText(body, 'text', _charset=_charset)
        html = MIMEText(body, 'html', _charset=_charset)
        message.attach(html)
        message.attach(text)
        await Mailer.server.send_message(message)
        log.info(f'Successfuly sent mail to {receiver}, shutting down SMTP')
        Mailer.server.close()
Exemplo n.º 19
0
    async def send_c(self, content):
        """ Send a email.
        """
        message = MIMEMultipart("related")
        message["Subject"] = content
        message["From"] = self._username
        message["To"] = ",".join(self._to_emails)
        message["Date"] = email.utils.formatdate()
        message.preamble = "This is a multi-part message in MIME format."
        ma = MIMEMultipart("alternative")
        mt = MIMEText(self._content, "plain", "GB2312")
        ma.attach(mt)
        message.attach(ma)

        smtp = aiosmtplib.SMTP(hostname=self._host,
                               port=self._port,
                               timeout=self._timeout,
                               use_tls=self._tls)
        await smtp.connect()
        await smtp.login(self._username, self._password)
        await smtp.send_message(message)
        logger.info("send email success! FROM:",
                    self._username,
                    "TO:",
                    self._to_emails,
                    "CONTENT:",
                    content,
                    caller=self)
Exemplo n.º 20
0
 async def __aenter__(self) -> 'SMTP':
     self.smtp = aiosmtplib.SMTP()
     await self.smtp.connect(hostname=self.host,
                             port=self.port,
                             username=self.user,
                             password=self.password,
                             use_tls=True)
     return self
Exemplo n.º 21
0
async def connect():
    smtp = aiosmtplib.SMTP(hostname=mail_config['smtp'],
                           port=mail_config.get('port', 587),
                           loop=loop)
    await smtp.connect()
    await smtp.starttls()
    await smtp.login(mail_user, mail_password)
    return smtp
Exemplo n.º 22
0
 async def delivery(self, mailfrom, rcpttos, data):
     async with aiosmtplib.SMTP(hostname=server, port=port,
                                use_tls=False) as smtp:
         await smtp.ehlo()
         await smtp.starttls()
         await smtp.login(username, password)
         await smtp.sendmail(mailfrom, rcpttos, data)
         log.info(f'Mail has been successfully sent to {rcpttos}')
Exemplo n.º 23
0
def application(loop):
    app = aiohttp.web.Application(loop=loop)
    app.router.add_post('/', create_handler(
        lambda: aiohttp.ClientSession(loop=loop),
        # TODO: remove use_tls=False if we won't use starttls
        lambda: aiosmtplib.SMTP(hostname=SMTP_HOSTNAME, port=SMTP_PORT, loop=loop, use_tls=False),
    ))
    return app
Exemplo n.º 24
0
async def send_email(message: MIMEText):
    smtp_client = aiosmtplib.SMTP(hostname=MAIL_SERVER,
                                  port=587,
                                  use_tls=False)
    await smtp_client.connect()
    await smtp_client.starttls()
    await smtp_client.login(MAIL_USERNAME, MAIL_PASSWORD)
    await smtp_client.send_message(message)
    await smtp_client.quit()
Exemplo n.º 25
0
 async def stmp_connection(app, loop):
     self.smtp = aiosmtplib.SMTP(loop=loop,
                                 hostname=app.config.MAIL_SEND_HOST,
                                 port=app.config.MAIL_SEND_PORT,
                                 use_tls=app.config.MAIL_TLS)
     await self.smtp.connect()
     await self.smtp.login(app.config.MAIL_SENDER,
                           app.config.MAIL_SENDER_PASSWORD)
     logger.info("[SanicMail] smtp connected !")
Exemplo n.º 26
0
async def send_hello_world():
    smtp_client = aiosmtplib.SMTP(hostname=SERVER, port=PORT, use_tls=False)
    await smtp_client.connect()
    await smtp_client.ehlo()
    await smtp_client.starttls()
    await smtp_client.ehlo()
    await smtp_client.login(username=LOGIN, password=PASSWORD)
    await smtp_client.send_message(msg)
    await smtp_client.quit()
Exemplo n.º 27
0
async def send_message(task_state: dto.TaskState, smtpconf: SMTPConfig, message_body):
    message = MIMEText(message_body)
    message["From"] = "*****@*****.**"
    message["To"] = task_state.email
    message["Subject"] = "Md5 calculation result"

    async with aiosmtplib.SMTP(
        hostname=smtpconf.host, port=smtpconf.port, loop=asyncio.get_event_loop()
    ) as smtp:
        await smtp.send_message(message)
Exemplo n.º 28
0
    async def connect(self):
        client = aiosmtplib.SMTP(timeout=self.timeout)
        await client.connect(hostname=self.host, port=self.port)
        if self.use_tls:
            await client.starttls()

        if self.username:
            await client.login(self.username, self.password)

        return client
Exemplo n.º 29
0
async def send(send_to, msg):
    server = aiosmtplib.SMTP("smtp.gmail.com")
    await server.connect()
    await server.ehlo()
    await server.starttls()
    await server.ehlo()
    await server.login(EMAIL_USER, EMAIL_PASSWORD)
    await server.sendmail("*****@*****.**", [send_to], msg)
    server.close()
    print("Email sent succesfully")
Exemplo n.º 30
0
 def __init__(self, host: str, port: int, user: str, password: str) -> None:
     self._host = host
     self._port = port
     self._user = user
     self._password = password
     self._server = aiosmtplib.SMTP(
         self._host,
         self._port,
         use_tls=True,
         tls_context=ssl.create_default_context(),
     )