Example #1
0
def _mail_payload(msg, mail_from, recipient_email):
    # Send the email using Python's smtplib.
    smtp_connection = smtplib.SMTP()
    if 'smtp.test_server' in config:
        # If 'smtp.test_server' is configured we assume we're running tests,
        # and don't use the smtp.server, starttls, user, password etc. options.
        smtp_server = config['smtp.test_server']
        smtp_starttls = False
        smtp_user = None
        smtp_password = None
    else:
        smtp_server = config.get('smtp.server', 'localhost')
        smtp_starttls = asbool(
            config.get('smtp.starttls'))
        smtp_user = config.get('smtp.user')
        smtp_password = config.get('smtp.password')

    try:
        smtp_connection.connect(smtp_server)
    except socket.error as e:
        log.exception(e)
        raise MailerException('SMTP server could not be connected to: "%s" %s'
                              % (smtp_server, e))
    try:
        # Identify ourselves and prompt the server for supported features.
        smtp_connection.ehlo()

        # If 'smtp.starttls' is on in CKAN config, try to put the SMTP
        # connection into TLS mode.
        if smtp_starttls:
            if smtp_connection.has_extn('STARTTLS'):
                smtp_connection.starttls()
                # Re-identify ourselves over TLS connection.
                smtp_connection.ehlo()
            else:
                raise MailerException("SMTP server does not support STARTTLS")

        # If 'smtp.user' is in CKAN config, try to login to SMTP server.
        if smtp_user:
            assert smtp_password, ("If smtp.user is configured then "
                                   "smtp.password must be configured as well.")
            smtp_connection.login(smtp_user, smtp_password)

        smtp_connection.sendmail(mail_from, [recipient_email], msg.as_string())
        log.info("Sent email to {0}".format(recipient_email))

    except smtplib.SMTPException as e:
        msg = '%r' % e
        log.exception(msg)
        raise MailerException(msg)
    finally:
        smtp_connection.quit()
Example #2
0
def mail_recipient(recipients_list,
                   subject,
                   body,
                   sender_name='Humanitarian Data Exchange (HDX)',
                   sender_email='*****@*****.**',
                   cc_recipients_list=None,
                   bcc_recipients_list=None,
                   footer=None,
                   headers={},
                   reply_wanted=False,
                   snippet='email/email.html',
                   file=None):
    if recipients_list is None and bcc_recipients_list is None:
        raise MailerException('There are no recipients to send email')
    return _mail_recipient_html(sender_name,
                                sender_email,
                                recipients_list,
                                subject,
                                content_dict=body,
                                cc_recipients_list=cc_recipients_list,
                                bcc_recipients_list=bcc_recipients_list,
                                footer=footer,
                                headers=headers,
                                reply_wanted=reply_wanted,
                                snippet=snippet,
                                file=file)
Example #3
0
    def test_request_reset_but_mailer_not_configured(self, send_reset_link,
                                                     app):
        user = factories.User()

        offset = url_for("user.request_reset")
        # This is the exception when the mailer is not configured:
        send_reset_link.side_effect = MailerException(
            'SMTP server could not be connected to: "localhost" '
            "[Errno 111] Connection refused")
        response = app.post(offset, data=dict(user=user["name"]))

        assert "Error sending the email" in response
Example #4
0
    def test_request_reset_but_mailer_not_configured(self, send_reset_link):
        user = factories.User()
        app = self._get_test_app()
        offset = url_for('user.request_reset')
        # This is the exception when the mailer is not configured:
        send_reset_link.side_effect = MailerException(
            'SMTP server could not be connected to: "localhost" '
            '[Errno 111] Connection refused')
        response = app.post(offset, params=dict(user=user['name']),
                            status=302).follow()

        assert_in('Error sending the email', response)
Example #5
0
    def test_request_reset_mailer_exception(self, mock_mail_user):
        mock_mail_user.side_effect = MailerException("bad things happened")

        user = factories.User(email="*****@*****.**")
        app = self._get_test_app()
        response = app.post(
            url=url_for("user.request_reset"),
            params={u"user": u"*****@*****.**"},
            status=200,
        )

        self.assertIn("Could not send reset link", response.body)
        self.assertTrue(mock_mail_user.called)
Example #6
0
    def test_request_reset_display_error_on_smtp_problem(
            self, send_reset_link, app):
        # given:
        user = ckan.tests.factories.User()

        # when:
        offset = url_for("user.request_reset")
        # This is the exception when the mailer is not configured:
        send_reset_link.side_effect = MailerException(
            'SMTP server could not be connected to: "localhost" '
            "[Errno 111] Connection refused")
        test_response = app.post(offset, data=dict(user=user["name"]))

        # then:
        _assert_in_body(
            "Error sending the email. Try again later or contact an administrator for help",
            test_response)
