flexget.plugins.output.send_email
Covered: 93 lines
Missed: 68 lines
Skipped 42 lines
Percent: 57 %
  1
import logging
  2
import smtplib
  3
import socket
  4
from email.message import Message
  5
from smtplib import SMTPException
  6
from flexget.plugin import PluginError, PluginWarning, register_plugin
  8
log = logging.getLogger('email')
 11
class OutputEmail(object):
 13
    """
 14
    Send an e-mail with the list of all succeeded (downloaded) entries.
 16
    Configuration options
 18
    ===============  ===================================================================
 19
    Option           Description
 20
    ===============  ===================================================================
 21
    from             The email address from which the email will be sent (required)
 22
    to               The email address of the recipient (required)
 23
    smtp_host        The host of the smtp server
 24
    smtp_port        The port of the smtp server
 25
    smtp_username    The username to use to connect to the smtp server
 26
    smtp_password    The password to use to connect to the smtp server
 27
    smtp_tls         Should we use TLS to connect to the smtp server
 28
    smtp_ssl         Should we use SSL to connect to the smtp server
 29
                     Due to a bug in python, this only works in python 2.6.3 and up
 30
    active           Is this plugin active or not
 31
    ===============  ===================================================================
 33
    Config basic example::
 35
      email:
 36
        from: xxx@xxx.xxx
 37
        to: xxx@xxx.xxx
 38
        smtp_host: smtp.host.com
 40
    Config example with smtp login::
 42
      email:
 43
        from: xxx@xxx.xxx
 44
        to: xxx@xxx.xxx
 45
        smtp_host: smtp.host.com
 46
        smtp_port: 25
 47
        smtp_login: true
 48
        smtp_username: my_smtp_login
 49
        smtp_password: my_smtp_password
 50
        smtp_tls: true
 52
    Config multi-feed example::
 54
      global:
 55
        email:
 56
          from: xxx@xxx.xxx
 57
          to: xxx@xxx.xxx
 58
          smtp_host: smtp.host.com
 60
      feeds:
 61
        feed1:
 62
          rss: http://xxx
 63
        feed2:
 64
          rss: http://yyy
 65
          email:
 66
            active: False
 67
        feed3:
 68
          rss: http://zzz
 69
          email:
 70
            to: zzz@zzz.zzz
 72
    GMAIL example::
 74
      from: from@gmail.com
 75
      to: to@gmail.com
 76
      smtp_host: smtp.gmail.com
 77
      smtp_port: 587
 78
      smtp_login: true
 79
      smtp_username: gmailUser
 80
      smtp_password: gmailPassword
 81
      smtp_tls: true
 83
    Default values for the config elements::
 85
      email:
 86
        active: True
 87
        smtp_host: localhost
 88
        smtp_port: 25
 89
        smtp_login: False
 90
        smtp_username:
 91
        smtp_password:
 92
        smtp_tls: False
 93
        smtp_ssl: False
 94
    """
 96
    def validator(self):
 97
        from flexget import validator
 98
        email = validator.factory('dict')
 99
        email.accept('boolean', key='active')
100
        email.accept('text', key='to', required=True)
101
        email.accept('list', key='to', required=True).accept('text')
102
        email.accept('text', key='from', required=True)
103
        email.accept('text', key='smtp_host')
104
        email.accept('integer', key='smtp_port')
105
        email.accept('boolean', key='smtp_login')
106
        email.accept('text', key='smtp_username')
107
        email.accept('text', key='smtp_password')
108
        email.accept('boolean', key='smtp_tls')
109
        email.accept('boolean', key='smtp_ssl')
110
        return email
112
    def get_config(self, feed):
113
        config = feed.config['email']
114
        config.setdefault('active', True)
115
        config.setdefault('smtp_host', 'localhost')
116
        config.setdefault('smtp_port', 25)
117
        config.setdefault('smtp_login', False)
118
        config.setdefault('smtp_username', '')
119
        config.setdefault('smtp_password', '')
120
        config.setdefault('smtp_tls', False)
121
        config.setdefault('smtp_ssl', False)
122
        if not isinstance(config['to'], list):
123
            config['to'] = [config['to']]
124
        return config
126
    def on_feed_output(self, feed):
127
        """Count the email as an output"""
129
    def on_feed_exit(self, feed):
130
        """Send email at exit."""
131
        config = self.get_config(feed)
133
        if not config['active']:
134
            return
137
        if feed.manager.options.learn:
138
            return
141
        if not feed.accepted:
142
            return
145
        entries_count = len(feed.accepted)
146
        subject = '[FlexGet] %s : %d new entries downloaded' % (feed.name, entries_count)
147
        content = (u'Hi,\n'
148
                    'FlexGet has just downloaded %d new entries for feed %s :' % (entries_count, feed.name))
150
        for entry in feed.accepted:
151
            content += "\n - %s (%s)" % (entry['title'], entry['url'])
152
            entry_path = entry.get('path', feed.config.get('download'))
153
            entry_filename = entry.get('filename', entry['title'])
154
            if entry_path:
155
                content += " => %s (%s)" % (entry_path, entry_filename)
157
        content += "\n\n"
160
        message = Message()
161
        message['To'] = ','.join(config['to'])
162
        message['From'] = config['from']
163
        message['Subject'] = subject
164
        message.set_payload(content.encode('utf-8'))
165
        message.set_charset('utf-8')
168
        if feed.manager.options.test:
169
            log.info('Would send email : %s' % message.as_string())
170
        else:
171
            try:
172
                if config['smtp_ssl']:
173
                    import sys
174
                    if sys.version_info < (2, 6, 3):
175
                        raise PluginError('SSL email support requires python >= 2.6.3 due to python bug #4066, upgrade python or use TLS', log)
177
                    mailServer = smtplib.SMTP_SSL(config['smtp_host'], config['smtp_port'])
178
                else:
179
                    mailServer = smtplib.SMTP(config['smtp_host'], config['smtp_port'])
180
                    if config['smtp_tls']:
181
                        mailServer.ehlo()
182
                        mailServer.starttls()
183
            except socket.error, e:
184
                raise PluginWarning('Socket error: %s' % e, log)
185
            except SMTPException, e:
187
                raise PluginWarning('Unable to send email: %s' % e, log)
189
            try:
191
                if config.get('smtp_username') and config.get('smtp_password'):
192
                    mailServer.login(config['smtp_username'], config['smtp_password'])
193
                mailServer.sendmail(message['From'], config['to'], message.as_string())
194
            except IOError, e:
196
                raise PluginWarning('Unable to send email! IOError: %s' % e, log)
197
            except SMTPException, e:
198
                raise PluginWarning('Unable to send email! SMTPException: %s' % e, log)
200
            mailServer.quit()
202
register_plugin(OutputEmail, 'email')