Example #7
0
def mail_recipient(recipients_list,
                   subject,
                   body,
                   sender_name='HDX',
                   sender_email=None,
                   bcc_recipients_list=None,
                   footer=None,
                   headers={}):
    if recipients_list is None and bcc_recipients_list is None:
        raise MailerException('There are no recipients to send email')
    return _mail_recipient(recipients_list,
                           subject,
                           body,
                           sender_name,
                           bcc_recipients_list=bcc_recipients_list,
                           footer=footer,
                           headers=headers,
                           sender_email=sender_email)
Example #8
0
def restricted_user_create_and_notify(context, data_dict):

    def body_from_user_dict(user_dict):
        body = ''
        for key, value in user_dict.items():
            body += '* {0}: {1}\n'.format(
                key.upper(), value if isinstance(value, str) else str(value))
        return body

    user_dict = user_create(context, data_dict)

    # Send your email, check ckan.lib.mailer for params
    try:
        name = _('CKAN System Administrator')
        email = config.get('email_to')
        if not email:
            raise MailerException('Missing "email-to" in config')

        subject = _('New Registration: {0} ({1})').format(
            user_dict.get('name', _(u'new user')), user_dict.get('email'))

        extra_vars = {
            'site_title': config.get('ckan.site_title'),
            'site_url': config.get('ckan.site_url'),
            'user_info': body_from_user_dict(user_dict)}

        body = render_jinja2(
            'restricted/emails/restricted_user_registered.txt', extra_vars)

        mail_recipient(name, email, subject, body)

    except MailerException as mailer_exception:
        log.error('Cannot send mail after registration')
        log.error(mailer_exception)

    return (user_dict)
Example #9
0
def restricted_user_create_and_notify(context, data_dict):
    def body_from_user_dict(user_dict):
        body = u'\n'
        for key, value in user_dict.items():
            body += ' \t - ' + key.upper() + ': ' + (
                value if type(value) == str else unicode(value)) + '\n'
        return body

    user_dict = user_create(context, data_dict)

    # Send your email, check ckan.lib.mailer for params
    try:
        name = 'CKAN System Administrator'
        email = config.get('email_to')
        if not email:
            raise MailerException('Missing "email-to" in config')

        subject = u'New Registration: ' + user_dict.get(
            'name', 'new user') + ' (' + user_dict.get('email') + ')'

        extra_vars = {
            'site_title': config.get('ckan.site_title'),
            'site_url': config.get('ckan.site_url'),
            'user_info': body_from_user_dict(user_dict)
        }
        body = render_jinja2(
            'restricted/emails/restricted_user_registered.txt', extra_vars)

        mail_recipient(name, email, subject, body)

    except MailerException as mailer_exception:
        log.error("Cannot send mail after registration ")
        log.error(mailer_exception)
        pass

    return (user_dict)
Example #10
0
def _mail_recipient_html(sender_name='Humanitarian Data Exchange (HDX)',
                         sender_email='*****@*****.**',
                         recipients_list=None,
                         subject=None,
                         content_dict=None,
                         cc_recipients_list=None,
                         bcc_recipients_list=None,
                         footer=True,
                         headers={},
                         reply_wanted=False,
                         snippet='email/email.html',
                         file=None):

    if sender_email:
        mail_from = sender_email
    else:
        mail_from = config.get(
            'hdx_smtp.mail_from_please_reply') if reply_wanted else config.get(
                'smtp.mail_from')

    template_data = {
        'data': {
            'data': content_dict,
            'footer': footer,
            '_snippet': snippet
        },
    }
    body_html = mailer.render_jinja2('email/email.html', template_data)

    # msg = MIMEMultipart('alternative')
    msg = MIMEMultipart()
    for k, v in headers.items():
        msg[k] = v
    subject = Header(subject.encode('utf-8'), 'utf-8')
    msg['Subject'] = subject
    msg['From'] = _(u"%s <%s>") % (sender_name, mail_from)
    recipient_email_list = []
    recipients = None
    if recipients_list:
        for r in recipients_list:
            email = r.get('email')
            recipient_email_list.append(email)
            display_name = r.get('display_name')
            if display_name:
                recipient = u"%s <%s>" % (display_name, email)
            else:
                recipient = u"%s" % email
            # else:
            # no recipient list provided
            recipients = ', '.join([recipients, recipient
                                    ]) if recipients else recipient

    msg['To'] = Header(recipients, 'utf-8')
    if bcc_recipients_list:
        for r in bcc_recipients_list:
            recipient_email_list.append(r.get('email'))
    cc_recipients = None
    if cc_recipients_list:
        for r in cc_recipients_list:
            recipient_email_list.append(r.get('email'))
            cc_recipient = u"%s <%s>" % (r.get('display_name'), r.get('email'))
            cc_recipients = ', '.join([cc_recipients, cc_recipient
                                       ]) if cc_recipients else cc_recipient
        msg['Cc'] = cc_recipients if cc_recipients else ''

    msg['Date'] = Utils.formatdate(time())
    msg['X-Mailer'] = "CKAN %s" % ckan.__version__
    if sender_email:
        msg['Reply-To'] = Header((u"%s <%s>" % (sender_name, sender_email)),
                                 'utf-8')
    part = MIMEText(body_html, 'html', 'utf-8')
    msg.attach(part)

    if isinstance(file, cgi.FieldStorage):
        _part = MIMEBase('application', 'octet-stream')
        _part.set_payload(file.file.read())
        Encoders.encode_base64(_part)
        extension = file.filename.split('.')[-1]
        header_value = 'attachment; filename=attachment.{0}'.format(extension)
        _part.add_header('Content-Disposition', header_value)
        msg.attach(_part)

    # Send the email using Python's smtplib.
    smtp_connection = smtplib.SMTP()
    if 'smtp.test_server' in config:
        # If 'smtp.test_server' is configured we assume we're running tests,
        # and don't use the smtp.server, starttls, user, password etc. options.
        smtp_server = config['smtp.test_server']
        smtp_starttls = False
        smtp_user = None
        smtp_password = None
    else:
        smtp_server = config.get('smtp.server', 'localhost')
        smtp_starttls = paste.deploy.converters.asbool(
            config.get('smtp.starttls'))
        smtp_user = config.get('smtp.user')
        smtp_password = config.get('smtp.password')
    smtp_connection.connect(smtp_server)
    try:
        # smtp_connection.set_debuglevel(True)

        # Identify ourselves and prompt the server for supported features.
        smtp_connection.ehlo()

        # If 'smtp.starttls' is on in CKAN config, try to put the SMTP
        # connection into TLS mode.
        if smtp_starttls:
            if smtp_connection.has_extn('STARTTLS'):
                smtp_connection.starttls()
                # Re-identify ourselves over TLS connection.
                smtp_connection.ehlo()
            else:
                raise MailerException("SMTP server does not support STARTTLS")

        # If 'smtp.user' is in CKAN config, try to login to SMTP server.
        if smtp_user:
            assert smtp_password, ("If smtp.user is configured then "
                                   "smtp.password must be configured as well.")
            smtp_connection.login(smtp_user, smtp_password)

        smtp_connection.sendmail(mail_from, recipient_email_list,
                                 msg.as_string())
        log.info("Sent email to provided list of recipients")

    except smtplib.SMTPException, e:
        msg = '%r' % e
        log.exception(msg)
        raise MailerException(msg)
Example #11
0
def send_state_change_notifications(members, email_dict, sender_name,
                                    sender_url):
    '''
    Sends state change notifications to sub-org members.
    Updated by Khalegh Mamakani on March 5 2015.
    List of changes :
        - Creating the smtp connection once for all notifications instead of connecting and disconnecting for
          every single recipient.
        - Using a thread to send the notifications in the background.
    '''

    # Email common fields
    subject = email_dict['subject']

    mail_from = config.get('smtp.mail_from')
    subject = Header(subject.encode('utf-8'), 'utf-8')

    # Connecting to smtp server.
    smtp_connection = smtplib.SMTP()
    if 'smtp.test_server' in config:
        # If 'smtp.test_server' is configured we assume we're running tests,
        # and don't use the smtp.server, starttls, user, password etc. options.
        smtp_server = config['smtp.test_server']
        smtp_starttls = False
        smtp_user = None
        smtp_password = None
    else:
        smtp_server = config.get('smtp.server', 'localhost')
        smtp_starttls = paste.deploy.converters.asbool(
            config.get('smtp.starttls'))
        smtp_user = config.get('smtp.user')
        smtp_password = config.get('smtp.password')
    smtp_connection.connect(smtp_server)
    try:

        # Identify ourselves and prompt the server for supported features.
        smtp_connection.ehlo()

        # If 'smtp.starttls' is on in CKAN config, try to put the SMTP
        # connection into TLS mode.
        if smtp_starttls:
            if smtp_connection.has_extn('STARTTLS'):
                smtp_connection.starttls()
                # Re-identify ourselves over TLS connection.
                smtp_connection.ehlo()
            else:
                raise MailerException("SMTP server does not support STARTTLS")

        # If 'smtp.user' is in CKAN config, try to login to SMTP server.
        if smtp_user:
            assert smtp_password, ("If smtp.user is configured then "
                                   "smtp.password must be configured as well.")
            smtp_connection.login(smtp_user, smtp_password)
        '''
        Adding extra email fields and Sending notification for each individual member.
        '''

        for member in members:
            if member.email:
                body = email_dict['body']
                msg = MIMEText(body.encode('utf-8'), 'html', 'utf-8')
                msg['Subject'] = subject
                msg['From'] = "%s <%s>" % (sender_name, mail_from)
                msg['Date'] = Utils.formatdate(time())
                recipient_email = member.email
                recipient_name = member.fullname or member.name
                body = add_msg_niceties(recipient_name, body, sender_name,
                                        sender_url)
                recipient = u"%s <%s>" % (recipient_name, recipient_email)
                msg['To'] = Header(recipient, 'utf-8')
                try:
                    smtp_connection.sendmail(mail_from, [recipient_email],
                                             msg.as_string())
                    log.info(
                        "Sent state change email to user {0} with email {1}".
                        format(recipient_name, recipient_email))
                except Exception, e:
                    log.error(
                        'Failed to send notification to user {0} email address : {1}'
                        .format(recipient_email, recipient_email))

    except smtplib.SMTPException, e:
        msg = '%r' % e
        log.exception(msg)
        log.error('Failed to connect to smtp server')
Example #12
0
def _mail_recipient(recipients_list,
                    subject,
                    body,
                    sender_name,
                    bcc_recipients_list=None,
                    footer=None,
                    headers={},
                    sender_email=None):
    mail_from = config.get('smtp.mail_from')
    body = add_msg_niceties(body=body, footer=footer)
    msg = MIMEMultipart('alternative')
    for k, v in headers.items():
        msg[k] = v
    subject = Header(subject.encode('utf-8'), 'utf-8')
    msg['Subject'] = subject
    msg['From'] = _(u"%s <%s>") % (sender_name, mail_from)
    recipient_email_list = []
    recipient = u""
    if recipients_list:
        for r in recipients_list:
            email = r.get('email')
            recipient_email_list.append(email)
            display_name = r.get('display_name')
            if (display_name):
                recipient += u"%s <%s> , " % (display_name, email)
            else:
                recipient += u"%s , " % (email)
            # else:
            # no recipient list provided

    msg['To'] = Header(recipient, 'utf-8')
    if bcc_recipients_list:
        for r in bcc_recipients_list:
            recipient_email_list.append(r.get('email'))
    msg['Date'] = Utils.formatdate(time())
    msg['X-Mailer'] = "CKAN %s" % ckan.__version__
    if sender_email:
        msg['Reply-To'] = Header((u"%s <%s>" % (sender_name, sender_email)),
                                 'utf-8')
    part = MIMEText(body, 'html', 'utf-8')
    msg.attach(part)

    # Send the email using Python's smtplib.
    smtp_connection = smtplib.SMTP()
    if 'smtp.test_server' in config:
        # If 'smtp.test_server' is configured we assume we're running tests,
        # and don't use the smtp.server, starttls, user, password etc. options.
        smtp_server = config['smtp.test_server']
        smtp_starttls = False
        smtp_user = None
        smtp_password = None
    else:
        smtp_server = config.get('smtp.server', 'localhost')
        smtp_starttls = paste.deploy.converters.asbool(
            config.get('smtp.starttls'))
        smtp_user = config.get('smtp.user')
        smtp_password = config.get('smtp.password')
    smtp_connection.connect(smtp_server)
    try:
        # smtp_connection.set_debuglevel(True)

        # Identify ourselves and prompt the server for supported features.
        smtp_connection.ehlo()

        # If 'smtp.starttls' is on in CKAN config, try to put the SMTP
        # connection into TLS mode.
        if smtp_starttls:
            if smtp_connection.has_extn('STARTTLS'):
                smtp_connection.starttls()
                # Re-identify ourselves over TLS connection.
                smtp_connection.ehlo()
            else:
                raise MailerException("SMTP server does not support STARTTLS")

        # If 'smtp.user' is in CKAN config, try to login to SMTP server.
        if smtp_user:
            assert smtp_password, ("If smtp.user is configured then "
                                   "smtp.password must be configured as well.")
            smtp_connection.login(smtp_user, smtp_password)

        smtp_connection.sendmail(mail_from, recipient_email_list,
                                 msg.as_string())
        log.info("Sent email to provided list of recipients")

    except smtplib.SMTPException, e:
        msg = '%r' % e
        log.exception(msg)
        raise MailerException(msg)